Part IV: Introduction to the Java Syntax

By | February 9, 2021

Table of Contents

Before we start to cover the basic syntax of programming with Java, I just want to mention a couple of things that can be good to keep in mind when you embark on your programming journey with Java :)

Semi-colons in Java and their function

In Java you need to place a semi-colon after each and every statement in your code to indicate that your statement is complete, like so:

int numberVar = 5;

If you were to ignore this, and try to write your code without “finishing” your statements, usually the Java editor of your choice will probably not run the code but instead present you with an error code. You could think of it like that the compiler that would interpret and run your program code, would not know when to stop and actually do something with your code, but might instead try to continue interpreting and make sense of too much information that doesn’t make sense at all until it reaches a semi-colon.

So if you want to write successful Java code, remember the semi-colons at the end of each and every line of code/statement that you write.

Import external libraries to use in your Java program for extended functionality

Java is full of useful source code libraries where a lot of functionality already have been coded by other people, for you to re-use in your program – so that you don’t have to code the functionality yourself.

Some libraries are already included in JRE by default (for example String, Math) but for your program to know what classes with source code to include into your program (that are not included by default), without you having to write out the full path to the class, you can use the Java import statement to let your program know what libraries you intend to use so that you don’t have to write out the full path to the library class with code everywhere in your program where you might need to use an external libraries source code.

See the contrast example below:

// Example with import statement:
import java.util.Scanner;

public class DemoProgram {

   public static void main(String[] args) {

      Scanner scan = new Scanner(System.in);
   }
}

// Example without the import statement:
public class DemoProgram {
   public static void main(String[] args) {
      java.util.Scanner scan = new java.util.Scanner(System.in);
   }
}

See how much easier it becomes to use a library in Java when importing the reference at the top of your class file? :)

You could think of it as not having to re-invent the wheel since someone else has already done it for you, and only reason for you to do it is to improve upon the previous design and add further value to it.

A few of these libraries which we will be using in a lot of our code examples include:

  • Java Math library for arithmetic operations
  • Java DecimalFormat library for controlling amount of decimals we work with for floating point values
  • Java String library to handle text strings (combinations of character data types and programmed operations on them)
  • Java Scanner library to listen to – and collect user input into our programs
  • Java Swing library for graphical user interface components
  • Java Date utility to manage datetime data
  • Java Event library for event listeners for interfaces

… to mention a few.

There are two popular ways of declaring what external library and its class references should be imported into our program, one is to specifically define the exact pathway to that Java library you wish to include into your project and use in your program.

The other way is to include multiple libraries by using shortcut pathway to include ALL libraries within the common folder where all libraries of a certain type (Utility for example) is gathered.

See below examples:

// Specific and exact pathway:
import java.util.Scanner;

// Generalized and more inclusive pathway:
import java.util.*;

If you come from a background of developing websites you might be familiar with the concept of increased loadtime and decreased performance of a website the more libraries are loaded into the website, however it seems this is not quite the case for Java programming, according to this interesting Stackoverflow post about the subject.

Notice how we use the star character (*) to include everything that exist in the util “folder”. Using the star character (*) to symbolize “Everything” is very common in programming, regardless of the context so its good to get used to :)

Both ways will work.

Variables in Java

Variables and member variables in Java and how to create and use them

Variables in Java intro

Variables in Java are sort of references with nametags that you define which will reference your data stored in your computers RAM that you will be working with in your programs.

Variables can be of different types to “hold” different types of values, and they are usually restricted to how much of a certain type of data the variable can hold – hence various data types.

If we were to get truly technical about it, a variable is a nametagged placeholder that refers to a certain slot in the computers RAM-memory which is used when running a computer program to hold temporary data.

Different variable types have different technical specifications, see the table below:

Variable type Data storage capacity
byte 8 bit (values can range from -128 minimum value to 127 maximum value
short 16-bit (values can range from -32’768 minimum value to 32’767 maximum value)
int 32-bit (values can range from -2’147’483’648 (-2^31) value to 2’147’483’647 (2^31 -1)
long 64-bit (values can range from -9’223’372’036’854’775’808 (-2^63) value to 9’223’372’036’854’775’807 (2^63 -1))

Think about the above table, each and every time you declare an integer varible, you will allocate 32-bit of your RAM memory (4 bytes), even if you are not going to use all of it.

Thats where byte and short comes in to save you some of that memory allocation and help make your programs more efficient (this is not as important when starting out your programming journey such as when you create larger and more complex programs later on).

This also means that if you exceed the capacity of your variable, you can either get error messages, or in worst case faulty data in your program.

Check this out for more information about how to know the capacity of variables that store floating point information (float and double)

If you need to store precise floating point information you should avoid using both float and double and instead use a specially designed library to represent floating point information accurately like the Java class BigDecimal. More information about this and round-off errors in Java later in this article.

Each char variable that represents each character in Java has a capacity to store a 16-bit Unicode character – the String class in Java works with char data type so you don’t have to, but imagine how much data is required to represent text if 1 single character takes up 16-bit of storage capacity.

So when you create a variable, what you do is that you reserve space in your computers RAM memory which should be allocated with a certain amount of data/information. So each time you call on a variable it will fetch your data that it references in your RAM memory of your computer.

This is why in C++ with manual garbage collection, you should delete variables that are done being used to free up RAM memory space in your program to make it possibly faster and more efficient, compared to in Java where it has automatic “garbage collection” which will detect on its own, when it thinks something is no longer needed, and then clear it from the RAM (less control, but less effort also for the programmer).

Various ways of creating variables and how to use them in Java explained

The type of variable can be:

  • integer (int)
  • floating point (double/float)
  • text (String)
  • true/false (boolean)
  • character (char)
  • class (String for example)
  • … or other

These types listed above are some of the most common variable types in Java. With their help you can create complex programs that can handle many different operations.

So then, how can we use our variables you might ask? Well, once a variable has been created we can then use our variable in various logical operations in our program – such as:

  • doing arithmetic (calculations)
  • or create full sentences
  • switch a check of something from true to false and vice versa
  • count iterations of loops
  • store banking information temporarily until it can be permanently stored in either file or database
  • etc.

There are tons of operations we can do with our variables, to demonstrate a few, see below:

// Calculate the sum of 2 numbers that are stored in two separate integer variables, store the sum in another integer variable
int sum = 0;
int numberOne = 5;
int numberTwo = 10;
sum = numberOne + numberTwo;
// After these operations, our variable "sum" will contain the sum of 15 (10+5)

// Build a sentence using multiple separate String variables
String stringOne = "";
String stringTwo = "";
String stringThree = "";
String combinedString = stringOne + stringTwo + stringThree;

// Determine action based on whether boolean is true or false
int aNumber = 5;
boolean lessThan = false;

if(aNumber < 5) {
   lessThan = true;
}else if(aNumber > 5) {
   lessThan = false;
}

if(lessThan == false) {
   System.out.println("aNumber was NOT less than 5.");
}else if(lessThan == true) {
   System.out.println("aNumber WAS less than 5!");
}

// Creating an object (instance) of the class Scanner and use it in a program
Scanner scan = new Scanner(System.in);

int userInput = scan.nextInt(); // Calling the method of Scanner class: nextInt() using "dot-notation" (.) - dot-notation can also be used to call on variables of a class

// Using floating point variables
double decimalValue1 = 0.5;
double decimalValue2 = 0.3;

double result = decimalValue1 - decimalValue2;

// If we were to only write:
int number; // This is a variable declaration
// But when we give the variable a value, we initialize it, like so:
number = 0;

Member variables in Java explained

Member variables are variables that belong to a specific class – they are members of a class.

What is null in Java

Null is a default value that can be set for objects in Java (instances of classes), much like 0 is the default value for any integer variable.

Null is the definition of an undefined value that is acceptable and can be used as default value for any object of a class in Java.

For example if an object in a program has not yet been set, an if-statement to check if the object variable has the value of null could determine if it has been set or not.

It’s a bit like Yin and Yang, if you have a possibility of setting values to a variable, you also have to have the possibility that no value has been set yet to a variable – without it breaking the program.

Object variables in Java as instances of classes

Object variables are variables that hold an instance of a specific class which is called an object of that class.

Imagine you have a blueprint that describes how you can manufacture a certain toy. Every toy that then is manufactured from that blueprint is then an object as a result of that blueprint (class).

The blueprint might have mentioned that our toy should have the color green and be able to do a certain task. So then every toy (object) that we create from this blueprint (class) will have the color green and be able to do that certain task.

We say that our object that was created, was created as an instance of our class.

The variable that represents our object of a certain class can then be used to access variables and methods of that specific class. See below example:

public class ObjectDemo {

   public static void main(String[] args) {
      Car aCar = new Car(); // Creates an instance (object) of our Car class, which we call "aCar" for future reference in our program
      aCar.getTopSpeed(); // Will return the topSpeed of our aCar object which is an instance of our Car class
      aCar.startEngine(); // Will start the engine of the car
      aCar.getModel(); // Will tell us what model our car is
   }

   public class Car() {
      // Class member variables:
      int topSpeed;
      String model;

      // Constructor
      public Car() { // This is the class constructor - this method will be run each time an instance (object) of our class is created
         this.topSpeed = 300; // Each time an instance (object) of the Car class is created we set the topSpeed value to 300
         this.model = "X57BNQ"; // Each time an instance (object) of the Car class is created we set the model value to "X57BNQ"
      }

      public void startEngine() {
         // Start the cars engine
      }

      // Getter for member variable that holds the Car class "model" value
      public String getModel() {
         return this.model;
      }

      // Getter for member variable that holds the Car class "topSpeed" value
      public int getTopSpeed() {
         return this.topSpeed;
      }
   }
}

Walkthrough of some Primitive Data Types in Java for variables (integer, double, boolean, float, char)

What is a Primitive Data Type?

Primitive data types are special data types built into the Java programming language. They are predefined and have a reserved keyword used to create them. Because of this they don’t need the new keyword to be created such as objects of classes.

There are 8 primitive data types in Java which are:

  • byte
  • short
  • integer
  • long
  • double
  • float
  • char
  • boolean

String is not technically a primitive data type, but since the Java programming language has adopted special support for Strings, it could be considered primitive.

List of all Primitive Data Types in Java (with limits/capacity)

We already covered 4 of the primitive data types of Java in a table above, so here it is again:

Variable type Data storage capacity
byte 8 bit (values can range from -128 minimum value to 127 maximum value
short 16-bit (values can range from -32’768 minimum value to 32’767 maximum value)
int 32-bit (values can range from -2’147’483’648 (-2^31) value to 2’147’483’647 (2^31 -1)
long 64-bit (values can range from -9’223’372’036’854’775’808 (-2^63) value to 9’223’372’036’854’775’807 (2^63 -1)
float 32-bit
double 64-bit
boolean At least 1 bit (true/false = 1/0), other than that it seems to be JVM dependent
char 16-bit Unicode character (ranges from value 0-65’535 – meaning it can represent 65’536 different characters total)

For default values for Java’s primitive data types see the table below:

Data Type Default value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000’
String (or any object) null
boolean false

This information is inspired from the Oracle Java documentation itself.

NaN – Not a Number value

A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero.

Quoted from Oracles Java documentation explaining floating point variable capacities.

So if you ever attempt a certain calculation which gives NaN value, this is why :)

Round-off errors in Java explained and suggested fix

Round-off errors are a result of the difficulty that the binary number system has to represent floating point (decimal) numerical values. In some cases the closest binary representation of decimal number values can come is an approximation, and when that happens, we get ourselves round-off errors in our code.

Anyone who ever listened in math class in school know that if you round something off before the calculation is 100% complete, you will always end up with an approximation or an incorrect, faulty number. This is due to the fact that every time you round something off, you lose out on details, on data, which makes something less than it actually is.

Compressing pictures in a computer is exactly the same – the more you compress something, the more data you will lose out on. Various algorithms for compressing will lose more or less valuable data depending on how they are designed.

In the case of binary representation of numerical decimal/floating point values, some values simply cannot be accurately calculated this way. It’s sort of like when your doing math yourself and want to find out what 1/3 equates to, and you will see on the calculator that you get an endless 0.33333333, and to use it in calculations, we often round this number down to 0.33. Big Java Late Object book had a great example of the problem this poses, because if you then multiply 0.33 with 3 you won’t get 100% a.k.a. 1, but instead 0.99.

The number the book uses to demonstrate this problem in Java is 4.35 which cannot be represented accurately in the binary decimal number system. Which means if you were to take 4.35 * 100, you would not get 435 as would be expected from an accurate calculation.

Another example is if we have the number 0.1 used in Java calculations, and it will also give faulty results.

There are a couple of different ways we can account for these “round-off errors” of which some are:

  • Using Math.round() function to round to the nearest integer
  • Limit the representation to a fixed set of decimal values
  • Use Java’s BigDecimal class library that will accurately represent any floating point values with the help of String-based methods

A good rule of thumb could be to always doublecheck your floating point calculations in Java using data type double or float variables to make sure that the calculations are done correctly.

Avoiding round-off errors using the BigDecimal Java class

If you want to be 100% sure for programs that might make use of user input where inputted values are unpredictable, use BigDecimal Java library class!

To demonstrate round-off errors and their suggested fixes, see below:

double a = 4.35;
double b = 100;

System.out.println(a*b); // Gives us 434.99999999999994

// Applying Math.round to round to the nearest integer:
Math.round(a*b); // Will give us 435

// Applying BigDecimal representation fix:
BigDecimal a2 = new BigDecimal("4.35");
BigDecimal b2 = new BigDecimal("100");

System.out.println(a2.multiply(b2)); // Outputs 435.00

Variable Scopes in Java explained

In Java we have 3 different types of Scopes, which mean where you can access variables depending on where in your code they were created.

  • Class Scope (member variables)
  • Local Scope (Method variables)
  • Block Scope (Loops, etc.)

So to start off with the Class Scope that is viable for any and all member variables, this means that as long as a variable is created inside of a Class brackets {} (but outside of a method), it will be available within the entire class.

When it comes to the Local Scope, this refers to variables that we create inside of our methods/functions, such variables cannot be accessed outside of said method/function!

These “local variables” also usually seize to exist after the method/function execution is completed.

When it comes to the Block Scope variables, these are variables declared inside of brackets {}. Any variable created inside of a loop will only be locally available to that loop.

Block Scope (loop) variables and Local Scope variables cannot have the same name, Java will then give error message. See example below:

int a = 2;
for(int a = 0; i < 5; i++) {
   System.out.println(a); // error variable already exist elsewhere
}

“Reserved keywords” in Java – what they are and what they mean

Reserved keywords are certain words that have a preprogrammed meaning in a programming language, for example the reserved keyword private is preprogrammed to restrict access when declaring variables, the reserved keyword int is preprogrammed to declare variables of data type integer, etc.

Reserved keywords are simply words with an embedded meaning that can be used in a programming languages syntax to accomplish various things.

They are the exception for when you can use words in your code without having to make them Strings.

If a reserved keyword were to be used in the wrong context in your program, the compiler will usually give error messages and maybe not even be able to run the program.

A good example of when you need to be aware of reserved keywords especially, is when you are naming your variables, you cannot name variables to reserved keywords, since then the compiler wont know the difference between a variable and the preprogrammed action connected with that specific reserved keyword. The compiler needs to be able to separate these two to be able to make functioning programs.

To find out more about reserved keywords in Java check this out

Constants in Java created using final reserved keyword – how to create them and when to create them

A constant variable can be declared in Java using the reserved keyword final. Declaring a constant variable in Java using the keyword final will ensure that the data held by the variable cannot be changed anywhere or at any time in your program.

When declaring constants using the final reserved keyword in Java, there is a recommendation for the order in which the reserved keywords ought to be used when declaring variables, but it doesn’t seem to be a requirement.

However you should opt to declare variables in the order defined by Oracle as their recommendation. Personally I find the order they suggest to be quite logical as well, which can help keep track of how to declare variables in an easy way every time, rather than always be confused what goes where and why.

So by following their recommendation you should always put the final keyword after the access declaration (private, protected, public) and after the static (if used), and before the data type declaration (int, double, float, etc.). See example below:

private static final int staticIntegerVariable = 10;

JVM also caches constants which can help improve performance of your program, as well as make it more readable for anyone interested now or down the line.

So use constants whenever you get the chance :)

How to specify different types of access to variables in Java (private, protected, public)

In Java you can control access to your variables by assigning reserved keywords such as:

  • private
  • protected
  • public

These reserved keywords in Java are always to be placed at the very front when declaring a member variable to define what type of access the variable should have.

The private keyword can be used to restrict access to a variable and the data it references – to only the class in which the variable is defined.

The protected keyword in contrast, will also restrict access to a variable and the data it references to the class itself where it is defined, but it will also grant access to the variable and its data to other classes that are part of the same project.

The public keyword will allow access to variables and their data from outside of the class where the variable was defined without even needing getters and setters to gain access to and manipulate the data referenced by a certain variable.

Getters and Setters are popular concepts in Java programming since they allow access and manipulation of variables that have been declared as private or protected from outside sources. Imagine you have a private variable inside of a class and in your main program you need to access the data the variable holds, you can do this then by calling the getter for that variable on the object of the class. See below example:

public class Car() {
   private int topSpeed = 300;

   // Getter for the member variable topSpeed of class Car
   public int getTopSpeed() {
      return this.topSpeed;
   }
}

public static void main(String[] args) {
   Car myCar = new Car();
   int myCarsTopSpeed = myCar.getTopSpeed(); // Using a getter to access the value stored in our member variable for topSpeed in the Car class
   int myCarsTopSpeedWOGetter = myCar.topSpeed; // This wont be allowed, since topSpeed is declared private, if public it would be.
}

Static variables in Java explained

In Java you can define so called “static variables” which will hold its value regardless of how many instances (objects) that have been created of that specific class.

As a practical example that helped me understand it when I was starting out programming in Java, imagine if you were to code a banking program, where you have a class to represent bank accounts. To be able to keep track of all of the banks bank accounts, we have created a variable (ArrayList) to store each and every account ever created.

But we also need a way to identify the various accounts, if you ever used your internet bank or done transactions between bank accounts, you know they have a unique bank account number.

So to create bank account numbers we need to use a static variable, if we wouldn’t use a static variable to keep track of our unique bank account numbers but instead a regular variable, it would be reset every time a new account is created. But with a static variable we can increment it (++) each and every time a new account is created so that the first account gets bank account number 1, second 2, third 3, etc. And the cool thing about this is that no matter how many accounts we create, we can be sure that we will get a unique bank account number if its based on our static variable.

Static means the value of the static variable is preserved regardless of instances created of a certain class. The static variable can – and will affect as well as be the same throughout all of the instances created for a certain class.

Type Conversion and Type Casting in Java

In Java it is possible to convert/cast variables of one data type, to become a variable of another data type. For example you can type cast/convert an integer to a double if it should at any point in your program be necessary.

There are differences between type casting and type conversion. Where type casting refers to when a programmer manually converts one data type into another. Whereas type conversion is done automatically by the compiler.

  • Type casting can be applied to both compatible as well as incompatible data types, whereas type conversion can only be applied to compatible data types
  • Type casting needs an operator to convert from one data type to another, whereas type conversion does not
  • In type conversion destination data type cannot be smaller than the data type being converted. Whereas in type casting it can be
  • Type casting where the programmer is in control is more efficient and reliable compared to type conversion which is not

There are also automatic type conversion in Java where you can declare a double variable and assign it an integer value to automatically convert the integer value to becoming a double in the declared double variable. See example below:

// Example of automatic type conversion:
int myNmbr = 5; // 5
double aDoubleVariable = myNmbr; // 5.0

Manual type casting also exist in Java, where you can convert a variable of one data type to another by putting the type you wish to convert to in front of your existing variable of another type. See example below:

double aDecimalNmbr = 5.68;
int myIntegerVariable = (int) aDecimalNmbr; // Gives the value 5 stored in myIntegerVariable, notice how it doesn't account for it being closer to 6 than 5

You can also convert and type cast variables from one type to another using calling upon conversion methods that are built-into wrapper classes for different data types.

For example Integer.parseInt() is part of the Integer wrapper class for our primitive data type int (for integers) and it will convert a value to become an integer. This could be seen as a sort of type transformation. But sometimes this is the way to go to make one type of variable turn into another type of variable.

Walkthrough of the String variable in Java to store and work with text

What makes String variable different from other varibles in Java

Strings are technically not a primitive data type, but since Java has adopted special support for the String class in the Java programming language, it could be thought of as a primitive data type.

The String class deals with text based on the data type for characters (char), so that we don’t have to directly. It would be quite tedious if we always had to work with char data type whenever we wanted to create something text related in Java.

If you wanted to master the data type char though, a good way of doing it could be to create your very own String class using only the char data type :) It can be quite fun and educative.

The String class also has a lot of built-in useful functionality to work with Strings. We will walk you through a few of these below.

How to create a String variable in Java

Strings can be created very similarly to how we create primitive variables, see the example below:

String aString = "My text goes here";

The only difference is that since Strings are created as objects of the String class, we need to have a capital S on String.

Concatenation: The concept of merging multiple strings into one and how it works

Using concatenation we can merge multiple strings to become one.

This is done using the “+”-sign like so:

String aString = "Hello";
String bString = " World";
String cString = "!";
String concatenatedString = aString + bString + cString; // Will contain the String "Hello World!"

// Example of concatenation where a String variable is merged with additional data not from specific variables or different types of variables
String aString = "We have ";
int myNumber = 54;
String concatenatedString = aString + myNumber + " seats available!"; // Will contain the String "We have 54 seats available!" <- Notice how the integer got automatically converted to a String

Using concatenation can be useful for when a String develops over time in your program to build a full presentation that contain calculations that are done during the program execution at various stages in the process for example.

Escaping characters in Java Strings – What it means and why its sometimes required

Escaping characters in Java can be used either to “escape” clashing characters that would otherwise cause compilation errors in your code because it confuses the compiler or they can also be used to format text with “invisible characters” such as newLine characters and Tab characters, etc. More about this in the next section.

Escaping characters can be done the same way in quite a few different programming languages as well, and its done using the backslash (\) character.

When it comes to escaping characters that are “clashing” – what I mean is, when you create a String in Java, usually you create it like so:

String str = "This is my String";

But using “” to create our String, that means we cannot use actual quotation marks as part of our Strings text content, because if we did this, the compiler that runs our program, wouldn’t know the difference from String definition, and quotation marks that are part of the actual String content, so they “clash”.

We can fix this using backslash (\) to “escape” our quotation mark that should be part of the actual String text content, like so:

String escapedString = "This is my \"escaped\" String";

If you would try writing that String in your code editor without the backslashes in front of our text content quotation marks, the compiler would complain and give you errors.

Since the backslash has such an important role in conveying additional information to the compiler regarding String formatting, in order to actually get a backslash in our String text content, this also needs to be backslashed :) See example below:

String backslashString = "This String has an actual backslash: \\"; // If there would not be 2x \\ there, the last " double quotation mark would be counted as part of the actual String text content and compiler would get confused

Escape sequences for String formatting in Java (newLine and Tab)

There are different combinations using the backslash character to define newLine and Tabs etc. that can help with formatting strings.

Basically by escaping characters we can explain to the compiler that will interpret and run our code that certain character combinations represent different purposes when it executes the code – sort of like code inside of our code.

For example using the Tab key on a keyboard, won’t create a Tab in an actual Java String, this has to be specially coded if this is whats wanted in the formatting of a String and this is done with the escape sequence \t (t for Tab).

Similarly newLine is escaped with \n <- so if you don’t feel like creating multiple System.out.println(); to create multiple lines of text output, \n can be used in 1 single  System.out.println(); statement and accomplish the same effect.

If you ever coded with HTML for websites, <br> (or <br />) is sort of the same as \n in Java String formatting :)

