For all you beginners eager to get started we will begin by explaining the basic concepts of Java coding.

Basic concepts of coding in Java

When you start coding in Java as I mentioned in the previous post you create a classfile and possibly a package to hold it.

Both of which also briefly were described in previous post.

Although – now its time to go deeper into the actual classfile that was created and have a look at what it actually contains so we have an understanding of why a .java file for example is being called ”classfile” because that makes little sense for some of you at this moment probably.

Alright so our classfile looked like this:

classfile

In the next section we will in detail cover a little more both what the package mean- as well as the class code.

Packages to organize classes and program files

The first thing we see on row 1 of the code document is the statement "package testproject;", I think you can guess what this is, but just to clarify it needs to be there to tell which package the code classfile (the java file containing the class) belongs to.

Classes – the specifications of all Java programs

After this declaration of ”what belongs to where”, we have our "public class testclass" which is our class declaration for this file. Between the left bracket ”{” and the right one ”}” our entire ”class” exists. So a class basically is a way to contain and structure code like an exact specification with data (variables) and a set of instructions (methods – what happens when). And classes are the fundamental building blocks in Java programming.

Main-method – the method that runs Java programs

In our case our public class testclass that Eclipse created for us contains only one method which gives our class the ability to be ”run as a program”. This method will be required for every single Java program to be run/executed. So inside of this method we can then place all the code we wish to run. As you saw with the Hello World! example program described briefly in the previous Java article of setting up the Eclipse development environment – once the program was executed, whatever was contained within our ”Main-method”, was executed and run as a program. You can see the Main-method and how it looks like below:

1

publicstaticvoidMain(String[]args){}

Alright so we are going to explain a lot of juicy stuff in this article, starting with one of the most useful and appreciated techniques for humans when it comes to writing code, namely: Indentation!

So what is ”indentation”? Well kind of like the headline says: it makes code more easily readable and better structured for humans. By typing code in a ”hierarchical manner”.

– ”Hierarchical manner” – means a tree-structure with different levels related to one another – much like the Windows Explorer folder structure. For example if we have folder2inside offolder1, folder1 is Level 1 in the hierarchy tree, while folder2 that is inside of folder1 is at hierarchy level 2 in the hierarchy tree. Hope that helped explain it a bit better 🙂

Machines basically dont care about whether you are coding with indentation or not, but it might just help you keep track of what you have coded and what belongs to where(!).

Sometimes, especially with larger programs it is very easy to get lost in your ocean of code that has been created over many hours of coding. And this is where indentation can be a lifesaver and the difference between 1 hour- compared to 1 week of debugging and error-searching in the code. And trust me- the longer you sit with something like this, the less fun it is..

As you can see in the image above "public class testclass {" is the 1st hierarchical indentation level of our program, everything contained within it gets a new hierarchical levels such as our Main-method which has an additional indentation ontop of our previous one of approximately 3-4 whitespaces or 1 TAB. Creating a second level of indentation. And since this is a method which also contains code within itself, the contained code will also get additional indentation with another 3-4 whitespaces or 1 TAB to indicate that the contained code belongs to the Main-method. And like this it can continue forever, hopefully though it doesn’t have to do that since it gets very messy after having nested enough blocks of code. Since every time you nest new code within old code, it gets pushed to the right with 3-4 whitespaces/1TAB which gives less room to actually write code on the first row before the row ”breaks” and no more code can fit on it, which can be a bit annoying, frustrating and very ugly sometimes. I think you can imagine how that would be like. Not so much fun.

You can in Eclipse set your own custom amount of spaces or tabs for indentation, or simply keep the default one.

Java Syntax

Java is strictly (strongly) typed , not loosely (weak) typed

So what do I mean by this then? Well when you discuss different types of programming languages you usually separate them- by among other factors- whether the language is so called: ”strict” or ”loosely” typed. What this means is that when a language is strict, it will not accept any ”loosely” typed code, basically generates errors more often if code is close but not quite proper to the standards of the language that has been set. Compared to a loosely typed coding language which isn’t as strict (obviously) which also means that running the code is more accepting to alterations and similarities of different parts of the code. Some languages allow you to in some cases for example skip alltogether the brackets that show in what area the code is being contained, or even skip semi-colons which declare statements to be done by just assuming for example ”at the end of this line of code the statement is over”. In a strictly typed language there can be a HUGE difference between upper-case and lower-case letters for example. It may mean completely different things.

Stuff like that.

Java is a strictly typed language and hence is very strict about the ”syntax” (the way code is written) its accepting. I personally think this is a good thing, because I like the structure it brings and the purity of the Java code. Everybody has to use a specific way of coding, a strict one at that, and there aren’t a lot of different ”similar” ways to coding the same thing.

Everybody has different opinions about this, but I like Javas simplicity and purity of coding. Its clean and easy to read no matter who wrote it (usually).

Semi-colons and their function

Basically you tell Javas compiler and many other programming languages compilers as well that a statement is over with the use of semi-colons.

The compiler needs this to know where one statement ends and the next one begins, without it, it confuses the compiler and may cause many unwanted errors.

Comments and documentation of code to explain what the code does and make it memorable for future

Alright so hopefully indentation is clear for you now, lets move on to ”comments and documentation of code” which is an option for almost, if not- all programming languages today, although usually in different ways between different coding languages!

When you code make sure to leave comments in your code to explain things either for your own sake for the future, or to inform others what that specific piece of code stands for and does, to help them understand it as well.

When the code is compiled and run all comments will be completely ignored by the compiler, its just some ”invisible” padding of the code documents to the compiler, But! for humans, it makes the programs much easier to understand.

In Java there are three major ways of documenting code:

// for inline-comments limited to 1 line of text

/* comment goes here */ for block-comments that stretches over several lines

/** */ for documentation comment which is used to make official documentation of methods in Java programs (this is done in a specific strict way)

Example of a document comment which differs quite a bit from the other two options is as follows:

1

2

3

4

5

6

7

8

9

10

/**

* Description of the method and what it does is placed here

* @param - nmbr - is how you document parameter(s) for the method, if more than one just type them on top of eachother in this comment

* @return result - and maybe a description of what the returned result variable contains or such

*/

publicintourMethod(intnmbr){

intresult=0;

//method statements

returnresult;

}

Why JavaDoc documentation comment looks and is typed differently from other comments is because there are programs that can make it easy to get an overview of these comments to immidately get an overview of all the methods and how they work in a program – kind of a bit like a recipe with all the ingredients and instructions.

Thats all you need to know for now, more details about this we will see when we start coding later in this article 🙂

camelCase and naming conventions in Java

Ever heard of something called camelCase? If not- its a naming convention for how you should name for example: classes and/or variables in Java, but not Java exclusively – camelCase is a good practice to adopt for all programming languages together with the naming practice of choosing names that actually has something to do with the variable, method or class that you are naming.

For example if I have a ”step counter”-variable to keep track of how many steps I’ve walked – an appropriate name could be stepCounter (notice how camelCase always starts with lower-case letter first for variables, while CamelCase for classnames have an upper-case first letter as well).

To summarize:classnames should have capital first letter as well as capital letter of following words in the name, whilst variables and methods should have lower-case first letter and capital first letter on following words in the names. That is a good practice to follow 🙂

Numbers are allowed to be used in variable and classnames as well as methodnames AS LONG AS they are NOT first in the name. For example:

ready1 = OK

1ready is NOT OK

How to import external classfiles/libraries to work with them in Java

When you want to access and work with External classfiles and libraries (they mean same thing basically) you have to import them at the top of your classfile that will be using- and accessing them AND their variables and methods. I will show how you do this for the following classfiles/libraries: Scanner, BigDecimal, Date, SimpleDateFormat, Arrays, ArrayList and Graphics, Color, Image and Font – because these are the libraries/classfiles we will be using and accessing throughout this entire article!

You do this by writing like so:

1

2

3

4

5

6

7

8

9

10

import java.util.Arrays;

import java.util.ArrayList;

import java.util.Scanner;

