Contents nav menu

As the title so exhaustingly declare (hehe wanted to get it all in there for search engine optimization ;P) we will cover a lot of programming areas for Java in this article.

Before we begin this article however i’d like to refer to our previous one containing detailed instructions of how to get started with downloading, installing and configuring Eclipse as Development Environment for Java.

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:



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:

public static void Main(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!

Indentation – makes code more easily readable and better structured for humans

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 folder2 inside of folder1, 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:

 * 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
public int ourMethod(int nmbr) {
   int result = 0;
   //method statements
   return result;

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, ColorImage 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:

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:

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, Member variables, various (primitive) Data Types (Integers, Doubles, Boolean, Float, Strings, Arrays and Arraylists), Round-off errors, Variable Scopes, “Reserved keywords” for variables and creating Constants in Java

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 short designed 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:

//Creating an integer that holds the value of 5
int numberFive = 5;

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

//Creating a float floating-point number variable holding value of 3.5
float floatVariableMiddleValueBetween3and4 = 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
boolean bool = true;

//Creating a String variable with textstring value using double quotes ("")
String text = "this is a text";

//Creating a string variable with textstring value using single quotes ('')
String text2 = '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:

//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 = new int[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:

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

Creating an array with integer values ranging from 1-10 (10 slots for 10 values).

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:

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.

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.

If however you still have a thirst for learning more about arrays on your own, feel free to check out Oracles own reference page for arrays:

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:

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:

//1st way: Just create the list, no values, no specified length.
ArrayList<String> stringArrList = new ArrayList();

//2nd way: Create the list with specific amount of slots (kind of like our regular arrays!)
ArrayList<String> anotherStringArrList = new ArrayList(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?

For more information about ArrayLists in Java you can visit this reference page at

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:

int numbersVariable;
int numbersVariable = 0;
int firstInteger, 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:

final int CLIENT_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:

private int appleWeight = 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 “”.
    • .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:

String aString = "This is a simple string";
String a2ndString = ": plus another one";
int fiftyFive = 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:

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:

String aString = "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:

String aString = "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.

Useful methods in String class: substring, charAt, contains, equals, length, split, toLowerCase, toUpperCase and trim

substring(int beginIndex, int endIndex) | A method to extract a “substring” of the original string by stating between what beginIndex and what endIndex to extract

Practical use example:

String aString = "one little piggy";
aString = aString.substring(4, aString.length()); //aString.length() gives length in characters of string to keep entire string after trimming the beginning
//result would be stored in aString and overwrite previous value and would be a string as follows: "little piggy" - note that whitespace counts as 1 character one+whitespace = 4

Also note how the String method is called ON a String variable!

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

Practical use example:

String aString = "Lorem Ipsum Dolor Sit amet"; //some dummy-text - See for generator
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:

String aString = "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)

Practical use example:

String aString = "this string";
String a2ndString = "this string";
System.out.println(aString.equals(a2ndString)); //will return and output boolean value true

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:

String aString = "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 “”

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.

String urlString = "";
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.

Arithmetic operations and working with numbers in Java: addition, subtraction, division, remainder, multiplication, round-off errors, BigDecimal class (for proper representation of currency data), incrementation/decrementation, type conversion and the Math class – including generating random numbers!

Basic arithmetic operations: addition, subtraction, division, remainder, multiplication

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:

int firstNmbr = 5;
int secondNmbr = 10;
int thirdNmbr = 3;
int result;

//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:
//5*3 = 15 - 10 = 5 + 3/3 = 5+1 = 6 - Remember that when writing mathematical expressions in Java parentheses gives priority and separates.

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.

BigDecimal numbers for accurate variable storage- and representation of currency values

If you want to do calculations with larger numbers, or get an accurate representation of currencies in Java you can use the BigDecimal class from the java.math package. A reference page for BigDecimal is found here:

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 method add, 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:

BigDecimal price = new BigDecimal("4.35"); //Note how we input the numbers as strings into our BigDecimal object variables
BigDecimal quantity = new BigDecimal("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).
  • bigDecNmbr1.equals(bigDecNmbr2) | This method compares bigDecNmbr1 with bigDecNmbr2 checking for equality (useful for conditional statements)
  • bigDecNmbr1.round(MathContext mc) | This method rounds bigDecNmbr1 according to the settings of the class object MathContext mc.
  • bigDecNmbr1.subtract(bigDecNmbr2) | Returns the value result of subtraction between bigDecNmbr1 and bigDecNmbr2 (bigDecNmbr1 – bigDecNmbr2)
  • bigDecNmbr1.toString() | Converts the bigDecNmbr1 BigDecimal value to a string – could be useful for concatenation.

There you have a few popular ones.

Since mentioning briefly something called “MathContext” class I figured its just as well to cover this shortly here as well. Here is a reference page if you wish to read more about it on your own as well:

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.

A reference for these rounding modes if interested can be found here:

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:

int numberToIncrement = 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/–).

int numberToDecrement = 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:

double fpNmbrVariable = 100.0;
int salory = (int) fpNmbrVariable; //will turn our initial 100 value double variable, into a 100 value integer

This is also sometimes called “typecasting”.

Math class and powerful useful methods that comes with it

The Java Math class/library comes with a lot of useful functions to use for mathematical calculations of various types.

For example some useful methods included are as follows:

  • Trigonometrical functions like for example: atan, asin, acos, cos, tan, sin
  • Rounding functions like: ceil, floor and round
  • Max/Min value functions that are compatible with a lot of the different number data types in Java – takes two values and returns the greater or smaller one depending on whether max or min
  • Raise number by a power for example 2*2*2 = Math.pow(double firstValueOf2InThisCase, double valueOf3InThisCase);
  • Math.sqrt(double nmbr) – gets Square root of the specified nmbr double variable
  • 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:

int lowerLimit = 0;
int upperLimit = 10;
int randomNmbr = (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:

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:

Date date = new Date(); //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:

Date dateNow = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("pattern goes here");
String formattedDateString = "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:

SimpleDateFormat sdf = new SimpleDateFormat("E, dd/MM-yyyy, HH:mm:ss (z) 'week:' w"); // this will give us a dateformat such as: Wednesday, 27/09-2016, 12:58:33 (GMT) week: 39

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:

//Template code for if-statement
   //statements go in here and the stuff you want to do if the condition turns out to be true
}else if(second condition)
   //if the second statement is true instead, do the statements listed here inbetween the brackets for the second condition
   //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:
int maxLimit = 10;
if(5 < maxLimit)
   //if 5 is less than our set maxLimit then do statements listed here
}else if(5 > maxLimit)
   //otherwise if 5 is larger than our set maxLimit, do the statements listed in this section
}else if(5 == maxLimit)
   //if 5 is the same as our set maxLimit - do the statements in this section
   //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:

//Using short-hand if-statement for inline if condition inside a String
int smallNmbr = 3;
int bigNmbr = 5;
String aString = "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:

String monthString = "October";
int monthNmbr; //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;

   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;

   case "May": monthNmbr = 5;

   case "June": monthNmbr = 6;

   case "July": monthNmbr = 7;

   case "August": monthNmbr = 8;

   case "September": monthNmbr = 9;

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

   case "November": monthNmbr = 11;

   case "December": monthNmbr = 12;

   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

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:

   case firstNmbr > secondNmbr:
   //do this
   case firstNmbr <= secondNmbr:
   //do this

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:

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:

if(!true) //if false then continue to actions
}else if(!firstString.equals(secondString)) //if the firstString does NOT equal secondString continue to actions