Sometimes you might want to format and structure your text content contained within your Strings similarly how you can using keyboard keys such as Tab and ENTER without having to use regular whitespace (spacebar) and separate System.out.println(); calls.

This can be done using escaped character sequences that emulates the behaviour of those keys. For a list of such escaped character sequences see below table:

\t TAB
\n newLine (ENTER)

Single quotation marks vs. Double quotation marks for Strings in Java

A common question that gets asked in programming is if there is a difference in using '' (single quotation marks) vs. "" (double quotation marks) when programming and defining Strings especially.

In some languages these can be interchangeable, with the difference that one might be “faster” performance-wise than the other because of how they are interpreted when the code is run or be different in some other way.

However in Java String literals a.k.a. Strings defined using the String class library are always defined using double quotation marks ("") whilst, the primitive variable for characters (char) that the String class is built on is defined using single quotation marks ('').

For more information, see this informative Stackoverflow thread explaining things.

List of useful String methods to work with Strings for everyday Java operations and how to use them

There are plenty of useful methods to work with Strings in Java, we will in this section walkthrough a chosen few that we deem to be useful and good to know how to handle and go into detail about how they work and how you can use them in practice.

Method Return
.charAt(int index) char (returns the char value at the specified index)
.contains(CharSequence cs) boolean (true/false whether CharSequence was found or not in the String)
.endsWith(String suffix) boolean (Tests if a String ends with a specified suffix-String)
.equals(String str) boolean (Returns true if a specific String matches another String object with the same character sequence)
.equalsIgnoreCase(String str) -||- (Same as above equals method, but ignores case sensitivity)
.indexOf(String str) int (Returns the index of the first occurence of the specified substring)
.indexOf(String str, int fromIndex) -||- (Same as above with the small difference that this starts to look from a specified index of the String)
.isEmpty() boolean (Returns true if and only if .length() is 0 for a String (empty of text content))
.lastIndexOf(String str) int (In contrast to above method .indexOf() this returns the last occurrence instead of the first occurrence of the search String/character (searches the String backwards/in reverse))
.lastIndexOf(String str, int fromIndex) -||- (Same as .lastIndexOf() but also same way the .indexOf() method with fromIndex, but in contrast it instead starts its search backwards/in reverse starting from the specified fromIndex)
.length() int (Returns the length of the String)
.matches(String regex) boolean (Returns true if the specific String matches the specified String pattern or regular expression)
.replace(CharSequence target, CharSequence replacement) String (Returns the new String with the target Strings replaced with the replacement Strings)
.replaceAll(String regex, String replacement) String (Returns the new String with the RegEx identified pattern matches replaced with the replacement Strings – differs from .replace() that .replaceAll() can use Regular Expressions)
.replaceFirst(String regex, String replacement) String (Returns the new String where the first occurrence of the RegEx match has been replaced with the replacement String)
.split(String regex) String[] (Splits a String on the specified RegEx/String/character and divides the different parts of the String into a String Array)
.split(String regex, int limit) -||- (Same as above .split() method with 1x input parameter with the difference of the limit integer, which serves the purpose of limiting the slots in the returned array, if limit value is -1 unlimited slots can be filled in returned array)
.startsWith(String prefix) boolean (Tests if a specific String starts with the specified prefix String)
.startsWith(String prefix, int offset) boolean (Tests if a specific String starts at the specified offset integer with the specified prefix String)
.substring(int beginIndex) String (Returns a new String that is a substring of the String .substring() method was called on, where the substring begins at the beginIndex index and continues to the end)
.substring(int beginIndex, int endIndex) String (Returns a new String that is a substring of the String the .substring() method was called on, where the substring begins at the beginIndex index and continues to the endIndex index)
.toLowerCase() String (Returns a String where all text content and characters have been transformed into lowercase characters)
.toUpperCase() String (Returns a String where all text content and characters have been transformed into Uppercase characters)
.trim() String (Returns a String without leading and trailing whitespace)

Note 1: The above methods are called on String variables – hence the dot (.) in front of them (methods part of classes are called using a dot (.) notation)!

Note 2: The bove equals method have input-parameter defined as String, technically this methods accept Any object, but since the evaluation is based on whether two different Object Strings have the same character sequence, I chose to simplify it for understandings sake :)

The charAt() String method in Java explained

So this method could be useful for when you wish to extract a single specific character from a String by specifying the index where that character can be found!

Practical example of this:

String myString = "A random string";
char specificChar = myString.charAt(0); // specificChar will get the character 'A' extracted from myString
 The contains() String method in Java explained