import java.util.Date;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;

import java.awt.Graphics;

import java.awt.Color;

import java.awt.Image;

import java.Font;

The library classes: String, System and Math are accessible for all program as a default, so you do not have to import these ones into your programs to work with!

Another thing worth pointing out is that in the above example we imported every single class/library on its own specifically, the possibility of importing entire libraries exist in Java as well – for example the Library java.util which holds our: Arrays class, ArrayList class, Scanner class and Date class and can be imported in one row of code instead by typing:

1

import java.util.*;

The star-symbol (*) is a universal sign for ”all” in most programming contexts.

But when you import the library files like so – it also means that you import ALL of the library files, not just the ones that you needed, which might slow down the program a little bit or such.

Variables in general (in Java)

Alright, finally time to dig a bit more into the actual coding syntax of Java. Let’s talk about Variables, what are they? Variables are storage locations in computer programs – each variable has a name and holds a value. It’s as simple as that 🙂 with a few extra bells and whistles in Java 😉

The values being stored in variables can have different (primitive) Data Types.

(primitive) Data Types in Java

The most commonly used ones are as follows:

int

double

float

String (or any object)

boolean

There are more, but these are- and will be the most commonly used (primitive) data types – at least for us in this article.

However just to inform you in general of other primitive data types here you have them:

char (store one character (like number, letter or other) only),

long (64-bit storage variable with max storage capacity of 2^63-1),

short (16-bit storage variable with max capacity of storing a number value of 32’767) and

byte (8-bit storage variable with max capacity of 127 number value).

char, short and byte are all good to use when saving storage space actually matters. The long variable is an extension to integer which has 32-bit storage to a max value of 2^31-1.

What separates float from double seeing as how the both are floating-point number variables (decimal numbers) is that float is like char, byte and shortdesigned to save space and neither float nor double should Ever be used for currency number storage(!). For this a class and Java library called BigDecimal is used instead, to offer appropriate precision and avoid any ‘round-off errors’.

Note that String and other Objects are not considered ”primitive variables” but instead Object variables since they are based off classes.

Below I show examples of how to code variables of each ”common” (primitive) data type:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//Creating an integer that holds the value of 5

intnumberFive=5;

//Creating a double floating-point number variable holding the value of 3.5

doublefpValueOfMiddleBetween3and4=3.5;

//Creating a float floating-point number variable holding value of 3.5

floatfloatVariableMiddleValueBetween3and4=3.5f;//note the f after the floating-point numer at the end!

//Creating a boolean variable to store a boolean value of true or false

//Creating a string variable with textstring value using single quotes ('')

Stringtext2='this is my text';

As mentioned above String or any object is one of the available data types listed although not included as a primitive data type. You can create an object of a class such as String – which then allows access to that classes methods and variables – this is what allows us to handle textstring as data in Java – the class/library called String has been built to handle specifically Textstrings with its methods and all the necessary variables its class holds so that we can simply call upon it whenever we are about to handle textstrings as data for our program!

The textvalue is stored within a variable of data type String (or Classname if another class is to be used to create an object variable of a class).

More advanced structures for storing data in Java (Arrays and ArrayLists)

Beside the primitive data types that exist in Java there are moments when you need ”a little extra flare” to the way you store your information.

An example of this is when you are going to store multiple values and want to be able to- for example loop through- these values and find the right one, or sort them in a specific order etc. This is where Arrays and ArrayLists come into the picture and shine the brightest.

Basically you can create arrays of any particular data type whether its String, integer, object/class, double, etc. This is done in the variable declaration stage as you will see example of below:

1

2

3

//Creating a new array of type integer (all values in the array (which basically is a list for values) must be of type integer)

//and we create one with 10 value slots as you see to the right of our "assign character" the equal sign (=): [10]

int[]anArray=newint[10];

That is however one of two ways you can declare/create an array in Java. There is a second way that lets you assign values right at the declaration stage and looks like follows:

If you however created an array as we did first with the anArray = new int[10] you might want to set values to the various positions inside of the created array. This is how you do that:

1

anArray[0]=5;//sets the value of slot 0 (first slot in the array) to the integer value of 5.

To access these values however, a different approach is used since you somehow have to ”navigate through” the different slots in the array. Each slot in the array is given a numerical index key. See below.

1

2

3

4

5

6

a2ndArray[0]=1//index always starts at 0 in programming so to extract first value from array always index key = 0 for that slot

a2ndArray[2]=3//since we count with 0 slot index 2 = value 3 - it can be a bit confusing at first, you will get used to it though :)

a2ndArray[10]=error// since declaring a variable with 10 slots mean indexes: 0-9, index 10 doesn't exist unless we have an array with 11 slots

//Practical use example of how to extract one of the values for practical application

System.out.println("This is out 1st value of our a2ndArray array: "+a2ndArray[0]);

Alright so now we can create arrays of various data types (just switch out int in front of [] to whatever data type you wish to create an array for) as well as initialize values with two different approaches and retrieve values from within an array. Another possibility of storing data in arrays that we haven’t covered yet is the storage of data in something we like to call ”multidimensional arrays” which basically is arrays stored within arrays. But these are a bit more advanced and we will not go through them in this article. Perhaps in the future.

I say thats enough arrays for now. However there is a sort of extended alternative to arrays for storing information in lists in Java which is extremely effective, user-friendly and useful and is called ArrayList and is basically like String in the way that it is a class with methods and such to help handle data storage in an effective way – kinda like how Strings methods help us handle textstring data.

Alright so a quick intro to ArrayLists as well and then we move on to the next area 🙂

So the truely awesome thing about ArrayLists compared to arrays is that they are super easy to sort and have tons of usefeul methods to manage the data being stored within them compared to regular arrays which usually requires you to shuffle around the contents with loops and crap to get the same result. Even if this sometimes is what makes arrays hard to work with, it is also one of the things that makes them so effective for simpler tasks such as storing and looping through its values. As long as you don’t have to shuffle around the data stored within regular arrays they are totally OK in my opinion for storing data in listformat.

Although if you think the methods of the ArrayList is better suited for your particular needs- by all means, create one, use one and do it with ease 🙂 To get a better picture of what ArrayList has to offer, you will get a list of some methods that I find very useful:

.add(int index, Object element)

Adds an element to the specified index

.add(Object element)

Adds the element to the end of the list

.clear()

Clear all of the elements from the ArrayList

.contains(Object element)

Returns true if the specified element could be found within the list! (no shuffle needed – it does that for you)

.get(int index)

Returns the value stored at the specified index

.indexOf(Object element)

Returns the index position of the specified element if it is stored in the ArrayList, if not it returns -1

.remove(int index)

Removes the element stored at the specified index

.set(int index, Object element)

Replaces the element at the specified position in this list with the new specified element

.size()

Returns the integer size of the ArrayList (very useful for iterating through and you know how many slots to iterate through)

.isEmpty()

Returns true if list has yet no values in it

Now that we have all of those easily accessible and overviewed, as you might have noticed I put a dot (.) in front of every method, this is because when we have created an ArrayList and we want to call a method upon that ArrayList, we use the dot-notation to do so, for example:

1

ourArrayList.add(0,"new textstring value");

The possibilities with ArrayList are endless!

But to have any use of the methods listed above, we first have to learn how to create our ArrayList. This can be done in one of three different, but very similar ways:

1

2

3

4

5

//1st way: Just create the list, no values, no specified length.

ArrayList<String>stringArrList=newArrayList();

//2nd way: Create the list with specific amount of slots (kind of like our regular arrays!)

ArrayList<String>anotherStringArrList=newArrayList(5);

The third way uses an already existing collection of values to create the ArrayList which seems a bit over the top for this introduction so I will not walk through doing that.

However I will point out another reason why ArrayLists are so great compared to regular Arrays: They do not have to specify their length at the moment they are created! As you could see in above example where we left out the size of the ArrayList. Perhaps you are wondering why this is then? Well its because ArrayList will expand its size after time new values gets added to it. Cool huh?