Loops (for-loop, enhanced for-loop/foreach-loop, while-loop) to iterate through things (for example arrays) in Java

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):

int[] array = {1,2,3,4,5,6,7,8,9,10}; //10 slots
int limit = array.length;
for(int i = 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:

//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};
int total = 0;

for(int nmbr : 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:

int nmbr = 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-usable without 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:

//Create our method for returning an integer number
public int returnANumberFunction(int inputNmbr) {
   return inputNmbr;

//Calling this method is done by calling the Classname the method and dot-notation together with the methodname including the in-parameter (argument)
int theNumberToInput = 5;
ClassnameForMethod.returnANumberFunction(theNumberToInput); //will return 5

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:


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:

Scanner scan = new Scanner(; //we have parameter 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
  • hasNextDouble() | Method similiar to above hasNextInt() but verifies that user inputted token of type double instead
  • hasNext() | Checks if user inputted another token

A practical usage example:

if(scan.hasNextInt()) //check if user input some integer to the system
   int nmbrVariable = scan.nextInt();
   System.out.println("The inputted integer variable was of value: " + nmbrVariable);

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:

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
  • Draw methods:
    • drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) | Used to draw images
    • drawLine(int x1, int y1, int x2, int y2) | Draws a line using the current color from (x1, y1) to (x2, y2) coordinates
    • drawRect(int x, int y, int width, int height) | Draws the outlines of a specified rectangle
    • drawString(String str, int x, int y) | Draws a String on the canvas
    • drawOval(int x, int y, int width, int height) | Draws an ovan with specified width and height on the canvas
  • Fill methods:
    • fillOval(int x, int y, int width, int height) | Draws an ovanl shape and fills it with the currently set color
    • fillRect(int x, int y, int width, int height) | Draws a rectangle and fills it with currently set color
  • getColor() | Gets the Graphic contexts current color
  • getFont() | Gets the current Font
  • setColor(Color c) | Sets this Graphics context current color to specified color
  • 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 after having set a specified color for example.

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

Graphics g;
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.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

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 😉

A resource and reference page to get further information about this area can be found at the Graphics class documentation:

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:


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.BLUE /
  • Color.CYAN / Color.cyan
  • Color.DARK_GRAY / Color.darkGray
  • Color.GRAY / Color.gray
  • Color.GREEN /
  • Color.LIGHT_GRAY /Color.lightGray
  • Color.MAGENTA / Color.magenta
  • Color.ORANGE /
  • Color.PINK /
  • 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:

Color myOwnColor = new Color(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:

//Creating a both Bold and Italic font and setting it to graphic context and drawing with it
Font boldANDItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 36);
graphicsConteoxt.drawString("bold + italic font test", 50, 120);

//Creating a bit simpler Sans-serif font
Font sansSerifFont = new Font("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.

Java as an attractive programming language thanks to its JVM – Java Virtual Machine Environment for Compatible code worldwide!

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

total cost = purchase price * amount of products;

Describe decisions and repetitions

If total cost 1 < total cost 2
then do something
else if total cost 1 > total cost 2
do something different

While the balance of an account is more than 20'000
do something

For each picture in the sequence
do these things to the 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:

For each car
   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

Choose car 1.
Report the final year value as the 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!


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!

A couple of other useful reference for all of you just getting started is my previous article explaining how to download necessary things to start coding in Java as well as instructions of how to download, install and configure Eclipse as your Integrated Development Environment (IDE) for Java.

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

Last but not least- the official documentation site of Oracle – the creators of Java, which seem to have one link for tutorials in Java and one link for pure documentation of Java code.

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 🙂

Hello all!

In this post we will go through how to install and configure/setup one of the most popular Java Integrated Development Environments (IDE) for beginners: Eclipse.

Now to be able to start developing java you first have to download something called Java Development Kit (JDK).

This will therefore be the first section we walkthrough and discuss and we will do so for Windows users primarily in this post, perhaps in the future additions will be made to cover instructions for Mac and Linux users as well, but for now Windows will have to do due to lack of time as well as experience of those operating systems (apologies for this in advance).

Another thing required to work with Java code in Eclipse is a “workspace” directory, this is the directory that you designate to hold all the work you will be producing when coding and saving that code. On startup of Eclipse you will get prompted to select this folder as I will demonstrate with an printscreen image later in this post.

We will also cover how the user interface of Eclipse is setup and what each different section includes and does, as well as how to create your very first java program in Eclipse!

Another post will be published short after this one which will be about our very first official Java program in Eclipse which will be a “testprogram” to demonstrate the basics of Java programming such as:

  • Syntax (including indentation what it is and how its used and why)
  • Data types
  • conditional statements
  • various types of loops for interation of code
  • basic variables to store information
  • more advanced ways of storing information (arrays and arraylists)
  • methods, in and out- parameters
  • variable scope
  • documentation of code and-
  • basic interaction with user such as input/output

Download, installation, configuration of JDK (and JRE) for Windows

JDK includes something called JRE (Java Runtime Environment) which is needed to run Java programs, plus development tools (such as compiler and debugger).

– The compiler is a computer program which translates our programming language – in this case Java which is considered a “high-level langauge” which means that it is very abstracted and simplified to ease the coding for humans compared to how machine language which the computers processor actually handles looks like (1’s and 0’s). Lower level coding languages are “closer” to how machine language actually looks like which means less abstraction and simplifications to ease the coding process for humans.

– The debugger is also a computer program with the purpose of testrunning the code you have written to see if its properly coded so its runnable when executed in the CPU (processor) – if your code is not – the debugger will be “trapped” and let the programmer know where in the code this trap occured so that the programmer can rectify the errors and make the code error-free, valid and executable.

Download JDK for Windows

First you need to visit which is the Java SE (standard edition) download site.

Once there, under “Java Platform, Standard Edition” it will say: “Java SE 8u(xx)”, where “xx” is the latest update number, Click the “JDK Download” button.

Then you have to “Accept License Agreement”.

Finally you have to select the operating platform you will be downloading JDK to, whether you are on Windows x64 (64-bit Windows OS), or Windows x86 (32-bit Windows OS).

Select Bittype of your OS - 32 or 64

Select Bittype of your OS (32 or 64)

If you are not sure which Windows OS you have – its easy enough to check by going to the search box in the Start Menu (if you have Windows 7) and typing in the command “dxdiag” and pressing ENTER. This might bring up a prompt that ask if you wish to check if stuff is signed/has certificate – I usually just bypass this by saying that I am Not interested.

Doing so will bring up the following box which is Diagnostic tool for DirectX and has the information you’re looking for:

dxdiag Windows 7 OS 64-bit

dxdiag Windows 7 OS 64-bit


Another method to check whether you have 32-bit or 64-bit OS is by going to Control Panel > System and check System Type. This might actually be easier for some.

Control Panel > System under system type

Control Panel > System under “system type”

Install JDK and JRE on Windows

Once downloaded the JDK its time to install it on Windows. You do this by running the installer called: “jdk-8u(xx)–windows-x64.exe” for example if you have and chose to download JDK for 64-bit OS. This will install both JDK and JRE!

Accept the defaults installation settings if you’re unsure and dont have a need to specify custom installation location for example.

If defaults are selected JDK will be installed in “C:\Program Files\Java\jdk1.8.9_xx” where xx is the latest upgrade number and JRE in “C\Program Files\Java\jre1.8.9_xx”.

Might need to know this in case Eclipse asks for JDK or JRE at any point in time during your setup of Eclipse Integrated Development Environment.

Download, install and configure Eclipse on Windows

Alright, so now that we got JDK and JRE covered we’re all set on the preparations to start programming in Java, now lets get our Integrated Development Environment of choice: Eclipse.

For this you have to start by visiting Eclipses website

From there you select “Download xx-bit” (i think it senses what bit operating system you have – it seems to be intelligent like that) under “Get Eclipse Neon”. And click the “Download button” on the page you get redirected to. File you will be downloading is called: eclipse-inst-win64.exe at the time of this post being written (26 of september 2016).

Once downloaded you run the .exe file and this will start the Eclipse Installer.

Once the installer has started, you will be prompted with the option to select one of various development environments. You will be selecting the top listed one called: “Eclipse IDE for Java Developers”.

Once selecting this one you will be asked to choose installation folder- or agree to their suggested default one, and select whether you wish to get a desktop shortcut (could come in handy) as well as Start Menu entry.

Once these options has been chosen, you press “Install”, Accept the agreements, and the installation will Begin! Once done you will get the option to Launch immidiately, if this for some reason doesn’t work and you selected to get shortcut on desktop – simply start it this way instead. Let’s do it! 🙂

Once Eclipse Neon has started first thing it will ask you to do is select the Workspace.

Setting Workspace directory for Eclipse in Windows

Once prompted for this, it will suggest a path, and also offer the option of a checkbox which says “use this as default and don’t ask me again” – check this option and you don’t have to care about this unless changing workspace directories (which can be done manually anyways). But by checking this option during the time you’re using the same workspace you don’t have to be bothered with annoying popup boxes

Workspace selection in Eclipse, Windows

Workspace selection in Eclipse, Windows

I will choose to keep their suggested designated workspace location, but if perhaps you have to little space on that suggested location, you can change it to better fit your system setup.

First startup of Eclipse Integrated Development Environment (IDE) and Welcoming Screen

Once this is done, you will be greeted by a “Welcoming screen” with various options for how to get started with eclipse, in the bottom left corner there is an option however that you can de-select if you do not wish to have this welcome screen greet you every single time you start up Eclipse.

Eclipse Neon Welcoming Screen

Eclipse Neon Welcoming Screen

A few of the options you are presented with as you can see above (apoligies for the icon bug in the image- please try looking beyond it) are as follows:

  • Create a Hello world application : which is a standard program for most programming languages demonstrating how to code in its most basic sense by testing the creation of a string and the printout of said string.
  • Create a new Java project : Is basically what we will be doing when working with Java on a “more real level”.
  • Checkout projects from Git : This is an option to include projects you have managed with the version management tool Git (a bit advanced for beginner).
  • Import existing projects : Will allow you to import already created projects into this freshly installed Eclipse Dev environment.

In the right-hand side of the Welcoming screen you will also be able to get “Overview of features”, go through some “Tutorials”, check out “Sample codes”.

In the “Overview of features” you can learn about basic eclipse workbench concepts (probably very useful if you intend to code a lot in Eclipse – then could be a good thing to get familiarized with the workspace layout and environment). You can also learn about: Git with Eclipse, browse eclipse extensions in the “Eclipse marketplace” and learn eclipse program development (all the basics one could possibly need to get started).

Workbench Layout

Eclipse Workbench layout.

Eclipse Workbench layout.

Eclipse Package Explorer

Moving on from the welcoming screen and on to the “workbench layout” (accessible in top-right corner of the welcoming screen by the way), you will see the “Package Explorer” to the left side which is where all your projects, code folders and codefiles will be hierarchically presented and accessible to work with.

Eclipse Coding area

The white area in the center is where you type in your code once a file has been created for this. In the bottom of the centered whitespace area you can see tabs called “Problems, Javadoc, Declaration”. Problems will list any and all errors that might occur when you try to run incomplete or invalid program code. This will be the most useful tab of the three by far (at least in my own experience with Java development in Eclipse).

Eclipse Workbench menubar

Above both the Package Explorer as well as the whitespace coding area there is a sort of menubar with options – there is a “bug” option for debugger (green color), a play button (also green) next to it used to actually run the code you write in various ways and configurations, there also is a button for creating new code files, projects etc. to the far left on this menubar.

– Java classes and packages

Options to create “classes” and “packages” also exist in this menubar. Classes are basically the code files you are working with when programming in Java and packages are a way to organize those code files and cluster related code files together (especially useful if you code bigger programs that require a lot of different code files to work as one program – packages bind all the different code files together to the one program).

– Eclipse perspectives

To the far right there also is an “open perspective” shortcut button which will allow you to switch between available so called “perspectives” such as coding workbench, debugging perspective, etc.

Eclipse Program menubar

One more level above the first menubar you have the Eclipse official menubar with tabs such as: File, Edit, Navigate, Search, Project, Run, Window and Help.

File option will allow you to create new files, or open already existing ones, save projects and files, as well as switch workspace and import/export projects and last but not least – access and set the properties of Eclipse.

The Edit option offers the basic editorial options such as Ctrl + Z (undo), copy (Ctrl + C), cut (Ctrl + X), paste (Ctrl + V), delete (DELETE-Key) as well as find/replace (Ctrl + F).

The Navigate option I haven’t personally used that much but seem to include options to handle logs and something they call “tasks” which I have yet to learn.

The Run option I’ve used quite a lot in contrast though, since it can be used for both running your code as different confugrations as well as debug your written code.

The Window option is quite useful as well since it offers Window and layout preferences as well as View-switching capabilities which in Eclipse basically is the power to switch between coding, debugging (which can be focused in separate views called “perspectives”) or simply show views which you are currently not able to see in the workbench layout.

The Help option offers options such as access to the Welcome screen once closed, access to Help manuals for Eclipse with tons of information, possibility of checking for updates, finding out installation details and general information about eclipse as well as access Eclipse marketplace to download plugins and extensions for Eclipse to extend its basic functionality.

Workbench flexibility and rearrangement

The Eclipse workbench is also very flexible and will allow you to move stuff around, enlarge, minimize different sections in the workbench as well as remove and add only the parts you personally want to have part of your workbench!

If you move your mouse towards the borders of each different section in the workbench are you will see what I mean when your mouse icon will switch to a “move icon” instead of cursor icon, etc.

For example the starting workbench layout has both taskbar as well as an area to the right called “outline” and since I don’t recall what these are used for or even that I ever have needed those when coding myself, I can choose to remove these alltogether, giving me more room to the Java coding area, and if I ever were to discover that these areas in fact were necessary for something, I have the Window tab in the Eclipse menubar to help me get these sections back to the interface!

Creating a new Project in Eclipse

Creating new Java project in Eclipse

Creating new Java project in Eclipse

You go to File > New and select Java Project and will then be prompted to type in the name of your new Java project.

Prompted to type in name of Java project

Prompted to type in name of Java project

Then you click Next which will be enabled after having typed in the name, and then Finish and Eclipse will create the necessary folders and paths for your new Project so you simply can start working right away!

Once you press Finish your project will show up in Eclipse Package Explorer, you will have the option to expand this folder by pressing the tiny arrow to the left of the folder. Doing so will reveal an internal folder called “src” as well as a “Library” called “JRE System Library” which you basically can ignore, its just there to let you run the code you write.

At this stage the “src” folder is empty but we need a Class file to be able to start our coding. So right-click the “src” folder and goto New > Class.

Creating new class to work with in your newly created Java project

Creating new class to work with in your newly created Java project

After having done so, you will get a popup box prompting for the Class name of the Class you wish to create – this should be a name given according to the Naming Conventions of Java programming for classes (which is that first letter of the name should be capital letter for example: ClassName, if more than 1 word use CamelCase which basically means every words first letter gets capitalized).

Class name and class creation

Class name and class creation

And as you can see above an option is offered to create a “method stub” called: public static void main(String[] args) which basically is the so called “Main method” of Java programming which allows programs to be run in general.

Once you press finish you will be presented with something looking like this:

class created and put on workbench

class created and put on workbench

As you can see in the Eclipse Package Explorer to the left, both the package “testproject” was created (if you look at previous image you will see a field allowing you to name the package created for the class under “source folder” at the top of the prompt window for creating a class) as well as the classfile (.java).

Anyhow, a package was created to house our class files, and a .java file was created to hold our java programming code which in turn will be part of our program.

And in the Eclipse Coding area you will now see that the Java file that was just created has been automatically opened to work with and it contains some basic contents that a class needs.

More about the actual contents of the file created will come in next post about how to code in Java.

But basically thats it, we’re done now and you can start coding!

Once you have typed the code you wish to have you can press either Run in Eclipse menubar or the green Play-button to run the code you have just written.

For quick introduction purposes lets create the simplest version of a program: Hello world! program real quick:

Where it now says: // TODO Auto-generated method stub you can replace this with the following code:

System.out.println("Hello World!");

And then run the program like so:

Running the simplest program in Java Hello World!

Running the simplest program in Java Hello World!

Once you press OK you will see this:

Hello World program running

Hello World program running

Hotkeys in Eclipse useful to know to code effeciently

In Eclipse there are a very useful hotkey to know which is: CTRL + 1 by default which offers you so called “quick fixes” to correct simpler errors that may be caused by the lack of import of a specific class you want to use in your code or such.

Another useful hotkey to know about is “Auto-formatting of code” which is: CTRL + SHIFT + F, which is used for example when you have coded sloppy or forgot to indent the code or do indentation wrongly on some places – this hotkey will help you correct the indentation in these cases!

Another hotkey that works for almost ANY program no matter where you are is the hotkey to “Search” the code:



Enjoy and hope that you got a nice introduction to Java Integrated Development Environment (IDE) Eclipse and how to work with it 🙂

I know I did 😉

I recently just finished another article which in comprehensive and much detail cover all the areas that can be useful to know about when starting programming in Java. Until next time!

I nedan innehållsförteckning kan ni se vad jag tänker gå igenom och ta upp i detta inlägg.

  1. Introduktion – Vad är Responsiv Webbdesign?
  2. Tillvägagångssätt – Mobile-First vs. Mobile-Last
  3. Tekniker och kodningsmetoder – “Enhetsspecifikt” vs. ”Breaking-points” (för & nackdelar)
    1. Breaking-points kodningsmetoden
      1. Att tänka på
      2. Nackdelar?
      3. Fördelar jämfört med Enhetsspecifika kodningsmetoden
      4. Hur kodningsmässigt?
    2. Enhetsspecifika kodningsmetoden
      1. Nackdelar?
      2. Fördelar?
      3. Hur kodningsmässigt?
    3. Verklighetsbaserat exempel
  4. Responsiv webbdesign’s utvecklings- och testmiljö i Firebug & Google Developer Tools
    1. Cloudbased Browser & Device- compatibility testing online
  5. CSS Media Queries & Responsiv webbdesigns-specifik kod
    1. Nödvändig Meta-kod för Responsiv Webbdesign
    2. CSS Media Query basics (grunder)
    3. Adaptiva och anpassningsbara måttenheter för responsiv typografi m.m.
    4. Manipulation av HTML dynamik via CSS (t ex. display: hidden vs. none)
    5. Adaptiva och responsiva bilder – på två sätt (utan JavaScript)
    6. Touch-baserade features för responsiva webbsidor
      1. Brist på indikations effekter jämfört med datorer (t ex. hover-effekt för länkar)
      2. Fingrar istället för datormöss och precisionsverktyg för klickande och val
      3. Handpositionering för smartphones och surfplattor
  6. Exempel Responsiv Webbdesigns kod- och Effekt i praktiken

Introduktion – Vad är Responsiv Webbdesign?

Responsiv webbdesign är ett populärt koncept för hur man kan bygga webbsidor idag. Detta då Responsiv webbdesign går ut på att anpassa en webbsida utefter vilka enheter som folk kan tänkas använda för att besöka webbsidan via. Om det så är Dator, Surfplatta eller Smartphone.

Med hjälp av Responsiv Webbdesign får man som utvecklare kontroll för att kunna anpassa en webbsida inför samtliga visningsscenarion som kan existera.

Tillvägagångssätt – Mobile-First vs. Mobile-Last

Inom Responsiv webbdesign finns där två olika “kända” sätt för hur man kan gå tillväga för att bygga sina webbsidor som jag stött på.

Det ena är med den s.k. ”Mobile-First-approachen”, vilken brukar anses vara den bästa då detta tillvägagångssätt är ämnat för att inte bara optimera utseendet för webbsidor- utan även optimera dess laddningstid och prestanda.

Mobile-First möjliggör detta genom att man börjar med att designa hur webbsidan ska se ut för mobila enheter i t ex. porträttläge (för minsta viewport-bredden).

På detta vis får bara det allra väsentligaste plats på webbsidan, och allt annat som egentligen är ”överflödigt” för att förmedla webbsidans verkliga syfte hoppas över för att bespara kod, layout och flashiga funktioner, vilket då kan leda till optimerad laddningstid- vilket är desto bättre för mobila enheter då dessa kanske har sämre bandbredd jämfört med vad en dator med bredband hade haft. Och därefter är det sen då tänkt att webbsidan ”växer” efterhand som högre upplösningar besöker sidan.

Medan ”Mobile-Last-appraochen” gör motsatsen: då man börjar med att designa sidan för hur den hade sett ut i största möjliga ”viewport bredden” som man siktar in sig på att visa sidan för. Och därefter sen skalar ned sidan allteftersom ”viewport bredden” minskar- och anpassar layouten för de nya upplösningarna.

Mobile-Last kan därför även medföra sämre laddningshastigheter då det kan vara svårare att ”göra av med” saker från de större layouterna när man börjar närma sig de mindre- jämfört med att redan i början för Mobile-First haft begränsat sitt urval av sådana prestanda krävande delar då det första man designar för är just Mobila enheterna med sämre bandbredd.

Så Mobile-First vs. Mobile-Last är i grund och botten tankesätt som man utgår- och planerar från när man väljer att bygga sin Responsiva webbsida.

Mobile-Last kan även kännas lite ”enklare” i vissa fall när man är nybörjare och först börjar med Responsiv webbdesign- då detta är närmast hur man annars brukar bygga ”vanliga” webbsidor och designa deras layouter.

I denna guiden kommer jag demonstrera Mobile-Last-approach då detta är sättet jag själv personligen är mest bekväm med och skapat några responsiva sidor via tidigare. Men prova gärna på att Googla tips om hur man skapar Responsiva Webbsidor via Mobile-First och försök att lära er detta då det finns många fördelar med denna metod 🙂

Tekniker och kodningsmetoder – “Enhetsspecifikt” vs. “Breaking-points” (för & nackdelar)

När vi ska börja närma oss själva koden för Responsiva webbsidor så finns där olika metoder för hur man kan koda. Två metoder jag själv stött på är ”Enhetsspecifika kodningsmetoden” och ”Breaking-points kodningsmetoden”.

Det finns för- och nackdelar med båda metoderna, men den bästa av de båda enligt mig är Breaking-points kodningsmetoden. Vad är det då jag pratar om kanske ni undrar? Jo, dessa två olika metoder är vad vi kommer följa när det gäller på vilket sätt vi skalar om vår responsiva webbsida.

Breaking-points kodningsmetoden

Att tänka på

När det gäller breaking-points kodningsmetoden (hädanefter kan jag komma att kalla denne för BPK-metoden) så är det bättre om man kan göra den responsiva webbsidan stabil nog att endast behöva stora ändringar i layouten vid ett fåtal tillfällen typ en stor layout-förändring för surfplattor i porträttläge, en stor ändring för surfplattor i landskapsläge, en för smartphones i porträttläge samt landskapsläge. Varför det då? Jo, för att desto färre tillfällen som korrigeringar behöver göras- desto mindre Media Query regler behövs – desto snabbare laddningstid, samt desto “smidigare” kommer webbsidan verka för dina besökare! Detta är dock inte alltid helt lätt att lyckas med, personligen anser jag det lite av en konst att lyckas med detta då jag själv upplevt hur tidskrävande/svårt detta ibland kan verka.


Det är tyvärr väldigt lätt i responsiv webbdesign att utgå från en “inte så bra/genomtänkt” grund för webbsidan (speciellt som nybörjare). Detta kan då i BPK-metoden senare leda till att man blir tvungen att skapa massor med CSS Media Query regler tätt inpå närliggande upplösningar- när man egentligen vill försöka hålla sig till så få regler som möjligt för endast de större ändringstillfällena (surfplatta porträtt, surfplatta landskap, smartphone porträtt, smartphone landskap, etc.). Som nämndes i ovan område “Att tänka på”.

Fördelar jämfört med Enhetsspecifika kodningsmetoden

Med BSK-metoden kommer vi alltid kunna behålla våra CSS Media Query koder oavsett vilka enheter som besöker vår responsiva webbsida då våra ändringar inte var baserade utefter specifika enheter- utan faktiska bristningspunkter i vår utgångslayout.

Hur kodningsmässigt?

För denne guides skull kommer jag bara att gå igenom hur man går tillväga när vi följer BPK-metoden. Denne går ut på att skala ned/upp (beroende på tillvägagångssätt) vår sida och identifiera när sidan ”går sönder”- med vilket jag menar när den börjar se annorlunda ut från hur vi vill att sidan skall visas. Och sedan då korrigera denna bristning så sidan ser bra ut igen för den nya upplösningen!

Så när detta inträffar identifierar vi de specifika måtten för när ”brytningen” skedde, och registrerar dessa i vår CSS Media Query kod som en regel för när ändringar i webbsidans layout skall ske- och inuti denna regel specificerar vi exakt vilka typer av ändringar som behöver genomföras/göras.

När vi använder oss av BPK-metoden så finns där en överhängande fråga om ”hur långt ska vi skala ned/upp sidan?”. För att besvara denna frågan så kan ni tänka er olika enheter ni vill nå ut till med er webbsida och tänka er vilka upplösningar dessa har- och sedan ha detta som ”max-upplösnings-gräns” och ”min-upplösnings-gräns”, eller så kan ni skala ned/upp sidan tills ni tror det inte är så stor mängd individer som kommer att kolla på sidan vid den upplösningen ni skalat om till (finns massor med statistik för detta (hur många som använder vilken typ av upplösning/enhet etc.) som enkelt brukar kunna hittas via Google eller andra sökmotorer på nätet).

Enhetsspecifika kodningsmetoden

Den Enhetsspecifika kodningsmetoden (hädanefter kan denne komma att hänvisas till som ESK-metoden) går ut på att man specificerar måtten för de specifika enheterna som finns idag som man vill sikta in- och optimera sin webbsidas layout för.


Uppenbara nackdelar med detta är bland annat att enheterna vi har tillgängliga att besöka internet och webbsidor via idag – ständigt förändras. Om vi då specificerar måtten för några specifika enheter som används idag, så lägger vi mycket tid på arbete som kan vara värdelöst om några månader, eller veckor om man verkligen har otur.


En fördel med detta sätt är dock för t ex. Testningssyfte eller om ni har specifika besökare där ni vet vad de kommer att besöka er webbsida med – t ex. Alltid från en specifik iPhone modell, eller iPad osv. (hur ofta detta nu än må hända) Då kan det kanske spara tid att använda denne metod- eller även för att begränsa Media Query CSS koden som gör sidan responsiv- då denna kan göra att sidan blir aningen segare att ladda vid “om-skalningen”.

Hur kodningsmässigt?

För vår Enhetsspecifika kodningsmetod så hade vår CSS Media Query kod haft en regel för en specifik enhets mått istället där sen då seriösa ändringar skulle ta plats för sidan.

Verklighetsbaserat exempel

Vid ett tillfälle valde jag för en av mina responsiva webbsidor att ha en maxgräns för 960px bredd, och mingräns för ca. 325px då det inte är många smartphones och mobiltelefoner som har den upplösningen i porträttläge idag (kollade upp detta med hjälp av statistik för vilka enheter och upplösningar folk använde vid det tillfället, som fanns insamlat och publicerat på nätet).

Responsiv webbdesign’s utvecklings- och testmiljö i Firebug & Google Developer Tools

När vi håller på att bygga vår responsiva webbsida så är det bra om vi har en ”testmiljö” där man enkelt kan skala upp och ned en webbsida och även identifiera när brytningar sker osv. Detta kan man enkelt och behändigt göra med hjälp av två av de populäraste webbläsarnas inbyggda webbutvecklings verktyg- Firefox Firebug, och Google Developer Tools för Google Chrome.

För att komma åt dessa lägen gör ni följande i Google Chrome: högerklicka på webbsidan ni önskar förhandsgranska med det responsiva designläget och välj ”inspektera” (chrome – [CTRL + SHIFT + I]). Därefter klickar ni på ikonen ni kan se nedan:

Toggle Device Mode aka Responsive testing environment

Som då kommer att öppna det Responsiva testläget för Google chrome som då ser ut såhär:

rwd mode gchrome

  1. Som ni då kan se i ovan bild så är det första inringade fältet i rött, möjligheten att välja specifika enheter vars upplösningar och skärmstorlekar då kommer läggas in för testning.
  2. Det andra rödmarkerade området är möjligheten att själva specificera specifika upplösningar att testa webbsidan i.
  3. Det tredje rödmarkerade området är en påminnelse om att sidan kan behöva uppdateras innan det responsiva testläget i Google Chrome fungerar optimalt.

Utöver ovan specificerade möjligheter och alternativ, så kan ni även se linjer som finns definierade både för höjd och bredd- personligen tycker jag detta är ett lite ”otydligt” sätt att visa vilken upplösning man skalat om webbsidan till, men det är i alla fall hur chrome gör saker och ting. För att förbättra detta kan man däremot ladda ned ett webbläsartillägg kallat ”Resize Window” för att (enligt mig) lättare kunna identifiera ”breaking-points” vid nedskalning av ens webbsida- dock funkar detta inte i chromes responsiva testläge, så detta behöver stängas först i sådana fall (vilket är lite trist).

Länk till var man kan ladda ned Resize Window webbläsartillägg för chrome, se nedan:

När vi pratar om Mozilla Firefox som webbläsare så har de sitt responsiva testläge placerat på annat ställe än tillsammans med inspektionsverktyget för webbsidor, istället hittar man deras responsiva testläge via webbläsarmenyn: Verktyg > Webbutvecklare > Responsiv designvy ([CTRL + SHIFT + M]). Se nedan:

firefox rwd mode


Personligen gillar jag Firefox Responsiva testläge så mycket bättre än Google Chrome’s, detta då man i Firefox responsiva testläge kan själv ”dra ut” en webbsida på bredden eller höjden som manuell omskalning på ett enklare sätt- däremot har Firefox responsiva testläge inte möjligheten som chrome’s testläge har att kunna välja specifika Enheter (såvitt jag kan se) att skala om sidan till att passa in för- om man skulle vara intresserad utav detta.

Cloudbased Browser & Device- compatibility testing online

Där finns även bra webbsidor för responsiva testanalyser av ens webbsida som kör en publicerad webbsida genom simulatorer för olika typer av enheter med deras specifika upplösningar och skärmstorlekar etc. Detta kallas även ibland för ”Live Cloudbased Browser Compatibility testing”.

Några sidor som erbjuder detta som ni kan testa och se vad ni tycker är som följer:


Där finns även en artikel om just sådan här typ av testning som kan vara av intresse att läsa igenom:–net-36521

Trots alla dessa sätt att testa sin responsiva webbsida finns där inget som slår den faktiska enheten man testar för tycker jag själv personligen. Exempel: testar ni er webbsida för iPad av någon speciell modell, så ta gärna och hitta någon som har en sådan iPad modell, och testa er webbsida hur den ser ut i denna modell så kan ni vara 100% säkra på hur den verkligen kommer se ut- för i vissa fall kan där finnas skillnader mellan simulerings- testsidorna och de verkliga enheterna.

Skillnader kan vara pixeldensitet eller finlir som bristande stödmjukvara för HTML5 Videotjänster och liknande. Ibland har inte dessa saker räknats med för de Cloudbaserade testing sidorna. Kan vara värt att ha i åtanke.

CSS Media Queries & Responsiv webbdesigns-specifik kod

Då har vi äntligen kommit till kodningsdelen för Responsiv webbdesign- och vi kommer att använda oss av en av de (enligt mig) bästa referenssidorna som stöd, nämligen Mozilla Developers Network Web Developers guide för CSS Media Queries:

I denna guide och på denna sida gås det igenom det mesta som har med Responsiv webbdesign att göra.

Nödvändig Meta-kod för Responsiv Webbdesign

För att indikera till mobila enheter att din webbsida är tänkt att vara responsiv och därför skalas om utefter CSS-koder så finns där en meta-tagg som informerar de mobila enheterna om detta. Den ser ut såhär:

<!-- Make browser understand this is responsive site and not in need of 'pinch-zoom-ins' -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

Se till att inkludera denna någonstans i ert <head> område för webbsidan.

CSS Media Query basics (grunder)

Media Queries CSS-kod i grund och botten är ganska simpla.

Man definierar en regel, och fyller sedan regeln med data- lite som i programmering när man sätter en IF-sats och definierar vad som skall hända inuti den.

Ett kodblock för Responsiv webbdesign kan se ut som följer:

@media (max-width: 960px) {
    div#mainContainer {
        width: 100%;
    /* added different values to match new responsiveness */
    article#mainContent { width: 100%; }

Man inleder alltid ett Media Query statement med @media. Därefter följer själva regel-definitionen skulle man kunna säga- i ovan fall så säger vi ”genomför dessa ändringar (inuti regeln) när bredden för sidan är mindre än- och upp till och med 960px”.

max-width attributet för vår Media Query ovan definierar när bredden för sidan är ”mindre än och upp till och med”.

Som ni sen kan läsa på MDN’s referenssida för CSS Media Queries så kan man definiera dessa för porträtt och landskapsläge, såväl som olika typer av media- t ex. om sidan skall bara anpassas för skärmar, eller även när den skrivs ut osv.

Man kan placera sin CSS Media Query kod i stort sett vartsomhelst- inkludera en separat fil som håller all sådan kod- eller lägga den längst ned i sitt vanliga CSS fil.

Testa er fram och försök på egen hand- tror ni kan lista ut det mesta själva – annars får ni mer praktiskt exempel på responsiv sida längre ned i denna artikel.

Läs igenom MDN artikeln- ni behöver inte gå igenom allting om ni inte vill- men kan välja ut de delarna som ni tycker verkar intressanta för just vad ni hade tänkt göra 🙂

Adaptiva och anpassningsbara måttenheter för responsiv typografi m.m.

Inom responsiv webbdesign kan det vara ganska attraktivt att ha textstorlekar som anpassar sig utefter att den s.k. ”viewport bredden” skalas ned eller upp för en webbsida. Där finns specifika CSS måttenheter för detta kallade ”vh” och ”vw” för viewport-height, och viewport-width.

Dessa måttenheter låter dig på din responsiva webbsida specificera måttenheter procentuellt baserade på sidans ”viewport height” respektive ”viewport width”.

Nedan kan ni läsa på mer om hur dessa måttenheter stöds i diverse olika webbläsare:


Och här får ni även länk till en väldigt bra artikel hos som går igenom dessa måttenheter i detalj om det är något ni skulle vara intresserade utav att använda:

Sen är det upp till er själva att experimentera med dessa 🙂

Manipulation av HTML dynamik via CSS (t ex. display: hidden vs. none)

När det gäller att ta bort element eller bara gömma element på sin webbsida och man gärna vill undvika JavaScript och hålla sig till CSS- så är attributet ”display” väldigt användbart.

Där finns två attributvärden som kan göra jobbet för en här:

  • none
  • hidden

display: none; kommer att fysiskt sett ”ta bort” ett element från webbsidan- och därmed ändra hela dynamiken av sidan, medan display: hidden; enbart kommer att ”gömma” elementet från besökares ögon- men fortfarande ha kvar elementet på sidan och därmed även bevara dynamiken för sidan.

Detta är användbara tips och tricks att tänka när det gäller layouten och hur den påverkas vid manipulation på sådant vis av HTML-innehållet via CSS.

Adaptiva och responsiva bilder – på två sätt (utan JavaScript)

När det gäller att anpassa sina bilder utefter upplösning på responsiva webbsidor så finns där säkert många sätt- varav några är JavaScript bibliotek som kan dynamiskt anpassa bilderna utan att man själv som utvecklare behöver bry sig speciellt mycket- dock är detta JavaScript och inte alltid så populärt + att det är lite mer krävande att ladda in än vad HTML och CSS är.

Via HTML och CSS kan man dock anpassa bilderna antingen genom att ange bredd och höjd med procentuella måttenheter (via CSS- då jag tvivlar på att detta funkar i HTML- men ni kan ju alltid testa bara för sakens skull), och sedan är det andra sättet att använda CSS Media Queries för att specificera att ”vid den specifika bredden/höjden skall bilden ändras si och så”.

Då kan ni även använda pixlar som måttenhet.

Touch-baserade features för responsiva webbsidor

Brist på indikations effekter jämfört med datorer (t ex. hover-effekt för länkar)

När man designar webbsidor för Touch-baserade enheter finns där några saker att tänka på. T ex. att touch-baserade enheter inte har den här s.k. ”link-hover” effekten som datorer med datormöss har som träder i kraft när man håller musen över en länk.

Man kan då istället använda sig av de äldsta tricken i boken när det gäller indikationer för klickbarhet så är de flesta vana vid att klickbara saker på webbsidor är understrukna då detta brukade vara en standard förr som många fortfarande håller fast vid.

Så understruken text kan kanske kompensera för bristen av ”hover-effekt” och liknande för länkar.

Fingrar istället för datormöss och precisionsverktyg för klickande och val

Touch-baserade enheter har heller inte lika lätt för att klicka på mindre ”klickområde” som en dator mus kanske inte har några problem att komma åt- då man använder fingrarna istället för ett precisionsverktyg att klicka med (undantaget de som klickar med touchpennor eventuellt).

Detta innebär att man måste tänka på sådana här saker när man designar sina layouter för touch enheter- desto större klickområde- desto bättre, och desto lättare för besökare att klicka på saker på ens webbsida.

Handpositionering för smartphones och surfplattor

Ytterligare en aspekt att tänka på (nu går vi in lite på ett område kallat Interaktionsdesign) är hur folk kan tänkas hålla t ex. mobiltelefoner av olika storlekar, eller surfplattor när de är ute på internet. Detta kan ha stor effekt på hur ni bör designa responsiva webbsidor när ni börjar närma er upplösningar motsvarande de av surfplattor och smartphones.

Exempel Responsiv Webbdesigns kod- och Effekt i praktiken {background-color: #ccc; width: 800px; border: 1px solid #000; padding: 6px 12px; box-sizing: border-box;} p {font-size: 36px; color: #00f; line-height: 1.5em;}

@media (max-width: 800px) { {
         background-color: #0f0;
          width: 600px;
    } p {
         font-size: 28px;
          color: #000;

@media (max-width: 600px) { {
          background-color: #00f;
          width: 400px;
    } p {
         font-size: 18px;
          color: #fff;

@media (max-width: 400px) { {
         background-color: #000;
          width: 200px;
    } p {
         font-size: 14px;
          color: #0f0;




Vid frågor om hjälp eller bara allmänt- se e-post på kontaktsidan.

Step 1: File structure

-file:   index.php
-file:   index.html (base-template file)
-folder: incl/
-file:   incl/header.php
-file:   incl/footer.php
-file:   incl/config.php
-file:   incl/functions.php
-folder: css/
-file:   css/mainstyles.css
-folder: img/

Step 2: Create the base-template file (index.html)

This is where we build our website as a normal .html file with headers, body, footer, and the whole layout in one file.
This will in turn be our base template to later disect into 3 pieces (header.php for header code, index.php for body and site code, footer.php for endpage-code)

Our base-template file will be very basic and simple and can be seen below:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>This will be our first Dynamic website using PHP dynamic templating techniques :)</title>
<!-- Below is our main stylesheet for the page -->
<link href="css/mainstyles.css" rel="stylesheet" type="text/css" media="all" />
<!-- Below adds a 'shortcut-icon' a.k.a. 'bookmark/favorite icon'-->
<link rel="shortcut icon" href="img/favicon.ico">
<!-- Make browser understand this is responsive site and not in need of 'pinch-zoom-ins' - Commented for now- remove if u want to use this-->
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0" /> -->
<!-- Below allows for addition of this particular page's description for SEO -->
<meta name="description" content="" />
<!-- Below allows for ability to define SEO keywords for this particular page-->
<meta name="keywords" content="" />
<!-- Below Meta-tags tells SE-Indexation spiders to index page and follow pagelinks of site -->
<meta name="robots" content="index, follow" />
<div id="mainContainer"> <!-- Wrapper for page -->
 <img src="img/logo.jpg" width="200" height="60" alt="" />
 <h1>Our homepage</h1>
 <p>- Slogan for this website</p>
 <li><a href="#" target="_top">Home</a></li>
 <li><a href="#" target="_top">Portfolio</a></li>
 <li><a href="#" target="_top">About us</a></li>
 <li><a href="#" target="_top">Contact</a></li>
 <h1>Content area for site is here...</h1>
 <p>And this is where all the content for the individual pages will end up.</p>
 <p>&copy; Copyright <?php echo date('Y'); ?>. All rights reserved.</p>
 <hr />
 <a href="#" target="_top">Sitemap</a>
 <a href="#" target="_top">FAQ</a>
 <p>Phone: 070X-XX-XX-XX &bull; Email: &bull; Address: Fictionstreet 32B, CA, USA</p>
</div> <!-- End of Wrapper for the page -->

Step 3: Breaking this down for ya in detail how this is going to work.

Okay, so the idea is to divide this website we just created into different parts (header, content and footer)- and we do this by analyzing which parts will be recurring throughout every single subpage of the website.
For example we can be pretty sure that all the code belonging to the “header” section including the main menu will be available on every single subpage- as will the footer code. This means that we can take all this code and place it in separate files – in our case we call these files header.php & footer.php and have them placed in a folder named: incl, which stands for “includes”.

Why do we do this then? Well the idea is to later include these separated external files which together contains all the code for the entire page layout.
In this way we “re-create” the website section by section by including these parts into the “main-subpage-file” – such as index.php for the mainpage, and contact.php for the contact page for example, etc.

Step 4: Start disecting & dividing the individual sections of the page which will reoccurr throughout all subpages of the website.

###- header.php - can be seen below
<!DOCTYPE html>
<meta charset="utf-8" />
<title>This will be our first Dynamic website using PHP dynamic templating techniques :)</title>

<!-- Below is our main stylesheet for the page -->
<link href="css/mainstyles.css" rel="stylesheet" type="text/css" media="all" />

<!-- Below adds a 'shortcut-icon' a.k.a. 'bookmark/favorite icon' -->
<link rel="shortcut icon" href="img/favicon.ico">

<!-- Make browser understand this is a responsive site and not in need of 'pinch-zoom-ins' - Commented for now- remove if you want to use this -->
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0" /> -->

<!-- Below allows for addition of this particular page's description for SEO -->
<meta name="description" content="" />

<!-- Below allows for ability to define SEO keywords for this particular page -->
<meta name="keywords" content="" />

<!-- Below Meta-tags tells SE-Indexation spiders to index page and follow pagelinks of site -->
<meta name="robots" content="index, follow" />
<div id="mainContainer"> <!-- Wrapper for page -->
 <img src="img/logo.jpg" width="200" height="60" alt="" />
 <h1>Our homepage</h1>
 <p>- Slogan for this website</p>
 <li><a href="#" target="_top">Home</a></li>
 <li><a href="#" target="_top">Portfolio</a></li>
 <li><a href="#" target="_top">About us</a></li>
 <li><a href="#" target="_top">Contact</a></li>
###- footer.php - can be seen below
 <p>&copy; Copyright <?php echo date('Y'); ?>. All rights reserved.</p>
 <hr />
 <a href="#" target="_top">Sitemap</a>
 <a href="#" target="_top">FAQ</a>
 <p>Phone: 070X-XX-XX-XX &bull; Email: &bull; Address: Fictionstreet 32B, CA, USA</p>
</div> <!-- End of Wrapper for the page -->

Now as you can probably see we included the “<article>” in the header.php file, while we included the “</article>” in the footer.php file, but totally ignored the content of <article> in both files.
We did this because we plan ahead- every subpage will probably have the need for an general “content-container” to place that particular pages contents in – so we make the <article> container itself become re-occurring, whilst the content of the container- is not.

So perhaps you’re asking yourselves now whats next? Well, we need to put the website back together again after having disected it- thats our next move- including the header.php & footer.php in the index.php for the main-subpage.

###- index.php - can be seen below:
<?php include('incl/header.php'); ?>
<!-- Here comes the HTML content specific to this Mainpage (will be placed inside of <article> in header.php since that is the last piece of code included with the header.php file) -->
<?php include('incl/footer.php'); ?>

Now the website will have been recreated in index.php since it first includes header.php (and all the code this file holds), then the HTML-content for that specific subpage, and last but not least- the footer.php file and the code that file holds.

Step 5: Explain the overflow files such as config.php & functions.php (plan ahead purpose)

Okay, so you might be wondering now that we seem to be done already why I made 2 extra files in the incl/ folder? Well this is simply because “looking & planning ahead” – in the future the config.php file will hold configuration code for the entire page, while the functions.php file will hold useful functions which later can be included into the header.php to be available for all of the respective subpages.

And another thing worth pointing out- the footer.php will be able to hold all the JavaScript file inclusions as well as Google Analytics code which you want to load in at the end of all subpages. Which also is a very nifty, useful and handy feature to have available.

Step 6: Spice up the webpage a bit more with dynamic SEO content for each individual page? as well as Titletext? 🙂

There are tons of fun stuff you can do with a Dynamic website template like this in PHP – for example if we want unique <title> texts for each individual subpage – we only replace our current HTML content in the header.php file
within <title> & </title> with something like: <?php echo $subPageTitleVariable; ?>
And then all left to do is to in index.php ABOVE WHERE WE INCLUDE HEADER.PHP -> place $subPageTitleVariable = "our specific subpage &lt;title&gt; text"; for example. and this would be available for the header.php file to make use of seeing as how we placed it ABOVE where header.php was included and PHP works vertically through the code from top->bottom. with top-content being available for bottom-content on a code page.

This method & technique can also be utilized- and comes in very handy for On-Page SEO where you need to specify specific keywords/descriptions for each individual subpage.

As a Last thing to mention I will recommended you to start the config.php file by placing <?php error_reporting(-1); ?> to report ALL Possible (PHP) errors on the page for debugging (recommended to be turned off when publish page – 0 as value instead of -1). And Also to include config.php ABOVE HEADER.PHP in INDEX.PHP file. so that the Error Reporting is active for ENTIRE PAGE.

Good Luck with all your Coding out there now 😉
This tutorial was brought to you by:

Hope you learn something new and get some new ideas for your next projects 😉 Was a pleasure helping out and hopefully inspiring to new creativity 🙂 Enjoy!