This is a very useful method for when you want to check if a String contains a specific “character sequence” (which could be interpreted as a part of a String).

Practical example of this could be if you are collecting information from your users, and wonder if they inputted a specific text as part of the full String, such as if the String they inputted contained profanity or perhaps a specific word you wish to ban from your program. See example in action below:

String aString = "This is a BAD word example";
if(aString.contains("BAD")) 
{
   // Do something if the String contained "BAD" (contains method returned true indicating match to the CharSequence/String)
}

As you can see from the example above, the CharSequence is defined like a String.

The endsWith() String method in Java explained

Could be useful if you wish to determine if a specific String ends with a specific String suffix.

See practical example below:

String testString = "A teststring for what this ends with";
if(testString.endsWith("with")) 
{
   // Do something if testString ended with "with" (endsWith method returned true)
}
The equals() String method in Java explained

This is a great String method for when you want to check whether a specific String is a match to another different String.

Note: Although one would think that equals comparison (==) would work just as well, there is a slight difference one needs to be aware of, which is that the .equals() String method compares the actual content of the String, whilst == is a “reference matching” more than content matching.

So avoid using == for String comparison! (Might give unpredictable results)

Practical example of .equals() String method below:

String compareString = "Compare me";
if(compareString.equals("Compare me")) 
{
   // Do something if compareString matched the equals defined String "Compare me"
}

// Can also use defined String variables in comparison
String compareString2 = "Compare me too";
String compareString3 = "Compare me too";
if(compareString2.equals(compareString3)) 
{
   //If compareString2 and compareString3 match, do something :)
}

There is a great Stackoverflow article discussing this further.

The equalsIgnoreCase String method in Java explained

This works the same as Javas String equals method, with the exception as explained in the table above that it ignores case sensitivity.

Which means if you want to purely compare the actual content of a String and ignore whether some characters don’t match because some are uppercase in one String while the same characters are lowercase in the other String, then the equalsIgnoreCase method can be very useful :)

See example below:

String newCompareString = "Testing";
String mixedCompareString = "TeStInG";
if(newCompareString.equalsIgnoreCase(mixedCompareString)) 
{
   // Evaluates to true even when our two Strings don't match in case sensitivity :)
}
The indexOf String method in Java explained

This method can be useful if you for some reason need to know what slot (index) a specific substring or character has as part of a specific String.

Some practical programs that could find this functionality useful could be if you for example wanted to verify if a special character at a specific part of a String matches your criteria.

Say for banking applications, maybe the bank account number is formatted like so: 1234-5432 – then you might want to check to make sure that the index of slot 5 (index 4, counting starts at 0 in programming), actually is the “-” and nothing else to make sure that the formatting is correct.

Practical example of this:

String bankAccountNumber = "1234-5432";
if(bankAccountNumber.indexOf("-") == 4) 
{
   // If formatting is correct and verified using indexOf method match to the character -, then do something :)
}
The other variation of the IndexOf String method in Java that we cover explained

This method works similarly to the above indexOf, but with one small difference. Here we can add an integer fromIndex to define where we want to start our “search” for a specific character in our String – this adds a bit of flexibility to the indexOf method allowing us to “skip” parts that we know are irrelevant for our check.

Practical example:

String checkString = "1234-5432---3210-1234";
if(checkString.indexOf("-", 12) == 16) 
{
   // The 12 input parameter ignores the first 12 indices (index) and checks for the - character starting at index 12
   // We then do something if the match occurred at index 16 (note than even if 12 first index was "ignored" they still count index-wise for the find)
}
The isEmpty String method in Java explained

This is a very useful method that can be used to check whether Strings are empty of text content or not – can be especially good to make sure that user input was entered in user interfaces before trying to do something with the inputted data to avoid program crashes in case user input was left empty.

Practical example:

String str = "";
if(str.isEmpty()) 
{
   str = "Something"; // If our String str was empty, we fill it with "Something" as value :)
}
The lastIndexOf String method in Java explained

Similar to the .indexOf() String method, this will search for the occurrence of our String or character specified as input parameter, but in contrast to the indexOf() String method it will search for the last occurrence of the specified String/character, so basically in reverse/starting the search backwards for the String being searched.

Practical example below:

String testStr = "klick";
System.out.println("Last index of k in testStr: " + testStr.lastIndexOf("k")); // Will give us the index 4 (last character, remember count starts from 0 in programming), slot #5 = index 4
The other variation of the lastIndexOf String method in Java that we cover explained

This will be same as .lastIndexOf() with only a String specified, but here we can also add a fromIndex integer to specify from what index we should starting searching backwards from.

See practical example below:

String backwardSearch = "AndromedA";
System.out.println("Last index of A searching backwards starting from index 7: " + backwardSearch.lastIndexOf("A", 7));
// Above will give us index 0, because we skipped the very last A by starting our search from index 7 and going backwards from there searching for "A"

Note: indexOf AND lastIndexOf methods are case sensitive!

The length String method in Java explained

This is probably one of THE most useful methods working with Strings in Java.

Reason is that this can help you determine if a String contains a value, if it has the appropriate length for what you expect based on how you have designed your program, etc.

Practical and very common praxis for using the length method for working with Strings below:

String aStr = "This is my String";
if(aStr.length() > 0) 
{
   // The condition we checked in our if statement is whether aStr is empty or not (instead of using .isEmpty() method
}

// Another popular example:
String bStr = "Test";
if(bStr.length() == 4) 
{
   // Do something if our bStr String variable had the expected length of 4 characters
}

Note: .length() method does return the actual length of a String, it does NOT count indices (index) starting from 0, but instead from 1 as is “regular” way of counting.

The matches String method in Java explained

This can be a very useful String method as well in Java, even if it might be considered a bit more advanced in order to use it to its full potential and power in programming.

With the .matches() method in Java you can check if a specific String matches a specified String Pattern using Regular Expressions or a regular String.

The beauty of String pattern recognition using Regular Expressions is that you can define in a very abstract way a text pattern that doesn’t have to be specified but could follow specifically defined guidelines instead so that the actual String content can be dynamically changed and thereby vary.

A practical example could be to validate data you ask of your users, there are text recognition patterns defined for validating email address formats as well as credit card numbers etc. Using Regular Expressions you could check if what your user entered was a valid credit card number format or email address format to make sure your program works the best way possible.

You could also use Regular Expressions to check if a specific String contains only numbers, or only A-Z upperccase letters, or a-z lowercase letters, or a combinations of all A-Z, a-z and 0-9 (letters + numbers) without accepting special characters like !?#@&/()= etc.

It can be extremely useful for creating powerful programs and code.

Regular Expressions are so popular that you can often find them and use them in many various programming languages as well, the syntax for defining the Regular Expressions might differ slightly from language to language though. JavaScript Regular Expression might be different from PHP Regular Expressions which in turn might be different from Java Regular Expressions.

In Java, Regular Expression patterns are defined as regular Strings, as can be seen in the example below:

String textString = "This is a text without numbers";
String numberString = "12345";
String fixedString = "Fixed";
if(textString.matches("[a-zA-z]")) 
{
   // The Regular Expression text recognition pattern responsible for a match here matches all Strings that contain ONLY the letters a-z and A-Z
}else if(numberString.matches("[0-9]")) 
{
   // The Regular Expression text recognition pattern responsible for a match in this case matches all Strings that contain ONLY the numbers 0-9
}else if(fixedString.matches("Fixed")) 
{
   // We end up here when we match a String to a "fixed" text pattern using a specifically defined String as pattern to recognize and match
}

If you find Regular Expressions interesting you can learn more about it in our Appendix, where we cover how to create them, as well as demonstrate various useful patterns and explain what each part of their syntax does. We also share with you useful online simulators and resources where you can study and try out various Regular Expressions in real-time :)

The replace String method in Java explained

With the .replace() method in Java you can replace occurrences of a specific String from another String, this could be very useful if you for example wanted to “clean” a String a certain character, word etc.

Practical example below:

String toReplace = "This-is-a-string-bound-by-minus-signs";
toReplace = toReplace.replace("-", "_");
System.out.println(toReplace); // Will print: "This_is_a_string_bound_by_minus_signs"
The replaceAll String method in Java explained

The difference with .replaceAll() method in Java for replacing occurrences of a String inside of another String is that .replaceAll() also accepts Regular Expression text pattern recognition for what should be replaced.

Imagine the possibilities, virtually endless, you could target all Emails in a huge text and replace then with a standard email address, or replace all special characters with nothing (in other words removing special characters) if special characters are not allowed for that particular String in your program.

Practical example below:

String mixedStr = "This 123 string 321 mixes 543 letters 345 and 789 numbers";
mixedStr = mixedStr.replaceAll("[0-9]", ""); // "" means nothing - so in this case replaceAll will replace all numbers with nothing/emptiness, in other words - remove all numbers
System.out.println(mixedStr); // Will print: "This  string  mixes  letters  and  numbers"
The replaceFirst String method in Java explained

Sometimes maybe you only wish to replace the very first occurrence of a specific String inside of another String? Then the .replaceFirst() method will do a decent enough job for you to accomplish this.

Example below:

String replaceString = "An 123 example 321";
replaceString = replaceString.replaceFirst("[0-9]", "");
System.out.println(repalceString); // Will print: "An 23 example 321", indicating that the RegEx matches each and every 0-9 digit rather than number combination
The split String method in Java explained

This is also an extremely useful String method in Java which you can use to “explode”/split a String on a specific character, word or String (its called explode instead of split in some programming languages which is quite appropriate since it basically “blows up” Strings on specific characters/Strings/Regular Expressions :P).

For example if you wanted to process a String on every word that the String consist of, you could “explode”/split it on whitespace and get every word separated in a String Array that you then can work with.

A common example for this at least in web development is to split a URL on forwardslash (/) to get all the various parts of the URL divided into different parts.

See a practical example below of this scenario:

String myURL = "https://www.example.com/controller/param1/param2/param3";
String[] strArray = myURL.split("/");
for(int i = 0; i < strArray.length; i++) 
{
   System.out.println("Index " + i + ": " + strArray[i]);
}
// The above will print:
// Index 0: "https:"
// Index 1: ""
// Index 2: "www.example.com"
// Index 3: "controller"
// Index 4: "param1"
// Index 5: "param2"
// Index 6: "param3"

Note: I added the double quotation marks to clarify that what is printed is actually String values that are stored in the String array

The other variation of the split String method in Java that we cover explained

There is another variation of the .split() method in Java which allows for a second input parameter which defines a “limit”. This limit is used to restrict how many times the specified split String pattern should be applied when splitting the String.

If the integer limit value is set to lower than 0 (usually -1) this means that there will be no limitations on how many times the split String pattern is applied and the String Array will be filled until the String cannot be split anymore. The resulting array will hold all the various parts of the split String.

See practical examples below:

String myURL2 = "https://www.example.com/";
String[] strArray2 = myURL2.split("/", 1);
for(int i = 0; i < strArray2.length; i++) 
{
   System.out.println("Index " + i + ": " + strArray2[i]);
}
// The above will print:
// Index 0: "https://www.example.com/"

Note 1: The second input parameter for limit is defined as n where then the split method uses n-1 to determine how many times to apply the pattern. So in above example where we gave n = 1, what is applied in the split method is n-1 = 1-1 in this case which equals to 0 times the pattern is applied for the split which gives us the original String. If you were to change the 1 to 2 instead, n = 2 gives n-1 = 2-1 which gives us 1 times to apply the pattern, if you try this you will se a printout as follows:

// Index 0: "https:"
// Index 1: "/www.example.com/" (Notice how 1 of the two // has disappeared, cuz thats where it was split)

Note 2: I added the double quotation marks to clarify that what is printed is actually String values that are stored in the String Array

The startsWith String method in Java explained

This is the opposite method to our previously covered .endsWith(), and will also return true/false based on if the targeted String starts with your specified String or not.

Practical example below:

String xString = "Wombat";
System.out.println(xString.startsWith("W")); // This will return boolean value of true
The other variation of the startsWith String method in Java that we cover explained

Another variation of the .startsWith() method in Java can have an offset defined to allow the check to start at a specific index.

Practical example below:

String zString = "WoW";
System.out.println(zString.startsWith("W", 1)); // This will return boolean value of false because index 1 (means "o" in our String) is the second slot, starting from index 1 (second slot) is "o" and not "W
The substring String method in Java explained

The .substring() method in Java is also extremely useful for working with Strings.

It allows you to “cut out” parts of a String and work with that part instead of the entire String.

One example of when this can be useful is when you have a long String with lots of information, but for your programs purpose you only need a smaller part of the long String, so you cut out anything you don’t need so that you can focus on working with that part of the String which you do need :)

You define from what index the .substring() method should start (inclusive) and then continue to the end of the String that you wish to create a substring of.

For practical example see below:

String name = "Hanna";
System.out.println(name.substring(1)); // Creates a substring from index 1 and to the end - will print: anna

// .substring() method can also be called outside of other methods
String nameZ = "Amona";
String newName = "";
newName = nameZ.substring(1); // newName will after this contain "mona"
The other variation of the substring method in Java that we cover explained

There is also another variation of the .substring() method in Java for working with Strings where you get to define both the beginIndex as well as the endIndex so that you can get a finer-grained control of what exactly you want to substring from your String.

Practical example below:

String otherName = "Hannah";
System.out.println(otherName.substring(1, otherName.length()-1)); // using String method .length() to get to the end of our String, and since the method substring goes to endIndex -1 this will print "anna"
The toLowerCase String method in Java explained

The .toLowerCase() method in Java can help you transform Strings to only lowercase letters, which can be useful for when you are checking if content matches your expectations for example or when you want to only want lowercase letters and don’t want to have to code complex checks to make sure that your user inputs only lowercase letters. Then this post-processing way of simply turning ALL characters of the inputted String into lowercase after they have been inputted can save both time and effort :)

Note however that the .toLowerCase() method returns a String which means you can’t just call the method on a String anywhere and then think that the original String will be changed – the original String will stay the same, but calling the .toLowerCase() method will give you a new and transformed all lowercase String that you then can continue working with.

Practical example below:

String mixedAlphabet = "AbCdEfGhIjKlMnOpGrSTuVxyZ";
System.out.println(mixedAlphabet.toLowerCase()); // This will print "abcdefghijklmnopqrstuvxyz"
The toUpperCase String method in Java explained

Same type of functionality as the .toLowerCase() method, but instead of transforming an existing String and its text content value to all lowercase letters, .toUpperCase() will do the exact opposite and transform it into all Uppcerase letters.

Example below:

String discount = "discount";
System.out.println(discount.toUpperCase()); // This will print: "DISCOUNT"
The trim String method in Java explained

The .trim() method in Java for working with Strings can be useful to trim away leading and trailing whitespace. Easiest to show how it works:

String messyString = "      this is a string    ";
System.out.println(messyString.trim()); // This will print: "this is a string"

Walkthrough of Arrays and ArrayLists in Java to store and work with sets (lists) of data

What are Arrays?

Arrays can be thought of as a list container where you define how many slots your list should have and what type of variable the list should hold (store), then you can fill your list with appropriate values.

How do Arrays work in Java?

Arrays are a tad more complex as variable type than our regular variables we have worked with so far. But the array and its list-like properties is invaluable when it comes to processing sets of data and information – just think back on the split String method which creates an array to be able to work with all the various parts we exploded/split the original String into :)

Arrays in Java can only store 1 single data type, and this has to be defined when you create your array using a specific Syntax that we will get into and show how it works later in this section.

Arrays in Java also are very restricted in the way that once you have defined a length of an array or its capacity for how many values it can hold/store, then it becomes a bit of a hassle if you then later realize you need to be able to store more values in your array and need to change the length.

Because then you basically have to create a new array where you define your new storage capacity/length of the new array and then transfer the values from the old array to the new array by copying them one by one.

Arrays also present an opt opportunity to get familiar with the concept of counting with the zero in programming, which is very common for a lot of tasks in programming.

In java the different slots are defined with indices (index) that start at 0 and range to length-1. See illustration below:

Java illustration of Array index and values

So to access the value 15 in our array, we have to ask for the value from index 0.

Also note that our array above has 6 values, but 5 is the highest index, since we count with the zero, the highest index becomes array.length-1.

This can also be good to be familiar with when it comes to loops such as for-loops where every iteration usually start at 0, you don’t have to of course, but its very common.

You can read more about accessing values from an array below :)

How to create an Array in Java

When creating arrays in Java you have to specify what variable data type the array should be able to hold/store as well as how many values it should be able to hold (fixed amount).

There are 2 significant ways of how you can create arrays in Java, where one is creating an empty array where you define the amount of slots your array should have and where the other way is to immediately define all the values the array should hold. See example of both ways below:

// First way of creating a new empty array:
String[] myStringArray = new String[10]; // Creates a new String array that can hold 10 values (not 11, don't count with 0 here, but regularly from 1)
// When creating a new empty array like above the pre-defined values of each of the arrays different storage slots will have the default value for the variable data type it stores
// So in the case above the variable data type is String, which has the predefined object value of null, if you wish to initially fill every slot with a different value, 
// you will have to manually populate the all of the slots by looping through them and assigning each slot the value you want them to initially have (will demonstrate in replacing array values section below)

// Second way of creating an array with predefined values:
String[] prePopulatedArray = {"this", "that", "those"}; // Index 0 = "this", Index 1 = "that", Index 2 = "those"

// See below for how other data type arrays are created in Java:
double[] anArrayOfDoubles = new double[5];
boolean[] anArrayOfBooleans = new boolean[5];
char[] anArrayOfChars = new char[5];
int[] anArrayofInts = new int[5];
// Remember that when creating new arrays without defining its initial values, Data Type default values will dictate initial values, read more bout default values here

How to work with Arrays in Java

Accessing values from an Array in Java

To access specific indices (index) values in an array in Java we use the square brackets [] and specify the actual index we want to fetch data from, like so:

int[] myIntegerArray = {1, 2, 3, 4, 5};
System.out.println(myIntegerArray[0]); // Will print first index (index 0) integer value, which in this case holds the integer value 1

If you on the other hand are more interested in accessing ALL of the arrays values, for-loop or foreach loop is usually the most popular ways to go, I will demonstrate for-loop below:

int[] anotherIntegerArray = {10, 15, 20, 25};
for(int i = 0; i < anotherIntegerArray.length; i++) 
{
   System.out.println(anotherIntegerArray[i]); // For every for-loop iteration, we will fetch the value of index i - so first iteration fetches index 0 value since i starts at 0
}
// Above will print the following:
// 10
// 15
// 20
// 25
Removing values from an Array in Java

Removing values from a regular array in Java can be a bit complicated depending on how exactly you wish to remove values from the array.

If you wish to just “clear” a value and reset it to the initial value for example, all you have to do is replace the current value with the reset value.

However if you wish to remove one or more value(s) as in remove the entire index with a specific value, you have to go through the process of:

  1. Creating a new array of the same data type, defined with the length of your current array minus x, where “x” represents the amount of indices (index) you wish to remove (since you want to remove a value and thereby reduce array length),
  2. Then you have to copy over all of the values from your current array into the new and reduced array where you don’t copy over the value you wanted to remove.

See below demonstration:

// Imagine we want to remove the value 2 of our integer array
int[] intArray = {1, 2, 3, 4, 5};
int[] newReducedArray = new int[intArray.length-1]; // Since intArray had 5 values a.k.a. 5 slots, new array with -1 reduced should have 4 slots
int counter = 0; // This will help us tell the compiler where we want to insert the copied values from intArray into newReducedArray
for(int i = 0; i < intArray.length; i++) 
{
   if(intArray[i] != 2) {
      newReducedArray[counter] = intArray[i]; // Transfering/Copying the value of intArray[i] to newReducedArray[counter]
      counter++; // Increment the counter ONLY when we are NOT on intArray slot with value 2 to represent newReducedArrays indices (index) to insert values to the right indices (index)
   }
}
Replacing values from an Array in Java

When replacing values in arrays in Java we often want to do this out of two reasons, either to “clear” the array of data values being stored/fill it with predefined initial values, or specifically change/alter a value being stored in a specific slot in the array. Demonstrating both examples below:

// Populating/filling a freshly created Array with initial values:
String[] myStrArray = new String[10]; // Every single slot of this newly created array will hold the value null
for(int i = 0; i < myStrArray.length; i++) 
{
   myStrArray[i] = ""; // Replacing null with "" in every index of our myStrArray
}

// Replacing specific value in a filled array:
String[] replaceArray = {"one", "two", "three"}; // Index 0 holds the String value "one", Index 1 holds the String value "two", etc.
replaceArray[1] = "five"; // This takex index 1 (a.k.a. slot 2 of our Array: "two") and replaces its String value with "five"

Emptying/clearing an array is just like populating/filling an array, you loop through each of the arrays different indexes and changes the values of each index to what you want to store there instead.

Sorting values in an Array in Java

Sorting of arrays in Java can be done manually using certain sorting algorithms. or it can be done using the Arrays utility class and its sort method (which is way easier).

The manual sorting algorithms (even the simpler ones can be quite the hassle to wrap ones head around, therefore I spent a few hours creating a visual illustration in Java printout to show how exactly the numerical sorting algorithm works. I will paste the visualisation results from the printsouts below, since the code however became quite messy to accomplish this I will skip it :)

The actual numerical order sorting algorithm in its purest form however will be posted as well as explained.

The actual process of manually sorting arrays using certain algorithms such as the numerical sorting algorithm requires restructuring of the actual arrays values and how they are being stored, which can be a hassle and involve complex programming algorithms – even the simpler ones can be quite confusing when first starting out learning Java to wrap ones head around.

There are a few sorting algorithms that can be applied for arrays in Java, but for educational purposes and simplicity sake, I will only demonstrate one of the simpler algorithms which is to sort an integer array in numerical order from lowest-highest (I’ll keep the amount of numbers to sort at a minimum to be able to visualize the process easier after). See example below:

// One of the simpler ways of sorting this array is to manually loop through it
// and then for every loop iteration we loop through all of the values in the array to compare to the first loops value to rearrange their places.
// Sort of like for every value in the array we loop through the entire array to compare the first loops value with every value in the array 
// and switch places where first loops value is larger than the second loops value

int[] numbersArray = {5 ,7, 3, 2};
for(int i = 0; i < numbersArray.length; i++) 
{
   for(int j = i+1; j < numbersArray.length; j++) 
   {
      int temp = 0;
      if(numbersArray[i] > numbersArray[j]) 
      {
         temp = numbersArray[i];
         numbersArray[i] = numbersArray[j]; // numbersArray[i] gets value of numbersArray[j] if i value was higher than j (move up the smaller value in the Array)
         numbersArray[j] = temp; // numbersArray[j] gets value that numbersArray[i] used to have that we stored in our temp integer variable, so they switch places
      }
   }
}

For a visualisation of how this sorting algorithm will work through sorting our above array, see below Java printout:

Unsorted Array: {5, 7, 3, 2}

outer iteration: [i] = 0: {[5], 7, 3, 2}

inner iteration: (j) = 1: {[5], (7), 3, 2}
no sort: numbersArray[0] = 5 numbersArray[1] = 7

inner iteration: (j) = 2: {[5], 7, (3), 2}
pre sort: numbersArray[0] = 5 numbersArray[2] = 3
5, 7, 3, 2
post sort: numbersArray[0] = 3 numbersArray[2] = 5
3, 7, 5, 2

inner iteration: (j) = 3: {[3], 7, 5, (2)}
pre sort: numbersArray[0] = 3 numbersArray[3] = 2
3, 7, 5, 2
post sort: numbersArray[0] = 2 numbersArray[3] = 3
2, 7, 5, 3

outer iteration: [i] = 1: {2, [7], 5, 3}

inner iteration: (j) = 2: {2, [7], (5), 3}
pre sort: numbersArray[1] = 7 numbersArray[2] = 5
2, 7, 5, 3
post sort: numbersArray[1] = 5 numbersArray[2] = 7
2, 5, 7, 3

inner iteration: (j) = 3: {2, [5], 7, (3)}
pre sort: numbersArray[1] = 5 numbersArray[3] = 3
2, 5, 7, 3
post sort: numbersArray[1] = 3 numbersArray[3] = 5
2, 3, 7, 5

outer iteration: [i] = 2: {2, 3, [7], 5}

inner iteration: (j) = 3: {2, 3, [7], (5)}
pre sort: numbersArray[2] = 7 numbersArray[3] = 5
2, 3, 7, 5
post sort: numbersArray[2] = 5 numbersArray[3] = 7
2, 3, 5, 7

outer iteration: [i] = 3: {2, 3, 5, [7]}

Sorted Array: {2, 3, 5, 7}

I have been told above way of sorting an Array can be referred to as “Bubble sort“.

Another way of sorting arrays is to use methods in the Arrays utility class, which is way easier than than doing everything manually.

This method sorts for example integer arrays in ascending order and more information about the Arrays utility class can be found at Oracle Documentation.

For a practical sorting example, see below:

int[] myArray = {1, 5, 7, 88, 43, 2, 1, 8, 9, 4, 12, 15, 3};
Arrays.sort(myArray);
for(int i = 0; i < myArray.length; i++) 
{
   System.out.println(myArray[i]);
}
// The above will print:
// 1
// 1
// 2
// 3
// 4
// 5
// 7
// 8
// 9
// 12
// 15
// 43
// 88
Expanding the capacity of an Array in Java

Expanding the storage capacity on an array in Java is the same principle as when we reduced the storage capacity when truly removing an entire index with a specific value from an array, like shown bove. Only difference for when expanding the storage capacity is that we now create a +x larger Array where “x” represents how many slots you wish to extend it with.

See example below:

int[] tooSmallArray = {1, 2, 3};
int[] biggerArray = new int[tooSmallArray.length+2];
// Note: biggerArray = tooSmallArray won't work because the length of biggerArray will be reduced to match the length of tooSmallArray
for(int i = 0; i < tooSmallArray.length; i++) 
{
   biggerArray[i] = tooSmallArray[i]; // This will copy the values from tooSmallArray to our biggerArray without corrupting our length of biggerArray
}
biggerArray[3] = 4;
biggerArray[4] = 5;
for(int i = 0; i < biggerArray.length; i++) 
{
   System.out.println("Index " + i + ": " + biggerArray[i]);
}
// The above will print:
// Index 0: 1
// Index 1: 2
// Index 2: 3
// Index 3: 4
// Index 4: 5
Using the Arrays class in Java to easily print the values of an Array without the need of a for-loop

The Arrays class in Java has a .toString() method (that most if not all Java classes usually has built-in for formatting the value to String) that we can use to format an array so that we easily can print arrays directly in a System.out.println() statement – without needing to for-loop through each and every value of the array.

See example below how we do this:

int[] numbers = {1,2,3,4,5};
System.out.println(Arrays.toString(numbers)); // This will print: [1, 2, 3, 4, 5]
Merging two Arrays of the same type into one and the same in Java

This can sometimes be a useful feature, that can be a bit difficult to do, so here below I will demonstrate one way of doing it:

int[] firstNumbers = {1,2,3,4,5};
int[] secondNumbers = {6,7,8,9,10};
int[] mergedArray = new int[firstNumbers.length + secondNumbers.length];

int secondNumbersIndexCounter = 0;
for(int i = 0; i < mergedArray.length; i++) 
{
   if(i < 5)  // The first 5 values can be fetched using i variable as index for firstNumbers array
   {
      mergedArray[i] = firstNumbers[i];
   }else { // One all of the numbers from firstNumbers Array have been added from 0-4 index of mergedArray, we then fill with secondNumbers from there
      mergedArray[i] = secondNumbers[secondNumbersIndexCounter];
      secondNumbersIndexCounter++; // Incrementing this counter will help us fetch values from our secondNumbers array
   }
}
System.out.println(Arrays.toString(mergedArray)); // This will print: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <- so now you see that mergedArray contains the merged result of firstNumbers and secondNumbers :)
Creating an Array with values as input parameter to a method without having created it beforehand

This is something I noticed sometimes could be useful when you want to create shorter amounts of code for doing something. In this case we don’t want to use 1 line of code for creating our array, but instead we create the array in the actual method call, see example below:

System.out.println(Arrays.toString(new int[]{1,2,3,4,5})); // This will print: [1, 2, 3, 4, 5] <- notice how we did a System.out.println, Arrays.toString and created an array in one single line of code

Multidimensional Arrays explained and use cases

The simplest example I have ever come across when it comes to multidimensional arrays in programming is to imagine two-dimensional arrays as Rows and Columns such as in Excel and Google Sheets, or as in relational databases if thats a familiar concept to you. Tables in general can also be used as an analogy where you have multiple rows and columns.

A multidimensional array is arrays inside of arrays.

A multidimensional array can sometimes be refered to as Matrix (not like the movie :P) or Vector.

Basically a two-dimensional array has the first index represent a Row and then each row has indices (index) representing the Columns. Let me demonstrate below:

Imagine we have this table with information:

Row 1, Column 1 Row 1, Column 2 Row 1, Column 3
Row 2, Column 1 Row 2, Column 2 Row 2, Column 3
Row 3, Column 1 Row 3, Column 2 Row 3, Column 3

Ok, so we are going to recreate this table structure in Java using a two-dimensional (multidimensional) array, as follows:

String[][] twoDimensionalArray = {
   {"Row 1, Column 1", "Row 1, Column 2", "Row 1, Column 3"}, 
   {"Row 2, Column 1", "Row 2, Column 2", "Row 2, Column 3"}, 
   {"Row 3, Column 1", "Row 3, Column 2", "Row 3, Column 3"}
};
// So as you can see in above example, every index of the very first array (the blue one) represents a Row, and every Row itself has a separate array (the red one) inside of the first array that is the Row value
// The rows array then has 3 String values where each String represents a Column value

Also Note that we define the two-dimensional array with String[][] to indicate that we have arrays within arrays.

The amount of square brackets indicate the dimensions of the array.

Personally I think two-dimensional arrays can be useful, but when you start to exceed it into 3+ the brain starts to hurt a little bit :P Especially if you also have to process the data stored within using nested for-loops in 3 different levels, with 3 different iteration keys (i, j, k for example) for a 3-dimensional array.

Accessing values from a multidimensional Array in Java

When you wish to access values in a multidimensional array such as our two-dimensional array above, you have to “nest” for-loops, meaning have for-loops inside of for-loops where each for-loop will be responsible for iterating/looping through each dimension of the multidimensional array.

So if we were to access and print all of the values from our two-dimensional array above we have to first loop through the Rows using 1x for-loop, then inside of this for-loop we have to have another “nested” for-loop which will then be responsible that for every Row, loop through every Column value on that row.

See practical example below:

String[][] twoDimensionalArray = {
   {"Row 1, Column 1", "Row 1, Column 2", "Row 1, Column 3"}, 
   {"Row 2, Column 1", "Row 2, Column 2", "Row 2, Column 3"}, 
   {"Row 3, Column 1", "Row 3, Column 2", "Row 3, Column 3"}
};

for(int row = 0; row < twoDimensionalArray.length; row++)
{
   for(int col = 0; col < twoDimensionalArray[0].length; col++) 
   {
      System.out.println(twoDimensionalArray[row][col]);
   }
}

This means we loop through every single row, and on each row, we loop through each and every column value, so:

  • First row iteration, first column value System.out.println will print the String value “Row 1, Column 1”
  • First row iteration will then move on to second column in the second nested for-loop and print the String value “Row 1, Column 2”
  • When all of the column value iterations are completed for the nested for-loop, the nested loop sequence returns to the first loop and executes row++ and moves back up to the first loop iteration which will then loop through the column values of Row 2 one by one. And so the nested for-loop will continue until there are no more rows or column values left!

If you set out breakpoints in Eclipse debugger you can more easily observe exactly how this is happening by putting breakpoints on each statement inside each for-loop.

That way you will se that the most inner nested for-loop will loop through each column value until the second iteration of the outmost for-loop (for rows) continue onwards to the next value.

Introducing ArrayLists in Java

When you have been forced to work with arrays for a while its easy to get tired of them since how much work they require to do seemingly simple tasks, thats when ArrayLists can come to the rescue.

ArrayLists may be barely a bit slower than regular arrays, but it feels so worth it since:

  • The dynamic storage capacity
  • The possibility to store multiple data types in 1 single ArrayList
  • As well as the simple sort methods that do the heavy lifting for you are so satisfying

It has never been easier to add and remove values to a list container using the built-in methods of the ArrayList in Java.

I completely switched over for my more complex programs where I needed to store lists of data once I discovered ArrayLists, it made life so much easier.

Note: Since ArrayList is part of the Java Utility Collection Framework, you need to import either the entire utility framework or the ArrayList class from the utility framework to work with it :)

Difference between ArrayList and Array in Java

A key difference between regular arrays and ArrayLists in Java are that ArrayLists can only work with objects, so to store integer values that are a primitive data type in Java, it will use the Integer wrapper class to store integer values av Integer wrapper class objects.

  • Another difference is also that regular arrays in Java can be accessed using the square brackets [] whilst ArrayLists are accessed using a built-in .get() method.
  • As mentioned above also the ArrayList has dynamic storage capacity, whilst regular arrays in Java have a fixed storage capacity.
  • ArrayLists can also hold/store various data types in one and the same ArrayList variable, whilst regular arrays in Java can only hold 1 variable data type at once.
  • ArrayLists however can only store 1 dimension of data set whilst regular arrays in Java can store multiple dimensions with data sets.
  • ArrayLists are usually a bit slower (barely noticeable in casual programming) than regular arrays in Java and can have limited storage capacity compared to a regular array in Java.
  • ArrayLists however usually make it way easier to handle, sort and expand the data being stored.
  • Also defining the length of ArrayList before-hand could also help improve its performance since the dynamic memory allocation process can be taxing.

Working with ArrayLists in Java

How to create ArrayLists in Java

ArrayLists also define data type as well as length when they are created, however its done a bit differently than for regular arrays, see below:

// Creating an Integer ArrayList with 5 slots (that can be dynamically altered whenever)
ArrayList<Integer> myIntegerArrayList = new ArrayList<Integer>(5);

// Creating a String ArrayList with unspecified amount of slots (yes this is also possible :P)
ArrayList<String> myStringArrayList = new ArrayList<String>();

// Creating an ArrayList that can hold any Object (String, int, double, etc.)
ArrayList<Object> myMultiArrayList = new ArrayList<Object>(5);

Note: We use Integer wrapper class as the object for the integer ArrayList :) Same will be for Double and other primitive variable data types.

How to get length/size of ArrayLists in Java

The ArrayList class has a built-in method for this called .size() which can take some getting used to since regular arrays use the length variable and Strings the .length() method :P

It also behaves a bit differently in that it won’t print a length if the ArrayList is empty. If you have defined an ArrayList with initial capacity of 5 the .size() will still only print 0. Because it counts amount of elements within the ArrayList!

Example of .size() usage:

ArrayList<String> myStrArrList = new ArrayList<String>();
System.out.println(myStrArrList.size()); // Will print 0

// Example of initial capacity not counted when using .size()
ArrayList<String> aStrArrList = new ArrayList<String>(5);
System.out.println(aStrArrList.size()); // Will print 0

// Example of added elements being counted but not other capacity even if it is "reserved" as initial capacity
ArrayList<String someStrArrList = new ArrayList<String>(5);
someStrArrList.add("String");
System.out.println(someStrArrList.size()); // Will print 1
How to acess values from ArrayLists in Java

The ArrayList class has a built-in method for getting values called .get(int index) where you can specifically retrieve the value at a specified index.

Otherwise if you wish to access all of the values in the ArrayList the principle is the same as for regular arrays – you can for-loop through it and access each individual value in order :)

See example below:

// Example of accessing specific value inside ArrayList
ArrayList<Integer> iArrayList = new ArrayList<Integer>();
iArrayList.add(15);
iArrayList.add(30);
iArrayList.add(45);

iArrayList.get(1); // Fetches index 1 value (slot 2) a.k.a: 30
How to add values to ArrayLists in Java

Adding values to our ArrayList must be done using the ArrayList class method .add(), and when we add the added value will be added after all the already existing values, unless you specify otherwise by giving a specific index to “add” the value to. Here how it works:

ArrayList<Integer> anIntegerArrayList = new ArrayList<Integer>();
anIntegerArrayList.add(15);
for(int i = 0; i < anIntegerArrayList.size(); i++) 
{
   System.out.println(anIntegerArrayList.get(i));
}
// Above will print:
// 15

// Example if you wish to set default values in your ArrayList
ArrayList<Integer> myNewArrList = new ArrayList<Integer>(5);
for(int i = 0; i < 5; i++) 
{
   myNewArrList.add(0);
}
// After this is done our ArrayList will contain 5 slots where all the values will be 0

// You can also specify a specific index you wish to add a value to for your ArrayList using the method .add(int index, Object value)
// We will in this particular example add value to some indices (index) of above example where the values were initialized to 0
// This since just creating an ArrayList with initial capacity won't work, it will throw error due to initial capacity not being actual values just "reserved" space
myNewArrList.add(2, 15);
myNewArrList.add(4, 30);
for(int i = 0; i < myNewArrList.size(); i++) 
{
   System.out.println(myNewArrList.get(i));
}
// Above will print:
// 0
// 0
// 15
// 0
// 30
// 0
// 0
// Notice how adding to certain elements when those elements already have values "pushes" away the already exisiting values

// You could also loop through a regular Array with values and add each value to your ArrayList, like so:
int[] otherIntValues = {10, 15, 20, 25, 30};
ArrayList<Integer> intArrayList = new ArrayList<Integer>();
for(int i = 0; i < otherIntValues.length; i++) {
   intArrayList.add(otherIntValues[i]);
}
How to remove values from ArrayLists in Java

The ArrayList class method .remove(int index) will remove the value and actual index for which index you specify, see example below:

ArrayList<Integer> intArrList = new ArrayList<Integer>();
intArrList.add(1); 
intArrList.add(2); 
intArrList.add(3);

intArrList.remove(1); // Remove the index 1 aka slot 2
for(int i = 0; i < intArrList.size(); i++) 
{
   System.out.println(intArrList.get(i));
}
// Above will print:
// 1
// 3
How to replace values in ArrayLists with new ones in Java

There is also a .set(int index, Object value) method in the ArrayList class that allows us to replace the value of an index that already has a value.

See example below:

ArrayList<Integer> myIntArrayList = new ArrayList<Integer>();
myIntArrayList.add(15);
myIntArrayList.set(0, 30); // Replace/set the value at index 0 with 30 instead of what it was
System.out.println(myIntArrayList.get(0)); // Will print 30
How to check if ArrayLists is empty in Java

The ArrayList class in Java has .isEmpty() method that can be used to check if an ArrayList has any values in it. See demonstration below:

ArrayList<String> anotherStrArrayList = new ArrayList<String>();
System.out.println(anotherStrArrayList.isEmpty()); // Will print true
How to check if ArrayLists contains a specific value in Java

The ArrayList class in Java also has a method to check if the ArrayList contains a specific value, see example of it below:

ArrayList<Integer> anIntArrList = new ArrayList<Integer>();
anIntArrList.add(15);
anIntArrList.add(3);
anIntArrList.add(40);

System.out.println(anIntArrList.contains(15)); // Will print true
How to get the index of a specific value in ArrayLists in Java

We can use the built-in .indexOf(Object value) method in the ArrayList class to find out what specific index a specific value has.

See example below:

ArrayList<String> stringyArrayList = new ArrayList<String>();
stringyArrayList.add("One");
stringyArrayList.add("Two");
stringyArrayList.add("Three");

System.out.println(stringyArrayList.indexOf("Two")); // Will print 1 (the index for "Two")
How to clear all elements in ArrayLists in Java

The ArrayList class also has a built-in .clear() method to remove all of the values from the ArrayList. Here how it works:

ArrayList<Integer> myNewIntArrayList = new ArrayList<Integer>();
for(int i = 0; i < 5; i++) 
{
   myNewIntArrayList.add(i+1);
}
// ArrayList will contain: 1,2,3,4,5 after the for-loop completed running
myNewIntArrayList.clear();
System.out.println(myNewIntArrayList.isEmpty()); // Will print true - you get error if you try to loop through your old ArrayList, because all values have been removed, not just the values, but index as well
How to sort ArrayLists in Java

We can use the Java Collections class .sort() method which sorts Collections such as Lists and ArrayLists and their elements ascending in their natural order.

See examples below:

// Sort ArrayList of integers
ArrayList<Integer> messyArrayList = new ArrayList<Integer>();
messyArrayList.add(3);
messyArrayList.add(1);
messyArrayList.add(15);
messyArrayList.add(5);

Collections.sort(messyArrayList);
for(int i = 0; i < messyArrayList.size(); i++) 
{
   System.out.println(messyArrayList.get(i));
}
// Above will print:
// 1
// 3
// 5
// 15
// Note it can also be used to sort Strings in alphabetical order and other :) Here you can read more about the Collections class and its sort method

Arithmetic operations and working with numbers in Java

How to calculate addition in Java

Addition is super simple in Java, all you have to do is use the plus sign (+) as you usually do, like so:

int a = 5;
int b = 10;
int sum = a + b; // sum will hold the sum of 15
// Note that the "+"-sign is also used for merging Strings via concatenation in Java, but this only happens when pure Strings or Strings + variables are combined with the "+"-sign

// Other example of addition without using variables that hold the values
int otherSum = 10 + 5;

How to calculate subtraction in Java

Subtraction is just as easy as addition in Java, just do as you normally do and use the minus sign (-), like so:

int a = 15;
int b = 10;
int difference = a - b; // the difference will hold the value of 5

How to calculate division in Java

Division is also super easy in Java using the forwardslash character (/), like so:

int a = 15;
int b = 5;
int quote = a / b; // quote will hold the value of 5 as the result from 15/5
// Note if you were to attempt divsion with integers where the integers don't give an even quote/result, values will be lost, 
// unless doing the division using floating point variables such as double - and even then you got to be aware of the round-off errors,
// due to binary numerical system used for computer programming number representation having issues representing floating point numbers with 1's and 0's