Alright so start experimenting with ArrayLists and have fun with it, don’t forget experimenting with regular Arrays as well though. Both can be very useful to know.

Various ways of creating variables

You can create a variable in many different ways in Java, either by only specifying the name of the variable together with the Data Type and thereby reserving the storage location for that name and type in the memory of the program until you are going to use it, OR you can assign a value immidately when you are creating your variable – this is called initiatlization and is done by the help of the ”assign value”-character in Java which is the equal sign (=). If you have a lot of variables you wish to create you can do this all at once, instead of separately by separating the variables inline using commas (,). Variables created this way can both be created: with and without values. Example of all of these ways is shown below:

1

2

3

intnumbersVariable;

intnumbersVariable=0;

intfirstInteger,secondInteger=0,thirdInteger=56;

Member variables in Java – What are they and what are they used for?

There is something called ”member variables” and these are variables you create to ”belong” to the entire program. And they do this by having you create them at the top of the class area outside of any (internal) methods – this way the variables ”scope” will stretch to reach throughout the entire program(!). This is very useful for variables that hold information that more than one part of the code will use. For example if you have color variables or dimension property variable that will be used by several methods you can create these variables outside of any methods, at the top of the class area, and they will be able to ”reach inside” of any methods contained in the class.

Variable scopes in Java

Depending on where in the code you create the variable it will have a specific ”scope”. Which basically means that it has restricted areas in which it can be accessed and used.

To demonstrate this with an example imagine that you create a variable inside of a method, that variable gets restricted by that method, it cannot reach outside of that method(!).

This you have to think about when writing code in Java so that your variables don’t have to be repeated, but instead you plan their creations so that they can reach to every destination that needs the data your variables are holding.

How to create constant variables in Java and does this mean?

Alright so we’ve gotten this far – what about when you want to create a variable which never need to change. Say you are building a Graphical interface perhaps, and this interface has a fixed width that won’t change at all. Then this width could be declared as a constant variable in Java.

This is done by using the reserved keyword: final. With final keyword and some different naming conventions (all capital letters with underscores separating more than one word) you can create a fixed variable which will never change and always be constant in your program! This can look like the following:

1

finalintCLIENT_WIDTH=500;//underscores are allowed in Java naming conventions as well

Now we have created a constant variable called CLIENT_WIDTH which has an integer value of 500 and will never change in the program! There you go 🙂

Specify states of- and access to: variables, classes and methods with ”reserved keywords” such as: static, protected, private and public

In java there are more ”reserved keywords” (which by the way are not allowed to be used as regular variable names(!)) such as static, protected, private and public. These keywords are used to define state of variables, methods and classes to ”the outside” of your program.

For example, declared ”private” variables means that these variables can ONLY be accessed from within the program/class and its own internal methods. And they will be unreachable by outside programs. So for example if we have two programs/classes that should be working together, and in one of them you have declared a private variable ”appleWeight” and you have a method in the other class called ”calculateApplePrice” which uses an algorithm based on the apples weight (appleWeight variable) – this method will NOT be able to reach the variable because it has been ”locked” using the reserved keyword: private. Sometimes this can be very useful, but sometimes this can complicate things if you don’t know what you are doing. So hopefully now you understand how the keyword private works. And using it for a variable could look like something as follows:

1

privateintappleWeight=125;//remember to use lower-case on all of the reserved keywords: static, private, public and protected

The keyword static on the other hand is famous for being used to declare so called ”static variables” and methods that belong to a class and not to objects/instances of classes. Which basically means that the variable or method stays the same throughout all different objects/instances of a class – this can be very useful. For example if you are building a virtual bank and to create new accounts the account numbers need to be unique, and they need to start from somewhere but still keep track of ”how far” the account number integer has increased from all the account creations that users have done. If you have a static integer this could hold that value throughout all the different instances being created of the bank. Say that you have two different instances running and the first instance create a new account and our static integer was initiatlized as the integer 1000 – then when the account is created in the first instance, this static variable increments to grow by 1 number and become 1001. Now the other instance wants to create an account as well and this also increments the static integer variable – giving it the integer value of 1002 because throughout all instances 2 accounts have been created and a static variable is keeping track of those!

The reserved keyword public basically means that any outside program or class can access the method, class or variable and is probably one of the most normal ones to use to declare variables, methods and classes in programs.

The reserved keyword protected differs quite a bit from both public as well as private as something a bit inbetween by letting ”related programs/classes” gain access to the protected classes, variables or methods. This means for example if you have two combined classes that work with each other, these can access the protected declared variables, methods etc. But nothing that isn’t related to either one of these classes or programs can access the protected variables. Classes can be related by existing in the same package, or being subclass of another class. (part of Object oriented programming design concept which is more advanced than what we will cover in this article).

Strings and the String class in Java

I felt the need for a section of its own when it comes to Strings in Java, simply because there is so much you can do with strings. Some things of which we will cover in this section:

Concatenation – the concept of merging strings with other strings or other variables

Escaping characters in strings and why this sometimes is required

Useful methods in String class

.substring(int beginIndex, int endIndex) | A method to extract a ”substring” of the original string by stating from what beginIndex to what endIndex a string should be extracted

.charAt(int index) | Finding specific character at an index point of the string

.contains(CharSequence cs) | Used to find out if a CharSequence (a type of textstring) exists inside another string

.equals(Object element) | Comparing two strings with each other – returning true if the same (can be done ignoring lower-case and upper-case letters as well with another similar method)

.length() | To find out the length of the string (amount of character it consists of)

.split(String regex) | Split a string up into different pieces stored in an array – for example divide a URL’s different parts by splitting the string on dots (.) as regex = ”.” resulting in array with www, domain and com as values in an array, instead of a string with ”www.domain.com”.

.toLowerCase() | Turn entire textstring into lower case letters – very useful if you are working with input for example that must be lower-case or conditional statements

.toUpperCase() | Turn entire textstring into upper case

.trim() | Lets you ”trim” away all whitespaces that may exist in front of – or after the actual text content in the string

Concatenation – what is it and how does it work – the concept of merging strings with other strings and/or other variables

Concatenation is as the title implies- a way of ”merging” one string with either another string or together with other variables.

In Java we do this by using the ”+” operator to merge strings and variables together. This is done for example like so:

1

2

3

4

5

6

7

8

9

10

11

StringaString="This is a simple string";

Stringa2ndString=": plus another one";

intfiftyFive=55;

//Now we are going to concatenate all of those three variables together to form a new string with them all included

aString=aString+a2ndString+", and a number: "+fiftyFive;

//The above concatenation will output the following string: "This is a simple string: plus another one, and a number: 55" and it will be

//stored within the variable aString

//There are shortcuts to merging variables together when we based our merge on our aString see below a shortcut:

aString+=a2ndString+", and a number: "+fiftyFive;

The above shortcut of concatenation basically says that: since we want to merge aString with aString (same variable) we can simply say += and the base string we store the merged one in (aString) will be concatenated (merged) with itself first(!) before anything else happens! This is since we want to keep aStrings original value: ”This is a simple string” in the beginning of the newly concatenated string.

If we were instead to type as follows:

1

aString=a2ndString+", and a number: "+fiftyFive;

Then we would end up missing the beginning that we wanted in our string, left would be the string ": plus another one, and a number: 55". Because we didn’t ”save”/keep the aString original value in the concatenation!

Escaping characters in strings and why it is sometimes required

Sometimes when you are coding in Java there will be moments when you want to use quotation marks (” ” / ‘ ‘) for example in a string which is surrounded by the same quotation marks, for example:

1

StringaString="it was the term "idiot" that really threw me";

What will happen if we have that string- is that we will get errors, because basically the machine will interpret the above value as first one string "it was the term " and then weird letters that don’t belong: idiot and then another string " that really threw me" – we will get error because the machine will misinterpret our intentions for this string. So how do we ”fix” this so that the machine understands what we mean then? Well its quite simple actually, we just have to Escape the double quotation marks inside of our string and the machine knows that they are characters inside the string and not part of the actual Java code syntax. This is done as following example shows:

1

StringaString="it was the term \"idiot\" that really threw me";

Now thanks to the backslashes (\) the code will know what is syntax, and what is string content. Backslashes are used for many different coding languages to escape characters in strings, not only Java.

charAt(int index) | Finding specific character at an index point of a string

System.out.println(aString.charAt(14));//this will print out the output "l" because the charAt counts WITH index of 0, so 14 index means 15th letter

contains(CharSequence cs) | Used to find out if a CharSequence (a type of textstring) exists inside another string

Practical use example:

1

2

StringaString="find the needle in the textstring";

System.out.println(aString.contains("needle"));// will return true

Note that above code example asked for an input variable of type ”CharSequence” and it accepted that we typed a string. We will Not look deeper into this due to lack of time. You can search for CharSequence and try to figure it out on your own though if you are interested in this 🙂

equals(Object element) | A method to compare two strings with each other – returning true if they are the same (can be done ignoring case sensitivity as well)

If however we were to change a2ndString‘s textvalue to capital T in the beginning, it would return false!

There is however an alternative method called .equalsIgnoreCase() which would return true since all the letters are the same if case sensitivity doesn’t matter.

length() | To find out the length of the string (amount of characters it consists of)

Practical use example:

1

2

StringaString="this";

System.out.println(aString.length());// would return and output the length integer 4 of the string

Notice how Strings method for finding out the length is .length(), whilst Arrays only has a variable which keeps track of the length of the array (amount of slots) which can be accessed by .length.

split(String regex) | Split a string up into different pieces stored in an array – for example: split up a URL’s different ”parts” by splitting the string on dots (.) getting an array with 3 String values of ”www”, ”domain”, ”com” instead of the one string split ”www.domain.com”

We will demonstrate the above practical example of splitting up the different parts of a URL by telling split to use dots (.) to split the string with.

1

2

3

StringurlString="www.domain.com";

String[]splitArray=urlString.split("\\.");//dots (.) mean "any character" in regular expressions so we must double blackslash escape it for this to work

System.out.println(Arrays.toString(splitArray));//the splitArray will contain and output "www" as a string on first index, "domain" on second, "com" on third

Arrays.toString(splitArray) method was used for simple output of the contents of our array in this case, note that the toString() method was fetched from the Arrays class which is the collective class with methods that work for any and all arrays in Java.

toLowerCase() | Turn entire textstring into lower case letters – very useful if you are working with input for example that must be lower-case, or if working with conditional statements

I think this one is pretty self explanatory – every time you call .toLowerCase() method on a string of your choosing, that string will be all lower-case letters!

toUpperCase() | Turn entire textstring into upper case letters

Same goes for this one but reverse – instead of lower-case, the string will consist only of upper-case letters.

trim() | Lets you ”trim” away all whitespaces that may exist in front of – or after the actual text content in the string

Sometimes for weird and mysterious reasons strings created by programs can contain whitespaces either in front of- but part of a textstring, or after the text in a string.

By getting rid off these unwelcome whitespaces and get a ”clean” string, one can use the String method .trim() which will return a version of the string without the unecessary whitespaces.

As with most programming languages, Java offers the basic logical capabilities to calculate values using fundamental arithmetic operators for addition, subtraction, division, even remainder as well as multiplication.

Only difference compared to a computer calculator is that you first have to create variables to hold the data with which you want to use for calculations. For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

intfirstNmbr=5;

intsecondNmbr=10;

intthirdNmbr=3;

intresult;

//Let us try some addition first:

result=firstNmbr+secondNmbr;//this will give us result having a value of 15 (5+10)

//What about subtraction then?

result=secondNmbr-thirdNmbr;//this will give us result having a value of 7 (10-3)

//And division?

result=secondNmbr/firstNmbr;//this will give us result having a value of 2 (10/5 = 2)

//Another perhaps a bit "weirder" division but very good for learning

result=secondNmbr/thirdNmbr;//since we are calculating with integers, result can only be an integer as well, and 3 fits 3 whole times on the number 10

//This seem like a good example to reveal the rest of the integer division between 10 and 3 - with help of remainder (leftover integer)

result=secondNmbr%thirdNmbr;//this will give us result having a value of 1 (10%3 = 1 leftover integer)

//How about multiplication?

result=firstNmbr *thirdNmbr;//this will give us result having a value of 15 (5*3)

//Shall we mix it up and do a bit more advanced calculations perhaps?

result=(firstNmbr *thirdNmbr)-secondNmbr+thirdNmbr/thirdNmbr;//this will give result 6 because as explanation below states:

Round-off errors and How to compensate for/fix them in Java

”Round-off errors” is something everybody coding in Java should know about, so I figured I would walk through it just to inform you.

Round-off errors might not be restricted to Java programming, in fact you can see it in real life as well- and is based on regular mathematics, if you consider when you do the division of 1 divded by 3 (1/3), and restrict the answer to only 2 decimal points, you will have the value of 0.33 right? Well what happens when you then multiply this by 3 hoping to reach a whole (1)? Well you end up 0.01 short don’t you? Since 0.33 * 3 = 9.99 you are missing out on 0.01 in value because of the restriction at 2 decimal points. But of course we knew this would happen already. In Java something similar happens because of the fact that numbers are represented in the binary number system(using only 0’s and 1’s) in the computer instead of the decimal number system we are used to. You can get round-off errors when binary digits are lost.

For example: If you were to declare a double variable with the value of 4.35 and another double variable of value 100 and try to get the product result of a multiplication between the two you would actually end up getting 434.999…

This is because in the binary system there is no exact representation of the number 4.35, just as we don’t have exact representation of 1/3 in our decimal system. The representation used by the computer is just a little less than the actual 4.35 value, so when multiplying with a value of 100, we come up a little bit short and hence not getting the proper representation of the calculation we wanted to do.

A ”hackish” fix for this would for example be to round the result off to the nearest integer.

Kudos by the way goes out to Cay Horstmann with the book: Big Java Late Objects, from which this explanation is paraphrased from.

It can be a bit slower to use than normal number variables, but on the other hand its virtually limitless and the best option for dealing with currency values(!).

BigDecimal class have its own custom methods for doing basic arithmetic operations much like our ArrayList or String does to handle the required operations.

For example instead of + arithmetic operator we have the methodadd, instead of ”-” we have the method subtract and instead of * we have multiply.

More about arithmetic operators in Java later in this article. To see example of how BigDecimal is used to store decimal number data see below:

1

2

3

4

BigDecimal price=newBigDecimal("4.35");//Note how we input the numbers as strings into our BigDecimal object variables

BigDecimal quantity=newBigDecimal("100");

BigDecimal total=price.multiply(quantity);//Example of multiplication of price with quantity

System.out.println(total);//This will print 435.00 perfectly - no round-off errors and as you could see the BigDecimal object variables could be outputted directly

Above example is yet another really useful piece of information paraphrased from the good book of Cay Horstmann Big Java Late Objects.

A few other things that can be worth knowing about BigDecimal class is that you can define BigDecimal numbers with integers as well, not only string values, or doubles, or longs and it can handle it. It has built in methods that can be useful to know about as follows:

bigDecNmbr1.add(bigDecNmbr2) | Returns the value result of addition with bigDecNmbr1 and bigDecNmbr2 (bigDecNmbr1 + bigDecNmbr2).

bigDecNmbr1.divide(bigDecNmbr2) | Returns the value result of division of bigDecNmbr1 with bigDecNmbr2 (bigDecNmbr1 / bigDecNmbr2).

This class has the options to either set the rounding settings to round to a ”precision” as its called- meaning rounding off the BigDecimal to a fixed amount of decimals defined with an integer, or setting the rounding settings to a so called predefined ”rounding mode”. Example of these rounding modes could be ”HALF_UP” (constants that already exist in the Java language) – which round towards the nearest neighbor unless both neighbors are equally distant in which case it rounds the number up.

Incrementation and decrementation of numbers

