Strings will have their own special section in the OO part of the website. Strings are a great way to explain some of the concepts of OO which I will not bore you with YET!

String test = "Hello";

Remember I said that int, float etc are all primative types? No? Well they are! Strings on the other hand are objects. This means that they behave differently to int's and float's. The above code may not look any different but what is happening inside Java is different.

Do not worry about that yet as we will cover it in depth in the OO section. But it does mean that we can not do certain things with a String. For example -

  1. String aNum = "88";
  2. int secNum = 22;
  3. int answer = (int)aNum +secNum;

This will fail with a "inconvertable types" error. Fail. Another example of Java not being too bright. What Java see's is not a number in aNum but some text and so thinks "You cant add text to a number , thats just silly!". Thus the helpful error message. Look at this example -

  1. String a = "8";
  2. String b = "2";
  3. String answer = a + b;

What will answer contain? "82". Why not 10? Simple. Java thinks they are bits of text. The only way it can think of to add two bits of text together is to concatonate them. That is shove them one after another.

The other big difference between a String and a number is the use of quotation marks. Look at the example below -

  1. String text = "Hello";
  2. String moreText = good bye;

Line 2 gives some epic fails! The reason is that text without quotation marks is treated as a variable name. We can be a bit fancy and call the text with quotation marks as a literal. String literals must be contained in quotation marks. This is true for all programming languages (that I am aware of) so get used to it.

A literal is a hardcoded value within a program such as a number or some text.

next example code >>

 
Basics
Menu
Search