// Example of uneven division using integers
int x = 5;
int y = 3;
int result = x / y; // result will hold the value 1 (the number 3 "fits" 1 time within the number 5 when dividing 5 with 3, and since integer, the rest is "lost"/ignored)

// To fix the above misrepresentation issue, we could try doing it with floating point variable, such as double:
double c = 5;
double d = 3;
double doubleResult = c / d; // doubleResult will hold the value 1.6666666666666667 (which seem to be correct in this case)

Another way to not “lose” out on value when dividing using integer is to collect the remainder using modulus (%), more about this later in this section.

How to calculate multiplication in Java

Multiplication is also very straight forward, using the star (*) character, see example below:

int e = 3;
int f = 10;
int product = e * f; // product will hold the value 30

Math rules that apply in Java programming as well

The usage of parenthesis () also can be used in Java to contain calculations so they can be done where they usually could not be done (like in an System.out.println statement). But it can also be used the same way its used in regular Mathematics to give priority to a certain part of a calculation before other parts. See example of both below:

// Imagine we have the following math equation to solve: 5 * 3 + 15 - 3 * 5 / 5 = 27
// This could be altered if we would use parenthesis like so: 5 * (3 + 5) - 3 * (5 / 5) = 37

// Example of doing calculations directly in System.out.println:
System.out.println("Calculation: " + (5 + 3 - 1 * 2)); // Without the parenthesis this would give errors

How to calculate Remainder/Modulus in Java

Modulus can be very helpful whether you need to “rescue” the otherwise lost value of an uneven integer division calculation, or you need to find out if a calculation is even or not (if modulus returns 0 you can be sure it was even since there were no remainder leftover. Calculating modulus in programming in Java uses the percent character (%). See example below:

int five = 5;
int three = 3;
int result = five / three;
int remainder = five % three;

System.out.println("Integer division gave: " + result + " and remainder: " + remainder); // result holds the value 1, and remainder the value 2 (1 * 3 + 2 = 5)

// Example of determining if a number is even or uneven using modulus
int[] numbersArray = {5, 4, 7, 8, 6};
int evenComparator = 2;

for(int i = 0; i < numbersArray.length; i++) 
{
   System.out.println("The number " + numbersArray[i] + " is " + ((numbersArray[i] % evenComparator == 0) ? "even" : "uneven"));
}
// Above will print:
// The number 5 is uneven
// The number 4 is even
// The number 7 is uneven
// The number 8 is even
// The number 6 is even

Working with floating point (decimal) numbers in Java

For this section I refer to the part higher up in this article which discusses round-off errors, type casting, type conversion, doubles, etc.

Controlling amount of decimals using DecimalFormat class in Java

One thing I can add here though, is that there is a DecimalFormat Java class which is very useful when you want to format your floating point (decimal) numbers to a fixed amount of decimals.

Bfelow you can see an example of using the DecimalFormat class to limit our floating point number to 2 decimals only:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2); // Define that we are only interested in 2 decimals

double oldValue = 5.367;

double newDouble = Double.parseDouble(df.format(oldValue).replace(",", ".")); // df.format returns a String value, with "," instead of "." so we use String replace() method "," with "." and parse the String into a double value using Double wrapper class .parseDouble() method

System.out.println(newDouble); // This will print: 5.37 (rounds up)

// Note that if we didn't use .replace() method for the "," to the "." of our df.format() result, program will throw error since double values use "."

If you find this interesting and wish to learn more about DecimalFormat Java class, check out the Oracle documentation of the class.

Introducing the Java Math library (class)

How to calculate the power of a number (2^2 = 4)

Using the Java Math class we can access a built-in static method (hence Math.pow() instead of Math math = new Math(); math.pow() – static methods don’t need to be run via objects of a class in Java) called Math.pow(number, exponent) which takes as you can see a number of your choosing and the exponent you wish to “raise it” with. See example below:

System.out.println(Math.pow(3, 2)); // This will calculate 3^2 and print the result as: 9.0 <- do however note these methods return double data types

How to calculate the square root of a number (sqrt(4) = 2)

The Java Math class also has a built-in method Math.sqrt(number) which will calculte the square root of our given number. Like so:

System.out.println(Math.sqrt(4)); // Will calculate the square root of 4 and print the result as: 2.0 <- this method also returns a double data type

How to get the minimum value of two numbers using the Java Math class min() method

The Java Math class contains a method that helps us calculate the minimum value of 2x given numbers. See example below:

System.out.println(Math.min(15, 5)); // This will print: 5

How to get the maximum value of two numbers using the Java Math class max() method

Similarly to how the Java Math class has a min() method, it also has a max() method which can help us calculate the maximum of 2x given numbers. See example below:

System.out.println(Math.max(15, 5)); // This will print: 15

How to make negative values positive with the Java Math class abs() method

Sometimes in a program, you want to make sure there are no negative integer values. For this you can easily use the abs() method in the Java Math class. Which will calculate the Mathematical absolute of a given number (absolute values in math are always positive). See example below:

System.out.println(Math.abs(-1)); // This will calculate the absolute value of -1 and print: 1

How to round numbers using the Math class in Java

There are two popular ways to round numbers in Java using the Math class library.

One is to use the Math.round(double number) method which returns a long data type that is the result of rounding a number you give to the nearest value. This method differs from the below Math.ceil() method in that it can round both up and down. See example below:

long roundUpNumber = Math.round(1.567); // This value should be rounded up naturally since > 1.5
long roundDownNumber = Math.round(1.267); // This value should be rounded down naturally since < 1.5
System.out.println(roundUpNumber); // This will print: 2
System.out.println(roundDownNumber); // This will print: 1

The second way is using the Java Math class Math.ceil(double number) method which will always round up from the number you give.

So no matter if you want to use Math.ceil() method to round the value of 1.567 compred to the value of 1.267, the answer will always be 2 because the method rounds to the nearest integer that is greater than or equal to the given number.

Note however that this method returns a double data type even if it rounds to nearest integer.

Practical example talked about demonstrated below:

double number = Math.ceil(1.267);
double secondNumber = Math.ceil(1.567);
System.out.println(number); // This will print: 2.0
System.out.println(secondNumber); // This will print: 2.0

How to generate random numbers in Java using the Math class

The Java Math class also contains a method to generate a random double number value between 0 and 1, which has been popularly used for dice programs to generate random dice numbers between 1 and 6 etc. throughout the years, as one example. Practical applications and examples of working with the Math.random() method can be seen below:

int lowerLimit = 0;
int upperLimit = 10;
int randomNumber = (int)(Math.random() * (upperLimit - lowerLimit +1)) + lowerLimit;
System.out.println(randomNumber); // This will print a random number between 0 and 10

Allow me to offer an explanation of how the above formula for random numbers work and why it looks as weird as it does, inspired by this Stackoverflow answer:

The only difference between the Stackoverflow and my approach is I added the lowerLimit to the end, because I thought it looked better, it doesn’t affect the final outcome at all, result is still the same, regardless of which way you write it since it just adds the lowerLimit, and that can be done both at the start or the end (try it if you don’t believe me :P).

Ok so, since Math.random() only gives us a double value between 0 and 1 (not including the 1) we want to multiply it by the range of values we want to get a random number between. So in this case our range is 0-10, this means our random value should be able to be any of the numbers between 0 and 10. We specify this by taking 10-0 (upperLimit - lowerLimit) and multiply our Math.random() with this range: Math.random() * (upperLimit-lowerLimit) a.k.a: Math.random() * (10-0) a.k.a. Math.random() * 10.

As a practical example, imagine that our Math.random() has given us the value 0.2, we then multply this by (upperLimit-lowerLimit), which in this case was 10-0 = 10, we now have the value 2.

But since Math.random() never can reach the double value of 1.0 we need to compensate for this. We do this by adding our lowerLimit value as the Stackoverflow answer explains, we can shift our value range to include our upperLimit.

This still won’t get us the upperLimit value however, so therefore we also need to add the value +1 and then type cast into an integer using (int) to just have our upperLimit and not excess double decimals with it.

Practical demonstration could be as follows:

Highest value we could possible randomly generate using Math.random() is 0.999999... In our scenario above with a wanted range limit of 0-10, we multiply by 10-0 = 10 which gives us 9.99999... And then since our lowerLimit was 0 in this case, +0 won’t do anything, so we’re still stuck at 9.99999... But if we add +1 we are suddenly at 10.99999... if we then type cast this with (int) all of the decimals will be truncated and left we have our upperLimit 10.

So in contast to this, just to see an example where the lowerLimit is not 0, imagine instead we have the range 1-5. lowerLimit = 1, upperLimit = 5. We then multiply by 5-1 = 4.

If we now imagine we still have the highest possible value we can reach with Math.random(): 0.999999... and we multiply this by 4, we get something like: 3.999999...

Then we add our lowerLimit value of 1 to this, and get 4.999999...

As you can see we are still shy of the 5.0 so now we add +1 once again and reach 5.999999... and then truncate the decimals using (int) type casting, and we end up with our upperLimit of value 5.

Generating random numbers using the Java class Random

There is also a Random class which can be a bit more stable in more situations if the random value you are looking to generate is an integer data type value.

See example below for how to generate a random number using the Java Random class:

Random rn = new Random();
System.out.println(rn.nextInt(5)); // This will print random numbers between 0-4, not including the 5 similarly to how Math.random() doesn't include the upperLimit without a little extra effort to make it work

If you want to read more about this, there is a great Stackoverflow answer that explains in detail more about generating random numbers using the Java Random class.

Useful constants that can be accessed in the Java Math class

The Java Math class also contains 2x useful constants for the Mathematical number PI and E.

These are also static and can be accessed as such:

System.out.println(Math.PI); // This will print: 3.141592653589793
System.out.println(Math.E); // This will print: 2.718281828459045

Useful wrapper classes in Java

To start off, I just want to explain what a “wrapper class” is referring to.

In this case our Integer wrapper class for example is a class that is specifically designed to work with the integer data type in Java. It contains useful methods and variables related to the integer data type in Java.

The Double wrapper class is the same but for the data type double in Java.

Integer wrapper class in Java

So we’ve covered the Integer wrapper class briefly and what it can be used for earlier in this article, but this section will cover it more in detail and how its variables and methods can be useful.

Useful variables of the Integer wrapper class in Java

The Integer wrapper class contains 3 useful static integer variables which can be used when you need specific information about an integer variable. These 3 are as follows:

Variable What it contains
Integer.MAX_VALUE The maximum value an integer can store
Integer.MIN_VALUE The minimum value an integer can store
Integer.SIZE The bits storage capacity required to represent an integer

If you ever want to add some “security” to your program to make sure that it won’t crash for example due to integer overload or similar issues, the Integer.MIN_VALUE and Integer.MAX_VALUE could be very useful to add an extra layer of validation and security to your program.

If you’re concerned about storage capacity, maybe you could use the Integer.SIZE variable to adjust program flow based on how much storage capacity is required to store large integer values.

Useful methods of the Integer wrapper class in Java

There are a couple of useful methods contained inside the Java Integer wrapper class, which we will go through below. Those methods are as follows:

Method Description
.compare(int x, int y) Compares 2x integers numerically (Returns an integer value of 0 if x and y are equal, and an integer value less than 0 if x is less than y and an integer value greater than 0 if x is greather than y)
.compareTo(int anotherInt) Compares two Integer wrapper class objects numerically (Returns an integer value the same way the .compare(int x, int y) method does but with the key difference that the “x” value in this situation is the Integer wrapper class object that this method was called on!)
.parseInt(String str) Converts (parses) a String into an integer (Returns the integer representation of the given String – this method is static and can therefore be called on the Integer class directly as such: Integer.parseInt(String str))

Personally I have never had to use neither the .compare() or .compareTo() methods of the Integer wrapper class, because usually conditional operators such as ==, <, >, <=, >= will do the trick.

The Integer.parseInt() method however has come in handy more than once :)

Double wrapper class in Java

Since the Double wrapper class is very similar to the Integer wrapper class, I think it will suffice to link to Oracle Documentation for the Java Double class so that you can check it out for yourselves there :)

Incrementation and decrementation in Java

In programming there is something called incrementation and decrementation. This means increasing an integer variable by +1 when we are talking about incrementation and decrementation when we decrease an integer variable by -1.

This functionality is very useful for when working with counters and in general just want a shortcut for increasing or decreasing a value.

See examples of how its done below:

// Example of incrementation of an integer variable
int counter = 0;
counter++; // Incrementation shortcut is ++ but does the same as counter += 1; OR counter = counter +1; So after this incrementation counter holds the value 1
// Note: counter += 1 is exactly the same as counter = counter + 1; its just another shortcut way of writing it

// Example of decrementation of an integer variable
int nextCounter = 5;
nextCounter--; // Decrementation shortcut is -- but means the exact same as if we had written counter -= 1; OR counter = counter -1; So after this decrementation nextCounter holds the value 4

Conditional statements (IF and Switch) in Java

The purpose of IF statements and guiding program logic in Java

With IF statements we can help guide logic in our programs. IF statements allow us to choose if we want to go one way or another based on conditions that we define using conditional operators.

Basically if the condition you specified evaluates to true, do something, otherwise do something else.

Conditional, relational and type comparison operators to guide program logic in Java walkthrough

Relational operators in Java explained

We also have relational operators which can be used to compare the relationship between our different values that we build our conditions out of, see the table below for these:

Relational operator Explanation
== Equal to
!= NOT Equal to
> Greather than
>= Greater than OR Equal to
< Less than
<= Less than OR Equal to

For practical use cases of each and every one of those, see below:

// Using the Equals to (==) relational operator to compare 2x integer values:
int a = 5;
int b = 5;
if(a == b)
{
   // If a was equal to b, do something...
}

// Using the NOT Equal to (!=) relational operator in practice:
int a = 5;
int b = 15;
if(a != b) 
{
   // If a was NOT Equal to b, do something...
}

// Using the Less than (<) relational operator in practice:
int a = 10;
if(a < 20) 
{
   // If a is Less than 20, do something...
}

// Using the Less than OR Equal to (<=) relational operator in practice:
int a = 5;
if(a <= 5) 
{
   // If a is Less than OR Equal to 5, do something...
}