Incrementing number values means that you increase them progressively one step at the time (+1/++). In java this is done by assigning a number variable the operator: ++. Like so:

1

2

3

4

5

6

intnumberToIncrement=5;

numberToIncrement++;//incrementing numberToIncrement (+1) one time.

System.out.println(numberToIncrement);// would print out the integer 6

//An alternative way of typing incrementation is via the concatenation method shown above for strings:

numberToIncrement+=1;//this will +1 to the original number - see what we did there? :P

This can be very useful to know because it can be used in Loops to keep track of how many iterations you have looped through, or at what index in an array you currently are when looping through that, or even to keep track of how many times a specific action via method has been executed, etc.

Decrementing a number means the opposite obviously – we decrease the number progressively by one step at the time (-1/–).

1

2

3

intnumberToDecrement=5;

numberToDecrement--;//decrementing numberToDecrement (-1) one time.

System.out.println(numberToDecrement);// will print out the integer 4

Type conversion in Java

Sometimes the different data types for numbers ”clash” and give error messages because they are incompatible with one another.

When this happens you need to do something called ”type conversion” which basically means you convert one of the number variables, to become the data type of your other number variable.

An example of this is a conversion of floating point double variable to integer:

Math.random() for randomization of number value – this method returns a double value with a positive sign greater than or equal to 0.0 and less than 1.0

Randomization with the Math class/library method Math.random()

Here I am going to walk you through how you can generate random numbers between two interval values in Java programming with Math.random(). Lets show you how its done:

1

2

3

intlowerLimit=0;

intupperLimit=10;

intrandomNmbr=(int)(Math.random()*(upperLimit-lowerLimit+1))+lowerLimit;// Will generate one random number between lowerLimit and upperLimit

This in turn can then be used to create your very own Dice games and other cool stuff 🙂

Working with the Date class for Date and Time and Formatting dates with SimpleDateFormat in Java

Another very useful feature worth having some knowledge of is how to work with dates and time in Java.

This can be very useful to store specific dates and time-formats for various programs and applications.

Alright so what do we need to work with Dates and Times in Java then? Well we first need to import the library that is the Date class, this is done by the following statement:

1

import java.util.Date;//place at the top of your own class file

Second what we need to do is create a Date class object:

1

Date date=newDate();//now the date variable have access to all the methods in the Date class

And as with most classes/libraries in Java they come with a set of useful methods that we can use, for the Date class some of these are:

after(Date date) | Check if the Date object calling the method is ”after” the input paremeter: date – returns true if it is, false if not

before(Date date) | Checks to see if the Date object calling the method is before the input parameter: date

compareTo(Date date) | A method to compare the value of the Date object calling the method to the input parameter date – if equal returns 0, if earlier than returns negative value (integer) if later than returns positive integer value

equals(Date date) | Checks to see if the Date object calling the method is equal to the date input parameter, if not returns false

getTime() | Returns time in milliseconds that has passed since January 1st, 1970

toString() | Converts the Date object calling the method into a string value and returns the result

As you can see there are a few methods that can be useful to know about. But how do we get the current date and time then? Well, creating new Date() actually gives us this, all we have to do to print it to a string would be to use toString() method for example.

Alright we got a created date then. But what if we want to present our date and time in a specific way? Java developers thought of this too by creating something called: ”SimpleDateFormat class” that can be used to format our dates into specific formats. Here is how it works: You create an object of type SimpleDateFormat that can access its methods, you specify the formatting pattern you wish to use, and you then format the created date using this formatting-pattern. Simple as that. See example of how it can be done below:

1

2

3

Date dateNow=newDate();

SimpleDateFormat sdf=newSimpleDateFormat("pattern goes here");

StringformattedDateString="Current Date: "+sdf.format(dateNow);//this will format the date using the specified formatting pattern

Ok seems simple enough right? What about the actual patterns used for formatting our dates then? How do we write those? Lets look at that now, below you will be able to find a list of some of the most commonly used formatting options structured as a table which you can browse through and study to get a better understanding of how to create your very own formatting pattern(!). After that we will show you example of how this is created with a practical code example and you will also get a link to an external resource for further information 🙂 Lets get started, shall we?

The table will be inspired from the external reference page that you can find a link to at the end of this section.

Pattern character

Description

Example

y

Year in four digits

2005

M

Month in year

February/02

d

Day in month

12

H

Hour in day (0-23)

12

m

Minute in hour

30

s

Second in minute

50

E

Day of the week

Wednesday

w

Week in year

40

a

A.M./P.M. marker

PM

k

Hour in day (1-24)

24

K

Hour in A.M,/P.M. (0-11)

10

z

Timezone

Greenwich Meantime (GMT)

‘

Escape for text

So that you can have regular text in your formatting pattern (you will see)

Remember that whether its an upper-case letter or a lower-case one IT MAKES A DIFFERENCE!

So with the help of above reference table we will create a formatting pattern of our own, an advice for doing this – plan how you want your date format to look like BEFORE you start experimenting with pattern characters to save time by just picking whatever you need to create your pattern from the pattern character reference table:

Dates and time and how to format these things when working with Java can be very useful for many applications.

Conditional if and switch statements + conditional and relational operators in Java

Alright so we finally have reached the point where we can feel good about what we know about variables and the fundamental basics of the syntax in java. Although we could use some more knowledge as to how you can determine whether some action should be taken in the code, or not. This is usually done with so called ”conditional statements” such as if and switch. And together with the conditional statements we also have conditional and relational operators in Java that help us create the conditions that say to the program what should be done when and what actions should be taken.

IF-statement to determine what should happen in the code

Lets start by taking a closer look at if-statements. With these you can think of telling the program something in the lines of: ”If a condition is true or false – depending on which, do different things”.

The real beauty with if-statement is the simplicity of them together with the endless possibilities thanks to conditional and relational operators available in Java (as well as many other programming languages). If you should have more than one ”condition” that you need to do stuff for it is possible to ”nest” if-statements with else-statement or else if-statement to say for example: ”if the number is 5 then do this, else if the number is 10 do this instead else (if number is anything else) do this default action instead”.

Practical example of various if-statements shown below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

//Template code for if-statement

if(condition)

{

//statements go in here and the stuff you want to do if the condition turns out to be true

}elseif(second condition)

{

//if the second statement is true instead, do the statements listed here inbetween the brackets for the second condition

}else

{

//if neither condition or second condition is true, go to this "default" clause to cover all the other options, and do the statements listed in here

}

//For a more practical example using conditional and relational operators to help us create different conditions:

intmaxLimit=10;

if(5<maxLimit)

{

//if 5 is less than our set maxLimit then do statements listed here

}elseif(5>maxLimit)

{

//otherwise if 5 is larger than our set maxLimit, do the statements listed in this section

}elseif(5==maxLimit)

{

//if 5 is the same as our set maxLimit - do the statements in this section

}else

{

//if 5 is NOT less than maxLimit, and is NOT greater than maxLimit and is NOT equal to maxLimit, then do the statements listed here (if anything is true but the other given conditions else applies)

}

Short-hand if-statement is very useful for inline-conditional statements

There is a way to create inline if-statements in Java as well – this can be really helpful to give specific values to a String immidiately when working with it instead of creating clumsy blocks of if-statement code when what you only need is different value whether a condition is true or Not.

The short-hand if-statement is available in many other programming languages as well and not specifically limited to Java. Practical example of its code is shown below:

1

2

3

4

//Using short-hand if-statement for inline if condition inside a String

intsmallNmbr=3;

intbigNmbr=5;

StringaString="this text will have color: "+(smallNmbr>bigNmbr?"blue":"green");

Lets disect the above inline if conditional statement: first we encapsulated the inline short-hand if statement in parentheses to make it ”clearer” of what belongs together.

Then you can see the condition to the far left: smallNmbr > bigNmbr – if this statement turns out true, then the first value is to be used: "blue". But if smallNmbr > bigNmbr turns out to be false (which in this case it would be) – then the second value is to be used: "green". So depending on the values you give to the variables smallNmbr and bigNmbr respectively, different color names will be concatenated into the aString variable at the end.

The questionmark (?) marks the ending of the condition and moves on to: true-value to be returned : false-value to be returned.

The switch statement and when you use it in Java

The switch statement could be said to be an alternative to if-statements, this is because they share similarities. Such as if one condition (called case in a switch-statement) is true, then execute the specified actions and statements.

The beauty of a switch statement is that you ”switch out” one specific value or variable and then the cases can check if this variable is multiple different values and act on if it is a bit more effectively and with less code than what a regular if-statement can do. Check out example code below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

StringmonthString="October";

intmonthNmbr;//declared but not initalized

switch(monthString)// switch out our monthstring to check against listed cases

{

case"January":monthNmbr=1;//if our monthString that we switch out matches the String "January" then the integer monthNmbr is set to the integer value of 1

break;//we use break to tell the program "this case is over here, continue to next"

case"February":monthNmbr=2;

break;

case"March":

monthNmbr=3;// note that the statements to be executed if our case matches the switched out variable doesn't have to be only 1 row

System.out.println("showing that a case can contain multiple row code as well");

break;//as long as you break when your done with your case, it doesn't matter how many rows it takes up

case"April":monthNmbr=4;

break;

case"May":monthNmbr=5;

break;

case"June":monthNmbr=6;

break;

case"July":monthNmbr=7;

break;

case"August":monthNmbr=8;

break;

case"September":monthNmbr=9;

break;

case"October":monthNmbr=10;// this is where our switched out variable will match and thus giving our integer monthNmbr the value of 10!

break;

case"November":monthNmbr=11;

break;

case"December":monthNmbr=12;

break;

default:monthNmbr=-1;//the default case is used if no other case condition matched against your switched out variable so when monthNmbr = -1 we know that no case matched our switched out variable

break;

}

In contrast to how we used the switch-statement above with a simple String value to match against our switched out String variable you can also do like in regular if-statements when you have actual conditions with relational and conditional operators for example:

1

2

3

4

5

6

7

8

9

10

switch(aVariable)

{

casefirstNmbr>secondNmbr:

//do this

break;

casefirstNmbr<=secondNmbr:

//do this

break;

}

So now you might see how the if-statement differs from the switch statement, and also might get some ideas when it could be best to use the one over the other! 🙂

Conditional operators (&& and || ) and what they are used for in Java

There is something called ”conditional operators” in Java which can be used to help create more complex and elaborate conditions to use in if-statements as well as switch-statements.

Here is a list of the two that exist:

&& – stands for AND and can be used to say for example: if firstCondition AND secondCondition is true (which means both MUST be true! to make condition true)

|| – stands for OR and is used when: firstCondition OR secondCondition is true (not both of them- but one of them – either one of them! to make condition true)

Practical example that demonstrates both of these can be seen below:

1

2

3

4

5

6

7

8

9

if(firstNmbr<secondNmbr&&firstNmbr==thirdNmbr)//if both these conditional statements turn out to be true, continue to the actions below

{

//actions to be taken

}

if(firstNmbr<secondNmbr||secondNmbr>=thirdNmbr)// if any of those two statements turn out true, continue to doing the actions

{

//actions to be taken if condition was true

}

Relational operators and what they can be used for in Java

Lets start with listing them all:

==

equal to

!=

NOT equal to

>

greater than

>=

greater than, or equal to

<

less than

<=

less than, or equal to

And as you probably can see its pretty simple understanding what each one does and how it can be used. And the example of if-statement even shows some example of usage of these relational operators.

Negating conditions, values and statements using exclamation mark (!) in front of it in Java

Another useful thing you should know about when programming in Java is that the exclamation mark (!) is used to ”negate” a condition, value or statement it is put in-front of. A practical example of this is shown below:

1

2

3

4

5

6

7

if(!true)//if false then continue to actions

{

//actions

}elseif(!firstString.equals(secondString))//if the firstString does NOT equal secondString continue to actions

Alright time to Loop through some list data containers to learn how loops work in Java.

Lets start with the most common Loop: The For loop.

The For-Loop in Java

For-loops are pretty basic in Java – you tell the program more or less: ”for an integer variable of 0, and as long as this variable is less than or equal to a looping-limit, then increment this integer variable every iteration of the loop and stop the looping once the conditional statement for the loop is no longer true!”

This can look like the example below for when iterating through the length of an array (as limit for the for-loop):

1

2

3

4

5

6

int[]array={1,2,3,4,5,6,7,8,9,10};//10 slots

intlimit=array.length;

for(inti=0;i<=limit;i++)

{

System.out.pritnln(array[i]);//prints the value of the array slot of index i which is our integer variable in the loop being icremented on every iteration

}

Above statement will ”iterate”/loop through our array’s every slot and print out the value in the console by using the incremented variable as the index to be typed out for the array for each loop iteration. And since our loop iterations increment this variable, this integer variable will keep on increasing to cover every single value inside of our array because we used the length of the array as our loop limit. This can happen thanks to for-loop stops looping through values when the condition for the for-loop is no longer true!

Enhanced For-loop/foreach-loop and how it works and when to use it in Java

The Enhanced For-loop or the Foreach-loop satisfies the need you sometimes might have to visit or access all values in an array for example.

It does this by instantly offering access to an element instead of having to use incremented index variable to keep track of the different array values. Use foreach-loop when you need access to elements inside of arrays but dont necessarily need the actual index values kept track of to be re-used in the code.

For example:

1

2

3

4

5

6

7

8

//Say we have an array with various number values, we want to add all of those to a total value

int[]nmbrValuesArray={2,5,3,2,6,8,10,15,25,18,16,5};

inttotal=0;

for(intnmbr:nmbrValuesArray)//foreach nmbr integer of nmbrValuesArray

{

total=total+nmbr;//nmbr is the current value of the foreach loop of our nmbrValuesArray

}

The While-loop and how it works and when to use it in Java

While-loops are a great way of repeating steps while a condition is yet to be met, for example if you wish to repeat something until a certain amount has been reached, while loop can do this with ease for you. See example below:

1

2

3

4

5

intnmbr=5;

while(nmbr<10)

{

nmbr++;//will increment nmbr integer variable until it is no longer less than the value of 10

}

Since we are using nmbr as the variable the condition is based upon we will have a nice working iteration here thanks to us incrementing this variable inside of the while-loop, but one thing you should be aware of is that if you should ”forget” to increment say the variable nmbr, then this loop would go on forever. Just a friendly reminder 😉 Because it would never reach its ”end-condition”.

Methods and arguments (parameters) and what it is and why/when to create/use them in Java

With methods in Java you can collect a serious of statements and actions to be carried out to be re-usablewithout having to repeat your code every time you need that specific type of functionality. To make methods more ”rich” and dynamic to use, we have the possibility of using something called ”arguments” together with the methods to input data into the methods, data that comes from outside of the method (variable scopes) and need to be used inside of the method for calculations for example, or that is needed to do a certain task.

Depending on the ”type” of method – they can have types like variables to indicate that they can return a value of that specific data type for example, or they can be of ”type”: void which means the method only will execute action/update a variable and Not return any data. Compared to other types of methods say for example a method of type: integer which will return a value of type integer.

Methods will encapsulate functionality to be re-used at multiple places in a program without having to re-type this functionality. If we take a quick look at our Math class/library, we had a lot of different methods we could use, for example: Math.random(). Where random() was a method within the Math class that we can use however many times we want to- and need to in our program. This is what Re-usable means.

In the case of the method Random(), it have encapsulated the functionality to return a random value between the double 0.0 and 1.0, which is the re-usable functionality we get access to when calling upon this variable in our programs.

Ok so for the arguments to be used with methods, we have to say what Data Type the argument should have and give it a name to be recognized inside of the method. For example:

1

2

3

4

5

6

7

8

//Create our method for returning an integer number

publicintreturnANumberFunction(intinputNmbr){

returninputNmbr;

}

//Calling this method is done by calling the Classname the method and dot-notation together with the methodname including the in-parameter (argument)