// Using the Greater than (>) relational operator in practice:
int a = 18;
if(a > 5) 
{
   // If a is Greater than 5, do something...
}

// Using the Greater than OR Equal to (>=) relational operator in practice:
int a = 3;
if(a >= 2) 
{
   // If a is Greater than OR Equal to 2, do something...
}

Conditional operators in Java explained

To guide our logic in our programs with conditions, we need operators to compare merge, separate and negate various conditions with. For this we have conditional operators such as:

  • && (AND)
  • || (OR)
  • ! (NOT)

See examples of how to use these below:

// Example of using the && (AND) operator to combine multiple relational conditions
int a = 5;
if(a < 6 && a == 5) 
{
   // When using the &&-operator like this, both of our combined conditions MUST return true to enter the statement, if one is false, the entire condition becomes false!
}

// Example of using the || (OR - created using the pipelines on your keyboard) conditional operator to check if one or another thing is true
int b = 3;
if(b < 5 || b > 5) 
{
   // When we are using the ||-operator it is enough that ONE of the combined conditions evaluates to true, to enter the statement, if one is false, you still get into the statement 
}

// Example of negating a statement for reverse evaluation (false statements become true and vice versa):
boolean valueAccepted = false;
if(!valueAccepted) 
{
   // If the valueAccepted is NOT true (a.k.a. false) do something - instead of checking if it is true and then do something, do something when its false
}

// Example of combining && (AND and || (OR) conditional operators
int a = 50;
if((a < 100 && a > 0) || a == 50) 
{
   // Notice the parenthesis surround our first conditions combined with the &&-operator
   // these parenthesis are necessary to "bind them together" since their combination is meant as 1 condition
   // In the example above both the condition to the left of the || (OR) operator as well as to the right of it, evaluates to true, 
   // But imagine if we were to change the right condition of the || (OR) operator to == 35 instead, then it becomes false
   // But since the left-hand condition combined with the &&-operator still remains true, we will still get an overall true,
   // since the || (OR) operator accepts either or and don't demand both conditions to be true to evaluate the entire statement to true, 1 is good enough
}

Type Comparison operator in Java explained

There is a Type Comparison operator called instaceof in Java that you can use to determine if an object is of a specific object type.

For example in Java when you are creating classes, you can also create sub-classes or child classes as its also called which inherits the traits of their “parent” classes or main classes.

A more practical example of this could be if you imagine we create a Java class for Car to symbolize a real life Car, then later we might want to also define sub-classes/child classes for the Car object to specify specific types of Cars, such as Honda, BMW, Porsche, etc.

If we consider this scenario, we might at some point want to be able to test, whether a specific object is of type Honda or BMW for example.

This can be done using the instanceof operator in Java.

But for our code example for using the instanceof operator, we will compare child classes and parent classes for simplicitys sake. Like so:

class Parent {}
class Child extends Parent {}
Parent parent = new Parent();
Child child = new Child();

if(parent instanceof Parent) 
{
   // We come here if our comparison using the instanceof operator between our parent object we created and our Parent class is true
   // Similarly if we were to make the comparison between parent instanceof Child - we would get false, because they are 2 different classes and thereby data types! Doesn't matter that they are related :)
   // Poetically its very similar to comparison of human beings, just because parents and children are related, doesn't mean they are the same :)
}

The beauty is that you can comebine the relational, conditional and comparison operators in endless ways to guide your program logic where you want it to go in Java!

Operator precedence in Java explained

These different operators you have now become familiar with that exist in Java have different priorities for when they are used together which is fired first, Oracle Java documentation has a great table which I will borrow a portion from to show here:

  1. “Postfix” a.k.a. variable++ and variable-- has the highest priority
  2. Followed by the “unary” operator such as: +expression -expression and ! (NOT) operator
  3. Then comes multiplicative operators such as: * (multiply) / (divide) and % (modulus)
  4. After that the additive: + (plus) and - (minus)
  5. Then our relational operators such as: < (less than) > (greater than) <= (less than or equal) >= (greater than or equal) instanceof type comparison operator
  6. It is followed by our equality operators as such: == (equals) and != (not equals)
  7. Then comes the logical && (AND) operator
  8. Followed by the logical || (OR) operator
  9. Then the “ternary” operator (used for Shorthand if) ? :
  10. Last but not least comes the assignment operators: = (value assignment) += (variable = variable + ) -= (variable = variable – ) *= (variable = variable * ) /= (variable = variable / ) %= (variable = variable % )

Note that I have not included everything from the table at Oracle Java documentation in this priority precedence list because I focused on including the most commonly used operators focused on Java beginners.

How to create an IF statement in Java

IF statements are quite easy to create, see three examples below:

// The most basic form of IF statement in Java:
int a = 5;
if(a > 3) // When the condition within the parenthesis () is evaluated to true, go inside our brackets {} and execute whatever code we have written there 
{
   // Do something
}

// Example of IF statement with else if clauses to match multiple various conditions and be able to execute various tasks based on whichever condition proves true
int a = 5;
if(a > 2) 
{
   // If a is bigger than 2 (a.k.a. true) do something here

}else if (a < 2) 
{
   // If our variable a is less than 2 then execute the task for this condition
}else if(a == 2) 
{
   // If a equals 2 then do something here
}

// Example of IF statement with an else clause to cover everything that does not match the condition
int a = 3;
if(a < 5) 
{
   // If a is less than 5, then we execute the code here
}else 
{
   // The code here is executed whenever the above condition a < 5 is NOT true.
}

Whats the difference between IF statement and Switch statement in Java

Switch statements can be handy if you have one and the same varible that you wish to test against multiple conditions, but don’t want to re-write the variable in every single condition (which you would have to do in IF statement).

Switch statements are also constructed programmatically differently than IF-statements and don’t share the same flexibility in constructing conditions like the IF statements.

IF statements feel more common than Switch statements.

How to create a Switch statement in Java

When we create Switch statements in Java, usually we first need something to switch out, such as an integer variable with a specific value. Then we can create “cases” similar to conditions for IF statements, where we ask if the integer variable we “switch” will match any of our defined “cases”. If there is a match, the program will similarly to the IF statement, enter the case and execute the code contained within.

Since cases in Switch statements aren’t surrounded with brackets {} such as in IF statements, we need another way of telling the compilator running the program that “here is the end of the case”. We do this using break; statements.

Usually in Java programming, you wish to avoid using break; statements, because its considered bad praxis and whatever you’re using the break; statements for, can usually be accomplished with better coding instead.

Switch statements are the exception to the rule, since we here require our break; statements to prevent the compiler from continuing onwards into the next case and just understand where the specific case code to execute ends.

We also have a default: case in Switch statements, which work similarly to the else clause for IF statements, and will be triggered if none of the specified cases matched and evaluated to true for our switched integer variable in this example. See example below:

int number = 5;
Switch(number) {
   case 1:
      // Code to execute if number == 1
      break; // Break is usually frowned upon being used in Java programming, but its necessary in Switch to "move on" from one statement to the next
   case 2:
      // Code to execute if number == 2
      break;
   case 5:
      // Code to execute if number == 5
      break;
   default:
      // Code to execute if none of the above conditions match our number and give true
      break;
}

To clarify the comparison with an IF statement of similar nature, see below:

int number = 5;
if(number == 1) 
{
   // Code to execute if number == 1
}else if(number == 2) 
{
   // Code to execute if number == 2
}else if(number == 5) 
{
   // Code to execute if number == 5
}else {
   // Code to execute if none of the above conditions match our number and give true
}

Notice how they both consume similar amount of lines of code (lines of code contribute to file size which can affect program execution performance – this however, does not mean the cheapskate with whitespace to get less lines at the cost of readability and easier understanding of the written code!).

However also notice how many times we repeat our number variable in the IF statement for every condition, compared to the cases in the Switch where we do not.

Repetition is usually frowned upon in programming, if it can be accomplish another way without repeating the same code on multiple places in your program (its frowned upon mostly because it makes future maintenance and scalability harder and can easily lead to wasted time down the line).

One could draw parallells to how repetition of same code on mutiple places in your codebase also leads to many more unecessarily added lines of code which in turn can increase file size and thereby affect performance of your program.

Shorthand IF-statement in Java – what it is and how to create/use it

Shorthand IF statements can be very helpful and useful for when you wish to do a simpler conditional determination of what code should be used based on a specific condition for example inside of a System.out.println() statement, without having to create a larger IF statement before the actual System.out.println(). Saving lines of code can actually help reduce program size and thereby increase program performance, as mentioned previously in this article.

Shorthand IF statements define its condition inside of a parenthesis and then has a question mark (?) follow the parenthesis to act as the “bridge” to the true value or the false value (separated with a colon (:)). See example of Shorthand IF-statement below:

(5 > 2) ? true : false; // So the parenthesis is evaluated to either true or false, then the question mark connects the various values to use for whether the condition is evaluated to true or false

// Practical example of Shorthand IF-statement in System.out.println:
System.out.println("The number 5 is " + ((5 % 2 == 0) ? "even" : "uneven"));

Loops (for, foreach, while, do-while) in Java

For-loops explained in Java

For-loops in Java are great for looping through a defined amount of iterations.

Loops can be great for both executing repetitive tasks as well as processing multiple iterations of similar data in one fell swoop. You have already seen examples of iterative loop processing of arrays in the array article section above.

Repetitive tasks that are perfect for loops could be both String building (Note that this refers to String concatenation rather than the StringBuilder Java class), calculations and data list processing.

Difference between a for-loop and the Enhanced (foreach) for-loop

In the regular for-loop we usually create an iteration variable that will act as an iteration counter which will help us keep track of our iterations in the loop while its running, as well as help us refer to the specific data being processed in each iteration (think array processing using for-loop myArray[i]). This iteration variable will also be the key lynch pin in determing when the for-loop is finished based on the condition with which the loop is defined with.

The enhanced (foreach) for-loop will loop through data sets and for each iteration directly extract the iterated value of the data set that it iterates through to work with immediately.

This for-loop/foreach loop as its often called have a more direct connection with the specific data set value of the particular iteration the loop is currently on.

This means that for example if you imagine us having an array with 5 values, when we use the enhanced (foreach) for-loop looping through these, instead of using an iteration value (i) connected to the loop iterations, we use the specific array value to be able to directly access it without having to do value extraction using the square brackets [] as we do in a for-loop for accessing values in an array.

Practical example of this can be seen the section below. And for more information about the foreach loop/enhanced for loop, you can check out the Oracle Java Documentation for it.

How to do “Enhanced for-loop” (foreach loop) in Java

Here’s how you do the enhanced for-loop a.k.a. the foreach loop in Java:

int[] numbers = {1,2,3,4,5};
for(int iterationValue : numbers) 
{
   System.out.println(iterationValue);
}
// This will print:
// 1
// 2
// 3
// 4
// 5
// Notice how we immediately gained access to the array value for our iteration without having to use the square brackets [] to access it with the index we are iterating

// If you want to access the index of an array value using the foreach loop it can be done using counter, but it could feel a bit counter-intuitive compared to using the regular for-loop
// Here's how you would do it anyways if you ever needed to:
int indexCounter = 0;
int[] numbers = {1,2,3,4,5};
for(int value : numbers) 
{
   System.out.println("The Array value of index: " + indexCounter + " is: " + value);
   indexCounter++;
}
// This will print:
// The Array value of index: 0 is: 1
// The Array value of index: 1 is: 2
// The Array value of index: 2 is: 3
// The Array value of index: 3 is: 4
// The Array value of index: 4 is: 5

While loops in Java explained – what they are and how to code them

While loops differ from both for-loops and enhanced (foreach) for-loops in that you specify a condition, and as long as the condition is true, the loop will continue running.

You can create infinite loops using while loops by setting the condition to always being true. That way the loop can never end unless program execution is forcefully stopped.

This technique have been used in viruses that open popup boxes to consume RAM-memory back in the day as a practical example. See practical examples of while loops below:

while(true) // Example of an infinite loop that will never end unless forcefully stopped
{
   System.out.println("Hello");
}
// Above loop will print infinite amounts of the String with value "Hello"

// Another example of a while loop which might seem a bit more practical in nature than the infinite loop, 
// is one where we want a value from our user, and we want the value to be greater than 0, if not, keep asking the user for a value, see below:
Scanner scan = new Scanner(System.in);
boolean valueNotAccepted = true;
int value = 0;
while(valueNotAccepted) // For as long as the valueNotAccepted is true, run the loop
{
   if(value > 0) 
   {
      valueNotAccepted = false; // While loop will "break" and end if condition is not evaluated to true
   }else {
      System.out.println("Your value needs to be higher than 0, please try again: ");
      value = scan.nextInt();
   }
}
// Note, this could also be done having boolean valueAccepted set to false initially, 
// and using the negate conditional operator (!) to reverse the statement, as such: 
// boolean valueAccepted = false; while(!valueAccepted) run the loop because here !false == true (double negative in math gives positive: 1-(-1) = 2 (-- = +)

Do-while loops in Java explained

The do-while loop in Java can be used if you want to execute a statement before evaluating the condition. See practical example below:

int counter = 0;
do {
   // Code to be executed before condition evaluation AND AFTER condition evaluation returns true
   counter++;
} while(counter < 5); // This loop will run 4 times instead of 5 since the condition evaluates counter AFTER the incrementation statement has been executed so counter has initial value in condition evaluation of 1, not 0.

Difference between the while loop and the do-while loop

The do-while differs from the regular while loop in that it evaluates its condition at the end and AFTER first statement has been executed, instead of as in while at the beginning and BEFORE the first statement has been executed.

Practical use case examples of loops in Java

Loops are useful in Java when you need to iterate through stuff like arrays and other list containers.

They can also be useful to execute a repetitive task 1 time instead of having to copy-paste multiple occurrences of the code you wish to execute to do the task.

Loops can be thought of as a sort of automation process where you make the computer work for you to do labor you otherwise would have to do yourself manually to get the same result.

Functions, methods and arguments for re-usable and well-structured code in Java

Difference between function and method in Java explained

A function is usually a callback for re-usable code created by a programmer to not have to re-write the same code over and over, and instead just be able to call on the function to execute said code.