You can call this method both from inside the class as well as from outside since we gave it the keyword public.

A key difference between calling the method from inside the class versus calling it from outside the class is that when calling it inside of the class you only have to call the method by writing the methodname like so:

1

returnANumberFunction(theNumberToInput);

Whilst calling from outside the class requires you to type the Classname first as shown in the first example.

A good practice is to use methods every time you have code that will be re-used throughout the code on multiple different locations so you don’t have to retype it.

As you can see the potential for methods together with arguments is virtually endless – you can do so much and manipulate data and programs in so many different ways as well as structure the code for re-usability to save space and time.

There are a lot of smart ways of use this to improve your program – start experimenting! 🙂

Basic user interaction with Input/Output using the Scanner class/library and System.out in Java

User interaction is a key feature of Java programming – this can help enrich code and programs by allowing users of the program to interact with the program by inputting values to do things or change stuff in the program. I love to take Bank programs as examples – and in a Bank program it would be key to have your users be able to create their own accountsfor example, and inserting money into accounts and such – this can then be done with input/output using the Scanner class/library.

Handling input with the Scanner class/library in Java

But to use the Scanner library we first have to create a Scanner object that we can use to manage possible inputs of various kinds, and then we have to gain a better understanding of what available methods exist within the actual Scanner library. So lets first create our Scanner class object as can be seen below:

1

Scanner scan=newScanner(System.in);//we have parameter System.in because the system input is what we are interested in scanning - can be files as well (more about this later)

Now that we have created the Scanner object called scan, we can use this to call upon the methods that will be shown below.

Personally I prefer to google the library like so: ”Scanner class Java” and I usually get redirected to either TutorialsPoint or Oracle Documentation for Java which usually hold all the information we could possibly need to understand the Scanner library better. A list of useful Scanner class methods will be listed below:

next() | Finds and returns the the next complete ”token” from this Scanner as a String

nextLine() | Adavances the Scanner to skin entire lines instead of singular tokens – very useful to work with

nextInt() | Scans the next token as an integer

nextDouble() | Scans the next token as a double

hasNextInt() | Method to verify that the user actually entered an input token of type integer

As you probably can see by now Scanner library is really useful and can be used for many various types of applications, programs and functions. Having users interact with your programs can make the programs so much more dynamic and ”richer” allowing you to code more complex systems that actually work together with the user, instead of assuming everything for the user instead of letting them interact with the program themselves and affecting the data of the program.

Printing output with System.out in Java

This functionality is included for all the classes created in Java which is very good since you don’t have to import special libraries and such which can be really nice for beginners not to have to worry about or get confused by in their learning process. System.out.println is a method I personally frequently use when programming in Java especially for Debugging purposes since it helps me stay informed of what is going on in my code when I run it. And it helps me see how different variables changes with the use of methods and such throughout the entire program.

System.out have different ways out outputting/printing information – either as an entire line including a linebreak (jumps down to next line immidiately after printing its output): System.out.println, as a single word without linebreak: System.out.print or formatting numeric output: System.out.printf.

The third option (printf) we will not cover in this article, maybe in the future.

Debugging Java programs with System.out.println and System.out.print

When debugging its very helpful and common to use System.out.println (prints out text on one line and then skips to the next line) to give a message to the system console to inform the developer what is happening when the code is being executed.

Difference between System.out.println and System.out.print and why you might prefer System.out.println for debugging is because System.out.print does not skip to the next line when it has printed the output data. So if you use System.out.print once first, and then again, the output will be after one another, instead of new separate line.

Drawing Graphics and images and working with colors and fonts in Java

To draw Graphics in Java, one is required to first import the class Graphics to be able to use- and access the appropriate methods and so on.

There are two different type of drawing methods in Java: Draw and Fill. And then there is attribute setting-methods which affect how the drawing will look like – such as setFont or setColor.

The basic possibilities of drawing in 2D with Java includes not only shapes, lines and text- but also the possibility of drawing images.

A key fact to know about and remember when drawing 2D Graphics in Java is that every element that will be drawn will be positioned on a ”canvas” using X and Y coordinates.

To get started we will first import our Graphics class:

1

import java.awt.Graphics;

Next we will provide you with a list of the various most common methods to draw and paint using 2D Graphics in Java.

clearRect(int x, int y, int width, int height) | Clear the rectangle by filling it with the background color of the current drawing surface – can be very useful in Game Design for example

setFont(Font font) | Sets a Font to be used for drawing Strings with help from the Font class library

As you could read in several of the above listed Graphic methods descriptions, something called ”Graphics context” is often refered to. When creating a Graphic object to work from, the ”canvas” is refered to and called: Graphics context. So you can set a color to be used within the Graphics context (the canvas) for all the graphic elements that you create afterhaving set a specified color for example.

Practical example of how some Graphical shapes can be created in Java follows:

1

2

3

4

5

6

7

Graphicsg;

g.setColor(Color.BLACK);

g.drawLine(50,80,100,150)//draw a line from X:50 -> X:100 and from Y:80 -> Y:150

g.drawRect(200,200,150,65);//draw a rectangle at (200,200) with width: 150, height: 65

g.setColor(Color.RED);

g.drawString("My string drawn inside my rectangle",200,200);

g.drawOval(400,400,150,50)//draw an oval of width: 150 and height: 50

Another useful thing to know when working with 2D graphics in Java, is that the X and Y axis for positioning of graphical elements on the canvas does not quite work like in regular mathematics. Our X-axis still works exactly the same, However our Y-axis starts in the top-left corner of the canvas and is expanded vertically down, as shown in image below:

How X and Y axis work in Java

Can be good to know this for when positioning your graphical elements on the canvas to know for sure where they will end up 😉

Working with Graphics and the Image class in Java

So if we would like to draw an image in Java, how would this be done?

Well, it turns out that drawing an image in Java I consider to be advanced knowledge and will therefore not cover this area in this section of the article. However, I will provide you with a resource link with which you can learn about it more on your own if you find it interesting and wishes to learn how to work with this in Java.

Working with Graphics and the Color class in Java

Colors are something very useful to know about when working with Graphics, especially if you intend to design Graphical user interfaces for example (not covered in this article of Java basics), or if you just want to experiment and have some fun with the Graphics context canvas in Java and the possibilities it offers.

To use different colors Java has a Color class with which you create different Color objects that will each one represent a specific color.

There are different ways you can use to create colors in Java, the simplest in my own opinion – is to use the predefined Color values that have already been created and is stored as static variables within the Color class.

If you decide to use these static variables in the Color class, all you have to do is use the Color class together with a dot-notation to access the static variables, like so:

1

graphicsContext.setColor(Color.BLUE);

However to use this feature to set colors, perhaps it would be useful to know which static color variables exist, so we provide a list of those below:

Color.BLACK / Color.black

Color.BLUE / Color.blue

Color.CYAN / Color.cyan

Color.DARK_GRAY / Color.darkGray

Color.GRAY / Color.gray

Color.GREEN / Color.green

Color.LIGHT_GRAY /Color.lightGray

Color.MAGENTA / Color.magenta

Color.ORANGE / Color.orange

Color.PINK / Color.pink

Color.RED / Color.red

Color.WHITE / Color.white

Color.YELLOW / Color.yellow

As you can see there are the existing predefined color values you can access as static variables, and they usually are accessible as two different types of writing them as you also can see in the list above.

What about if you want another type of color? Maybe you want to create a color you have experimented to discover with computer tools and have the Hexadecimal code or perhaps the RGB values for this color? There is an option to create colors this way in Java as well. See below how this is done:

1

Color myOwnColor=newColor(255,255,255);

Perhaps that didn’t make much sense to you? It might be because we have given the decimal values for Red, Green, Blue (R,G,B) to create our custom color.

How does RGB work?

RGB Works the following way: you can choose a value between 0-255 (256 values counting the value 0), where 0 means the value ”nothing”, while the value 255 means the value ”full”.

So what do we mean with values nothing and full? Well for the RGB colors we are given something I like to call ”color-pools” of 8-bits each, so our Red color-pool can have a value of 8-bits, and so can our Green color-pool as well as our Blue color-pool.

Together all of these three ”color-pools” create ONE color. This is RGB – combining Red, Green and Blue 8-bit color values to create one color.

Maybe you think 8-bit color values are confusing? Since we are using a Binary number system, 8-bits in this case means 2^8 possible values = 256 – and since we always count the value 0 in programming, we get a value range of 0-255. Simple as that 😉

And most tools available to discover colors on computers offer the possibility of seeing a discovered colors RGB and/or Hexadecimal value. So you just have to copy the RGB values into the create Color method in Java and you have your own custom color specified! Cool huh? 🙂

Working with Graphics and the Font class in Java

Java has two ways of handling fonts, either Physical or logical. The physical way means dealing with specific Character sequence tables and such using a bit more advanced methods, while the Logical way of handling font means using the Five predefined fonts that exist within Java that are guaranteed support throughout any and all environments.

These five ”logical” fonts are:

Serif

SansSerif

Monospaced

Dialog

and DialogInput

So if you are fine with generally specify the ”type” of font you wish to use – say with Serifs, without serifs or monospaced, then this will do fine. If you on the other hand are interested in using specific libraries I recommend you to read up on ”TrueType” and how to handle specific fonts with Java.

For this article we want fonts to be pretty basic – you create a Font object which defines what font-family should be used: ”Serif” or ”SansSerif” for example, what style the font should have Font.ITALIC, Font.ITALIC or Font.PLAIN (normal) and what size the font should have as well (assigned with integer).

A practical example of creating different fonts this way will be shown below:

1

2

3

4

5

6

7

//Creating a both Bold and Italic font and setting it to graphic context and drawing with it

Font boldANDItalicFont=newFont("Serif",Font.BOLD+Font.ITALIC,36);

graphicsContext.setFont(boldANDItalicFont);

graphicsConteoxt.drawString("bold + italic font test",50,120);

//Creating a bit simpler Sans-serif font

Font sansSerifFont=newFont("SansSerif",Font.PLAIN,14);

Further possibilities with Java but things Not covered in this article

Further areas to explore include: File handling in Java – writing to and reading files, using databases to store information even after program has been shut down (offline storage), creating Graphical User Interfaces (GUI’s) to make program more user friendly

There are many areas which we haven’t covered in this article for example the handling of Files for reading and printout output to, as well as using databases to store data even when a program is shut down for example, and create Graphic User interfaces. All of these areas are very exciting and can be read up on with help from Google to find good resources online to learn these areas. But we might also make articles about these areas in the future on this website. Because all of these areas and many more can be very fun to learn and very useful to help create applications.

Android application development with Java programming

Did you know that Java programming also is the language being used to Develop Android Applications? 😉 If this is of interest to you learn the basics of Java programming.

Internet Networking and Web Applications with Java

There are also options to use Java programming to create web applications that can work with internet and the world wide web! 🙂 As well as create Internet browsing software that can access internet.

Useful programming methodology to make you a stronger and more efficient coder in Java and in general (Agile Development (SCRUM), Object oriented programming (OOP), Test-driven Development (TDD) with JUnit)

Many exciting areas to discover, research and study in Java – Test Driven Development (with JUnit for example in Java) for stable programming, Agile Development for learning how some of the most efficient ways of coding works (not only in Java but all programming languages). One Agile methodology is called SCRUM for example. Looking into the concept of Object oriented programming design could also prove very useful to becoming even more advanced.

Extend your current Java knowledge by exploring new re-usable classes with useful methods and functionality

You could also explore classes that exist within Java to extend your capabilities and your skillset of what you can do with Java programming. There are a lot of them, and after reading this article hopefully you will have enough knowledge and insight as to understand how classes work in Java and how you can use different ones 🙂

Searching and sorting algorithms for data and information (stored within arrays for example) in Java

If you feel like storing and sorting/filtering information in Java is interesting you can also check out different ”Searching algorithms” which will show you how to search, filter and manipulate data stored within arrays for example in Java.

Learn to program for Multi-core system environment processors/CPU’s by learning Multithreading Java programming

To learn how to program for the modern computers with Multiple Processing cores you can read about Multithreading programming in Java.

Another piece of information that can be worth knowing of why Java might be an attractive programming language to know – is that Java code is executed in a virtual environment which is compatible with almost any system in the world by now and is very good because this means we don’t have to code differently for different platforms but since the code always gets executed in JavaVirtualMachine (JVM) it will always be the same and always compatible!

Pseudo code – how to type it and what is it?

Pseudo code is ”fake”/dummy code typed in a specific way to easily describe what you want a program or specific methods to do.

Pseudo code is something we use to rougly ”sketch” up the layout of our programs when we don’t want to type out the entire code for it and simply just ”code” the fundamentals of what the actual code will do in the program.

Use statements such as this below to describe how a value is set or changed

1

total cost=purchase price *amount of products;

Describe decisions and repetitions

1

2

3

4

5

6

7

8

9

10

Iftotal cost1<total cost2

thendosomething

elseiftotal cost1>total cost2

dosomething different

Whilethe balance of an account ismore than20'000

dosomething

Foreachpicture inthe sequence

dothese things tothe current picture

Use indentation to indicate which statements should be selected or repeated

For example if something needs to be done for multiple things you can write:

1

2

3

4

Foreachcar

operating cost=10*annual fuel cost

total cost=purchase price+operating cost

//above indicates that both indented statements should be executed for each and every car for example

Indicating results with statements like these

1

2

Choose car1.

Report the finalyear value asthe answer.

General rules for pseudo code

The exact wording used in pseudo code is not important. What is important is that pseudo code describes a sequence of steps that are: executable – meaning it is possible to do in practice/reality, ”unambiguous” – which means its clear when it comes to what it means should be done and its terminating – meaning that the steps sooner of later comes to an end.

Yet again I have to give out a big thanks to Cay Horstmann for the book: Big Java Late Objects which yet again has been my reference for how to explain pseudo code to you readers by paraphrasing the books content.

When pseudo code has all of the above mentioned steps – it is called an algorithm.

Algorithms are used to describe how to solve problems of various kinds, in this case- our problem might need a solution that can be accomplished with programming!

Finish

A Big Thanks to all that have been reading this article, I spent almost two complete days typing all of it up, it was a lot of content to cover. But I think I covered most basic and useful things that can be interesting to know about when starting out coding in Java.

Throughout this entire article I have often refered to a book called: Big Java Late Objects, written by: Cay Horstmann – its a really great book that helped me learn Java programming and most of the basics covered in the book I have also tried to cover in this article!

Two other external resources that have been referenced occasionally have been the website and tutoring portal online: Tutorialspoint.com for Java which I personally think had some great references and tutorials on various subjects in Java.

It was a genuine pleasure writing this article and I did it – not only for myself to have two great reference articles to remind me when time passes and I forget some of the details of Java, but also for everone else who are just recently starting to code with Java and kids interested in learning how to program with Java, etc.

Feel free to contact me if you have any questions about the article or see something that I missed and that could be good to fix for all the people who read this article. Contact information can be found under ”Kontakta oss”.

This website is originally intended to be a Swedish nieche web archive when it comes to Programming, Web and Development and useful tools reference lists, etc. But these latest two articles were typed in english because I got requests from people from other countries than sweden with interest in learning Java 🙂 So hopefully it will still be understandable for most, and for those who can’t I will probably write a swedish version of this entire article in the future, but right now I need to rest a little bit from being exhausted of all the typing 😉

And yes, I know this article is unusually long(even for me ;P) but I considered creating many various posts covering all the areas, but a bit more ”structured” and separated, but for now, one big article will have to do- maybe in the future if it turns out its to annoying to read an article this large, then I will for sure create many separate mini-version articles containing different sections of this article for better readability etc.

Thats it for me for now, hope you enjoyed it, I know I did 😉 Cya next time 🙂