A function is different from a method in that it doesn’t have to belong to a class. Whilst a method is always part of a class.

A function could be created in the Java main method to avoid creating duplicate code for example.

Why use functions/methods in Java

Functions and methods are great for creating well structured code and also collecting re-usable code to easily be called instead of having to be copy-pasted on multiple places throughout your code.

We want to avoid unecessary repetition of the same code as much as possible. A good program should not have multiple copies of the same code preferably. It makes the code harder to maintain and just adds more work and uselessly wasted time in the long run.

If you have a task that turns out to be useful on more than one place, try rethinking the design of the code that executes your task so that you can make it re-usable and can get the same task done via a function/method call rather than copy-pasting the actual code to multiple places in your program.

Functions and methods can in this way also help you build “libraries” with useful code that you have developed for many various occasions so that you in the future don’t have to create the solution from scratch, but instead can call upon function/methods in your library (usually a class file) to re-use those functions/methods functionality whenever they are needed in your programs.

Think of the String class methods for example, this is a great example of re-usable methods with functionality that can be used for any type of String object. Similarly to this, you could create a class called CodingLibrary and just collect all of your best work to be used whenever the need arises! (I will publish such a class on this site in the future with a lot of useful functionality to be re-used for whomever may be interested).

Getter and Setter methods in Java explained

Getter method in Java explained

Getter methods are methods that are part of a class designed to retrieve a variable value from the class, most of the time these variables have private restricted access, which means the only way for someone outside the actual class to gain access to these variables values, is to retrieve them using a Getter method. See practical example of Getter method below:

public class DemoProgram {
   // Member variables:
   private String name = "";

   public String getName() {
      return this.name;
   }
}

Setter method in Java explained

A Setter method on the other hand is used to set values to such variables that the Getter method is usually designed to retrieve with restricted access.

Thats why these two methods usually go quite well hand-in-hand for classes in Java. So instead of retrieving a value from a class, the Setter method actually sets a value to a specific variable thats part of a class. See practical example of Setter method below:

public class DemoProgram {
   // Member variables:
   private String name = "";
 
   public void setName(String name) { // Setters are usually void type since they "execute" tasks, such as change the name without expecting a return to the method caller
      this.name = name;
   }
}

Different method (return) types explained in Java

Methods can be defined as different types – which usually refer to the return data type for the method.

There is one exception for this, and that is the void reserved keyword used to define methods that doesn’t return any value at all.

This is because void type methods execute code purely, without returning anything. Thats why void methods can be very useful for manipulating class data by changing various variable values in the class or even just print something (executing tasks without returning anything to be processed where the method was called).

Other than the void type, methods can be of any type it can have return data type, so you can define a method with return types:

  • String
  • int
  • double
  • ArrayList<Integer>
  • Object
  • BigDecimal
  • int[]
  • String[]
  • etc.

Lot of possibilities exist. See a few examples below:

public int getSum(int a, int b) {
   return a+b;
}

public String concatenateString(String one, String two) {
   return one + two;
}

public int[] makeIntArray(int a, int b, int c) {
   int[] intArray = [3];
   intArray[0] = a;
   intArray[1] = b;
   intArray[2] = c;
   return intArray;
}

Static variables and methods explained in Java

Making methods static in Java makes both variables and methods belong to the class itself, instead of belonging to instances (objects) of the class.

So for example if we have a banking application with account numbers that start from 1000, and for every new account created this account number counter increments by +1.

We need to have this account number counter be the same throughout ALL accounts that are created, if not it would just reset back to 1000 for each and every new object (instance) of the class Account that we create. And to keep this instance-independent and class-dependent instead, we use the reserved keyword “static“.

Usually the access to a method or variable is usually given before the reserved keyword static. See below examples:

private static int a = 0;

public static int getSum(int a, int b) {
   return a+b;
}

Static could and maybe even should be used to declare anything that can and should be class-dependent rather than instance/object-dependent.

This way you could access the variables and methods without having to create an instance (object) of the class first!

Think about the Math class in Java and all of its methods that we previously in this article used. We called upon the methods using the ClassName rather than the name of a created object of the Math class.

This was possible thanks to the methods being defined as static. This allows us to call upon methods directly from the class.

Same thing with Integer.parseInt() which also can be called without having to first create an object (instance) of the Integer class.

We simply just call the static method directly on the class itself, and we can do this because the static methods and variables are instance-independent and instead class-dependent!

Class constructor method explained in Java

The constructor method is the method part of a class that is called whenever an instance (object) of the class is created and initalized.

The constructor method always has the exact same name as the actual class it belongs to in Java.

A class can have multiple constructor methods, as long as the actual method name is the same as the class it belongs to – what can vary between different constructors however, are the amount of input parameters they can have.

For example you could have one constructor that can be called without any input parameters while another one can be called with a String for “username” and a String for “password” which will trigger that particular constructor taking 2x String input parameters that have been designed to know how to deal with 2x String input parameters rather than the constructor that has not. See examples below:

public class DemoProgram {
   // Member variables

   // Constructor #1
   public DemoProgram() {
      // Do something if an instance / object is created of this class without having input parameters on object creation
   }

   // Constructor #2
   public DemoProgram(String str1, String str2) {
      // A second constructor that can be called with 2x Strings to do something with those 2x Strings
   }
}

How to create a function/method in Java

As you can see above, creating a function/method isn’t that difficult. You simply specify the following in this order:

  1. The access which you want to give the method (public, protected, private)
  2. Whether you want it to be instance-independent (static) or not (no reserved keyword necessary then)
  3. And declare the data type it should return (if any, if not: void)
  4. Then you give it a name with which you can call upon it later when you want to use it
  5. And last but not least you specify if any data should be passed into the method via input parameters (note that this is necessary if you want the function/method to work with data that does not exist inside of the method or the class it belongs to).

See an example of a method below:

public static int calculateSum(int a, int b) { // <- note how the first bracket comes straight after the input parameter parenthesis
   return a+b;
}

To disect the above method that we created, you can see we defined it as public – so that any class outside of the project this class belongs to, can access it.

We also defined it as static which means its instance-independent, which in turn means you can call on this method regardless of having created any objects (instances) of the class, so if this method was created as part of a class with the classname Calculator, you could call this method by writing Calculator.calculateSum(5, 3);

We defined that the value to be returned from this method should be an integer data type value and we also named the method calculateSum so that we can use this reference to call on the functionality contained within our method when- and wherever we might need it.

We also passed 2x integer values into the method using 2x separate input parameters of data type integer, that we in the method will use to calculate the sum of those two integer values.

Note that the names you give the input parameters, are the names you have to use to work with the values contained within the input parameters, within your method.

For example in our method above, we named the input parameters a and b, so to work with the value contained within the input parameter a, we must use the variable name a and the same goes for our input parameter b.

What is a recursive function in programming

A recursive function in programming is a function that calls itself continuously until the function has accomplished its task. It can look like this for example:

//Put below into your class
public static int counter = 0;
public static void printMessage() {
   counter++;
   if(counter < 5) 
   {
      System.out.println("Hello iteration: " + counter);
      printMessage(); // Notice how we call the printMessage() function, inside of the printMessage function, trippy right? :P This is what recursion is
   }
}
// Below is what you put in your main method (public static void main(String[] args))
printMessage(); 
// Above will print the following:
// Hello iteration: 1
// Hello iteration: 2
// Hello iteration: 3
// Hello iteration: 4
// Hello iteration: 5

A common practical example to demonstrate recursive functionality is to print the Fibonacci number sequence where you add the previous and current value to determine next value. If you want a challenge you can try doing it using a recursive function :)

Don’t worry if you find recursive thinking to be mind boggling, a lot of people feel the same way (Including me, even after having tested it multiple times at various occasions) :)

In the next and last section of this article we will attempt to sort out exactly how it works and what is happening.

How a Recursive function works in Java explained in detail

So when we have functions calling themselves, each function call is added to the Java “stack”, which will keep track of the order function/method calls will be executed in your program.

When it comes to recursive loops, which are one of the more practical applications, it usually means that the recursive function calls “build” up the Java stack with the different function calls until the specified condition has been met. In above code for example, nothing will start printing until the condition has been met, then the stack will start executing the rest of the code interrupted by the recursive function call in order of last to first function call.

So the first method call will do counter++ to make counter hold the value of 1 , then it will enter the if and print the message straight away (since its before our method call inside of the method). And it will keep running until it has reached completion of our condition for the IF.

If we instead would have something that looks like this:

//Put below into your class 
public static int conditionCounter = 0;
public static int numberCounter = 0;
public static void count() { 
   conditionCounter++;
   if(conditionCounter < 5) 
   { 
      count();
      System.out.println(numberCounter);
      numberCounter++;
   }
} 
// Below is what you put in your main method (public static void main(String[] args)) 
count();

Here the print won’t begin until the condition first has been reached, here’s how it will work:

  1. First method call will increment conditionCounter +1, then check the IF statement and if true, call itself anew
  2. Second we will be in the call from within the method, to the method itself, here we also increment the conditionCounter +1 and check the IF, and if true, call itself anew yet again
  3. This will continue until the condition is no longer true
  4. What then will happen is that the recursive loop will “walk backwards” through the function calls, starting from the last one added to the program execution stack (where conditionCounter became the value 4 and execute “the rest” of that 4th function call AFTER count(); was called for the 4th time.
  5. So in this case that means starting to print the numberCounter (which by the way has value 0 since numberCounter has never yet been incremented because if was placed AFTER the count() function call in our program)
  6. Next up is the second-to-last function call (where conditionCounter became the value 3) – here we also execute the rest of the code after the count() call, so we now print numberCounter again, but which this time has the value of 1 since the 4th function call (first to be executed on the stack) incremented it +1, then we increment numberCounter yet again.
  7. This goes on so the third-to-last function call a.k.a. the first actual function call from within the “original” function call (where conditionCounter became the value 2) will execute the code exactly the same as the two previous “last” function calls so the printout will be 2 this time, and numberCounter increments +1
  8. Then last but not least the absolute very first function call function call where conditionCounter became the value 1 (first time we called our function from within our function) will be executed

See graphical illustration of above explanation below:

Recursive illustration

 

36 thoughts on “Part IV: Introduction to the Java Syntax

  1. forex forum

    Very soon this website will be famous among all blogging and
    site-building users, due to it’s pleasant content

    Reply
    1. Trekka12 Post author

      Thank you for the very kind words :)! Much appreciated, and Very happy you like the contents ^^

      Reply
  2. 博彩开户送现金

    I’ve read a few just right stuff here.Definitely orth bookmarking for revisiting.
    I surprise how much attempt you put to make such
    a fantastic informative web site.

    Reply
    1. Trekka12 Post author

      Thank you :)! Glad to hear it, Much appreciated, and Very happy you like the content ^^

      Reply
    1. Trekka12 Post author

      Not sure how you mean what I would suggest in regards to what? But thanks for the very kind feedback, glad you liked it! :)

      Reply
  3. astrologiaagapikaisxeseis.wordpress.com

    Juust wish to say your article is as astounding.
    The cleearness in your post is just nice and i can assume you are an expert on this subject.

    Fine with your permission allow me to grab your feed to keep updated with forthcoming post.
    Thanks a millikon and please keep up the rewarding work.

    Reply
    1. Trekka12 Post author

      Really appreciate the kind feedback and inspiring praise, thanks a lot! More posts will come in future, sadly it might take a while due to other engagements at this moment in time. But feel free to check out previous contents if you appreciated this article :)!

      Reply
  4. Bandar Domino

    I’m not certain where you are getting your info, however good topic.
    I must spend a while studying much more or working out
    more. Thanks for great information I was searching for this information for my mission.

    Reply
    1. Trekka12 Post author

      I’m simply writing down what I’ve learned over the past years of studying these subjects :) Glad you liked it!

      Reply
  5. Sälja och köpa juridiska tjänster

    Appreciating the hard work you put into your site and in depth information you offer.
    It’s nice to come across a blog every once in a while that
    isn’t the same out of date rehashed information. Great read!
    I’ve saved your site and I’m adding your RSS feeds to my Google account.

    Reply
  6. osg777

    Hurrah, that’s what I was searching for, what a information! present here at this webpage,
    thanks admin of this site.

    Reply
  7. when hong kong got freedom

    Hi there! Someone in my Myspace group shared this site with us so I came to
    give it a look. I’m definitely loving the information. I’m bookmarking
    and will be tweeting this to my followers! Terrific blog and terrific design.

    Reply
  8. Coverband en DJ

    Wonderful web site. Lots of useful info here. I’m sending it to
    some buddies ans also sharing in delicious. And certainly, thanks in your sweat!

    Reply
  9. 토토커뮤니티

    My spouse and I absolutely love your blog and find many of
    your post’s to be what precisely I’m looking for.

    Would you offer guest writers to write content to suit your needs?
    I wouldn’t mind creating a post or elaborating on a few of the subjects you write with regards to here.
    Again, awesome web log!

    Here is my blog post: 토토커뮤니티

    Reply
  10. 바카라사이트

    I absolutely love your blog and find many of your post’s to be what precisely
    I’m looking for. can you offer guest writers to write content available for you?

    I wouldn’t mind writing a post or elaborating on a
    few of the subjects you write concerning here.
    Again, awesome site!

    Reply
  11. 안전놀이터

    Hello! This post could not be written any better!
    Reading this post reminds me of my previous room mate! He always kept chatting about this.
    I will forward this post to him. Pretty sure he will have a
    good read. Thank you for sharing!

    my webpage; 안전놀이터

    Reply
  12. Cliff

    Having read this I thought it was really informative.
    I appreciate you taking the time and effort to put this informative article
    together. I once again find myself spending a significant amount of
    time both reading and commenting. But so what, it was still worthwhile!

    Reply
  13. Valarie

    Hello There. I found your blog using msn. This is a really well written article.
    I will be sure to bookmark it and return to read more of
    your useful info. Thanks for the post. I will certainly comeback.

    Reply
  14. Billy Thrall

    I’m impressed, I must say. Rarely do I encounter a blog that’s both educative and amusing, and without a doubt, you have hit the nail on the head. The issue is an issue that too few people are speaking intelligently about. I am very happy that I found this during my hunt for something relating to this.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *