Tuesday, January 29, 2019

Java tutorial: initializing variables, literals, escape sequences, Introducing String class

References/Links: http://pasted.co/109159db

Chapters

Hello everybody! This is brainy ghosts and today we're gonna discuss initializing variables, literals, escape sequences and introduce the String class.

If you're ready then let's get started!

We're gonna use the Beginner class that we created in previous tutorial, If you deleted it or it's missing please check the link above and download the Beginner class there so you won't write all the code again. Open your preferred text editor then open the Beginner class. In previous tutorial we just declared instance variables in the Beginner class then the JVM assigns a default value to each variables implicity. Today we're gonna explicity initialize the instance variables here, before we do that let's discuss the literals first.

Literals

Literals are notations for representing a fixed value in source code. It is syntactic representation of boolean, character, or String data. Literals provide a means of expressing specific values in your program.

Here are examples of literal types in java:

Base System literals

Binary - e.g. 0b11110101(0b followed by a binary number)
Octal - e.g. 0365(0 followed by an octal number)
Decimal - e.g. 245
Hexadecimal - e.g. 0xF5(0x followed by a hexadecimal number)

Type Literals
Boolean Literals: true,false
Character Literals: e.g. 'A'

Integer Literals
Decimal: e.g. 245(default literal for byte, short, int and long type)
Binary:  e.g. 0b110111
Octal:  e.g. 0615
Hexadecimal:  e.g. 0xFF6655

Long Literals: 
Decimal:  245L
Binary: e.g. 0b110111L
Octal: e.g. 0615L
Hexadecimal: e.g. 0xFF6655L

Float Literals: e.g. 3.50f
With exponents: 1.72E3f
Hexadecimal floating-point with mandatory exponents and "f" suffix: 0x.5FP0f, 0x5.FFP2f

Double Literals: e.g. 3.50(default literal for double)
With optional "d" suffix: 3.50d
With exponents: 1.72E3d
Hexadecimal floating-point with mandatory exponents and "d" suffix: 0x.5FP0d, 0x5.FFP2d

Null Literal: &null

String Literals: e.g. "String"

Boolean, Integer and Long Literals

Now that we know what literals are let's try to add those in our code. To initialize a primitive variable we will use the assignment("=") operator then write the literal that we want, then type of literal must match the type of the variable.

Let's start with the boolean, there is two boolean literal values and that's the true and false. There's no byte and short literal to java so we will use the integer literals for these two because integer literals is the default literal value for numeric data type like byte, short, int and long.

Code:
public class Beginner
{
   boolean booleanVar = true;
   byte byteVar = 100;
   short shortVar = 1000;
   int intVar = 1000000;
   long longVar = 100000000L;
   //more codes here later...

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

   //more codes here later...


  }
}
Adding the "L" suffix in long literal is optional when we write a literal that is in the size range of int for example if we put 10,000 as the long variable value, the compiler won't complain about the missing "L" suffix.
Code:
public class Beginner
{
   boolean booleanVar = true;
   byte byteVar = 100;
   short shortVar = 1000;
   int intVar = 1000000;
   long longVar = 10000;
   //more codes here later...

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

   //more codes here later...


  }
}


compile the code and check the result. We can see that the compiler didn't complain about the missing "L" suffix. If we try to change the literal to a higher value like 10 billons, let's try that, put 1 then 10 zeroes then compile and run the program. We can see that the compiler complain and throws an error "The integer value too large".


"integer too large" error


this error occurred because the compiler knows that the integer size of int is ranging from -2,147,483,648 to +2,147,483,647 and because we didn't put an "L" suffix at the end of the value, the compiler consider this literal as an int then this value is too large for int to store that's why the compiler throw that error.

If we put the "L" suffix then compile and run the program. We can see that the compiler didn't throw an error, that's because we put the "L" suffix at the end of the literal and now the compiler knows that this literal is a long literal.

You might wonder: I thought when assigning an integer literal to another numeric data type like long the compiler will do the conversion automatically so why did the compiler still throw an error?

That's because, the compiler will check the literal first before converting it to the type of the variable so the compiler will consider the literal as an integer literal because it doesn't have an "L" and since the literal value is out of range for int, the compiler will complain.


Double and Float Literals

For the double literals adding "d" suffix is optional when writing a decimal values, so if we type 0.5, this literal is a double, if we want to be more specific we can put the "d" suffix at the end e.g. 0.5d. For float literals we need to put the "f" suffix at the end so the compiler will know that this literal is a float literal.
Note: If you're dividing two whole(int) numbers, putting the suffixes of double and float affects the result of our division e.g. 1000/60 = 16.0 , 1000f/60f = 16.666666

Code:
double doubleVar = 0.5;
double doubleVarTwo = 0.5d;
float floatVar = 0.5f;
let's try removing the "f" suffix and we will encounter an error.

"incompatible types" error


We can see that the compiler throws an error, this error means that we are trying to downcast double to float implicitly and java doesn't allow implicit downcast but implicit upcast is allowed.

Upcast and downcast are beyond to be covered in this tutorial, upcast and downcast are part of the typecasting/type conversion topic in java which will be covered in future tutorials but today i'll just give the general concept of upcast and downcast so you will have an idea on how upcast and downcast works.


Introducing Upcast and Downcast

Upcasting is converting a subtype to a supertype for example, float which is a subtype can be implicitly/explicity converted to double.

Downcasting is converting a supertype to a subtype for example, double which is a supertype can't be implicitly converted to double.

However, it's possible to convert double to float explicitly with the possibility for data loss. Same goes when you try to convert long to int, let's try that, then compile and run, and the compiler throws an error.


"incompatible types" error


Now, let's return our code to normal where there's no error. The long, float and double suffixes are case-insensitive so we can change those suffixes to lowercase and uppercase.

However, in the long suffix I recommend to leave it as an uppercase because if we change that to lowercase it will look like number one which is treacherous to our eyes.

Character Literals

For character literals we can use the unicode escape sequence like this:
Code: 
public class Beginner
{
   boolean booleanVar = true;
   byte byteVar = 100;
   short shortVar = 1000;
   int intVar = 1000000;
   long longVar = 10000;
   double doubleVar;
   float floatVar;
   char charVar = '\u0090';

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

   //more codes here later...


  }
}
The literal that we put in charVar is a unicode character literal, that literal represents a question mark symbol. There is a unicode character table that I provided in the Reference/Links.

View the unicode table and then hover our mouse on a character, we will see a tooltip with a strange text, well, this strange text the U+(number) is the unicode representation of that character, then the next portion of the text which is the Dec:(number) is the decimal representation of that character.

Notice the first character in the table in row "0000" this character is a null character which I already mentioned in previous tutorial. Null character represents nothing so it's not printable on the console. When we click the character we will see the unicode number and the html code which can be used in html.

Ok! let's try to display some of these characters on the console e.g. \u0100 . Then type the unicode value to the char variable then compile and run. We can see that the character is now displayed on the console.

We can also use the decimal representation of the character. Let's try to change the unicode to decimal value(e.g. '64') then compile and run.We can see that the unicode and decimal value in char is the same because they represent the same character in the unicode table.

We can use octal escape like this (e.g. '\141'), we can use the character itself as a char value(e.g. 'a') and we can use hexadecimal(e.g. 0x97 without quotes). The "0x" before the hexadecimal number is the hexadecimal prefix. The "0x" prefix usage is to indicate that the number is a hexadecimal.

Note: we can only put one character value in single quotes e.g. 'a'. If we put multiple characters e.g. 'ab', we will get an error.

We can also use the ASCII table characters since unicode is a superset of ASCII. ASCII table link is in the references/links link. In addition to integer literals, we can also use binary, octal and hexadecimal this is how you write an octal number (e.g. 0365).

When writing an octal into integer literal we must put zero first then the octal number so the compiler will know that the number is octal, when we compile and run our code, we can see that the value displayed on int is "245" which is decimal equivalent of octal number "365".

for hexadecimal put "0x" first before the hexadecimal number like this (e.g. 0xF5). For binary put "0b" first before the binary number like this (e.g. 11110101). Binary, octal and hexadecimal can be used to mask integer literal values
Code:
public class Beginner
{
   boolean booleanVar = true;
   byte byteVar = 0b10101;
   short shortVar = 035;
   int intVar = 0xFFA3;
   long longVar = 1000;
   double doubleVar;
   float floatVar;
   char charVar = 0x97;

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

   //more codes here later...


  }
}
Double and Float with hexadecimal and exponents

We can also use exponents and hexadecimal on double and float literal, I'll only show how to apply exponents and hexadecimal to float because you can apply the procedure that we will do to double, just change the suffix.

Let's do the exponent first, to apply exponent to float literal put a capital "E" or small "e" after the float number then put the exponent number it can be positive or negative and the exponent must not have a decimal point or fractional part then put "f" suffix after the "e" (e.g. 1.72E2f). compile and run and see the result.
Code:
public class Beginner
{
   boolean booleanVar = true;
   byte byteVar = 0b10101;
   short shortVar = 035;
   int intVar = 0xFFA3
   long longVar = 1000;
   double doubleVar = 0.5d;
   float floatVar = 1.72E2f;
   char charVar = 0x97;

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

   //more codes here later...


  }
}
If you don't know scientific notation or standard form then, you don't know how the output result ended like this. Let me remind you then, Scientific notation is a special form of writing numbers so, for example, we write this float number "1.72E2f" into scientific notation, it will be like this e.g. 1.72 x 10^2.

It means that we need to multiply 1.72 by 10 raise to 2 which is equal to 100, let's try that and compare our answer to the output, If you're using window just open the calculator app then multiply 1.72 by 100, As you can see our answer in calculator is the same to the console output.

You can also use negative exponent but instead of multiplication you will divide the float number by 10 raise to the exponent number in our case 10 raise to 2. If you use 0 as an exponent number the float number won't change obviously because there is nothing to divide or multiply.

Now, let's try to use hexadecimal, to use hexadecimal write the hexadecimal prefix first which is "0x" then the Hexadecimal digits, these digits will represent the whole number of the float literal e.g. 0x55f.

If you only want the fractional part then, write "0x", followed by decimal point, followed by hexadecimal digit. The hex digit will represent the fractional part of the float literal. Then, put a capital "P" or small "p", followed by the exponent number, followed by the float suffix e.g. 0x.FP2f.

Code: float floatVar = 0x.FP2F;
Result: 3.75

The computation in hexadecimal is different and more tricky than the exponent that we discussed earlier. To solve the problem, our first step is to convert the hexadecimal to decimal, first convert the whole number of the float literal to decimal. Since we don't have a whole number we can skip this step and convert the fractional part.

Convert each hex number in the fractional part to decimal then divide them by 16^[hex position starting from left to right]. For example, in our case the "F" hex which is 15 is in the 1st position so we will divide 15 to 16^1(16^1 = 16 * 1) then divide the next hex number to 16^2(16^2 = 16 * 16) and so on. then add the whole and the fractional part: zero plus .9375 is equal to 0.9375.

Once we're done at converting, the last step is to multiply the decimal by 2 raise to the exponent number which is 2 in our case and 2^2 is equal to 4 so 0.9375 * 4 = 3.75 which is the output of our program.

If you use negative exponent number the step is the same except to the last step, use division instead of multiplication when dealing with negative exponent number. If you use zero as a exponent number then java will only convert the hexadecimal to decimal and display it on the console.


String Literals and Introducing String Class


Now, let's discuss the String class, String class or String for short is an object that represents series of characters, String is immutable which means that once we create it we cannot change it. When we change any String, a new instance is created. We will learn more about String immutability in future tutorials.

Take note that the String is a reference type not a primitive type, most beginners thinks that String is a primitive type which is wrong. String is a big topic to cover and it will take time to explain all of its features so i'll only explain the basic usage of String here. Ok! let's declare a String variable, then after that let's add a println() method and put the string variable there, then compile and run.
Code:
public class Beginner
{
  boolean booleanVar = true;
  byte byteVar = 0b10101;
  short shortVar = 035;
  int intVar = 0xFFA3;
  long longVar = 1000;
  double doubleVar = 0.5d;
  float floatVar = 3.5f;
  char charVar = '\u0090';
  String strVar;
  

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

    System.out.print("boolean: ");
    System.out.println(beginner.booleanVar);
    System.out.print("byte: ");
    System.out.println(beginner.byteVar);
    System.out.print("short: ");
    System.out.println(beginner.shortVar);
    System.out.print("int: ");
    System.out.println(beginner.intVar);
    System.out.print("long: ");
    System.out.println(beginner.longVar);
    System.out.print("double: ");
    System.out.println(beginner.doubleVar);
    System.out.print("float: ");
    System.out.println(beginner.floatVar);
    System.out.print("char: ");
    System.out.println(beginner.charVar);
    System.out.print("String: ");
    System.out.println(beginner.strVar);


  }
}


We can see that the String default value is null which is expected because it has been discussed in previous tutorial. There are two ways to instantiate a String object, The first way to instantiate a String object is to use String literal e.g. String strVar = "Hello Java!"; compile, run and see the result. The second way is to use the new keyword
e.g. String strVar = new String("Hello Java!"); compile,run and see the result.

You might notice that the two String declaration syntax produce the same result and usage. You can't see any difference when instantiating and using the String but when we go behind the scenes into the memory level we will see their difference. We will discuss that topic in future tutorials, let's stick to the basics for now.


Character Escape Sequence


We can also form a text using the unicode and octal escapes that we used in char, let's try to display "Hello" using the unicode escape sequence, let's view the unicode table then pick the characters that we need.


public class Beginner
{
  boolean booleanVar = true;
  byte byteVar = 0b10101;
  short shortVar = 035;
  int intVar = 0xFFA3;
  long longVar = 1000;
  double doubleVar = 0.5d;
  float floatVar = 3.5f;
  char charVar = '\u0090';
  String strVar = "\u0048\u0065\u006C\u006C\u006F";
  

  public static void main(String[] args)
  {
    Beginner beginner;
    beginner = new Beginner();

    System.out.print("boolean: ");
    System.out.println(beginner.booleanVar);
    System.out.print("byte: ");
    System.out.println(beginner.byteVar);
    System.out.print("short: ");
    System.out.println(beginner.shortVar);
    System.out.print("int: ");
    System.out.println(beginner.intVar);
    System.out.print("long: ");
    System.out.println(beginner.longVar);
    System.out.print("double: ");
    System.out.println(beginner.doubleVar);
    System.out.print("float: ");
    System.out.println(beginner.floatVar);
    System.out.print("char: ");
    System.out.println(beginner.charVar);
    System.out.print("String: ");
    System.out.println(beginner.strVar);
  }
}
Then compile and run, and as you can see the hello word is displayed on the console and we used the unicode escape sequence for that.

What if we want to display a double quotes(") on the console how can we do that?, since the double and single quotes have a usage in the java language we can't use it directly like this: String strVar = """;

when we do that we will receive an error but there is a way to use the quotes as a string value, There are two ways that I know on how to use quotes as a String value the first way is to find the unicode or octal representation of the quotes.

Since we already used the unicode escape sequence, we will use the octal escapes next to demonstrate that the octal will work as a String value. Let's open the ascii table and find the octal number for double quotes then put it before and after the "Hello" word. The octal number for double quotes(") is "\42" or "\042".
Code: String strVar = "\42\u0048\u0065\u006C\u006C\u006F\42";

Then compile and run, As you can see we displayed the double quotes on the console.
If we try to use unicode characters, we will encounter an error. Unicode character for double quotes is "\u0022".
Code: String strVar = "\u0022\u0048\u0065\u006C\u006C\u006F\u0022";

Why we have an error? The thing about having an error using the double quotes unicode inside double quotes is about how java treat double quotes unicode character. When we put the double quotes unicode character in double quotes. Java literally treats this unicode as a double quote. If we remove the double quotes, we will see that "Hello" has been printed without double quotes.
Code: String strVar = \u0022\u0048\u0065\u006C\u006C\u006F\u0022;

We can separate the double quotes unicode character from the "Hello" word and use single quote like this
String strVar = '\u0022' + "\u0048\u0065\u006C\u006C\u006F"+'\u0022';
In this code, we are indicating to the compiler that we want the character form of \u0022 and combine it with the characters in double quotes.


To display single quote on the console just find the unicode or octal representation of single quotes then replace the character before and after the "Hello" word with the single quote escape sequence. The octal number for single quote(') is "\47" or "\047".
Code: String strVar = "\47\u0048\u0065\u006C\u006C\u006F\47";
You can mix unicode, octal and the character itself when forming a text as a String value but characters are mostly used when forming a String literal for obvious reason.


As we have seen, backslash(\) has a special function in java strings. We use backslash for octal and unicode characters. We also use backslash for special characters like \n. To use backslash as a literal we need to escape it. Escaping characters or strings is putting backslash before the character/string to override its intended purpose.

For example, "47" is a string literal that represents "47". If we escape that string("\47") then, "\47" is now an octal character that represents single quotes('). Now, to escape backslash(\) we need to add another backslash before the backslash that we wanna escape.
String strVar = "\\";
or
String strVar = "\\u0062";

unicode \u005C or \u0062(5+12) represents backslash(\)


Special Character Escape Sequence


Now, let's discuss the specific special character escape sequences.

Let's change our String value to a series of character first so we can read and edit it easily and this time our word should be "Hello Java".
Code: String strVar = "Hello Java";

Let's start with "\n" or the newline, You probably heard newline in my previous tutorials, well, the newline will move our word down to the next line or terminates a line let's try this character.
Code: String strVar = "Hello\nJava";

As you can see the java word goes down one line. Notice that the "\n" character function is like the no argument println() statement. We can say that their function is the same but the "\n" character can be used in conjunction with string literal while the println() method can only be used on the console to display output. We can use the "\n" and the println() to adjust the indent of text on the console.

Next is the "\r" or the carriage return, this character escape return to the beginning of the line let's try it.
Code:
String strVar = "Hello Java\rChange";
System.out.println(strVar);


then compile and run. As you can see the "Hello" String in System.out.println() has been changed to "Change" string, it happened because when java see the "\r" character it will go back at the beginning of the line then continue to print the text after "\r",thus overwriting some words on the line. In this example, we can see that the String text before "\r" has been overwritten.

the "\f" or the form feed character means advance downward to the next page, I can't show how this character works because it's not working on the console when I tried to use the form feed character, it displayed a character instead of advancing downward.

Next, is the "\t" which insert a tab in the text at this point let's try it.
Code: String strVar = "Hello\tJava";
As you can see the two words have more spaces in between.

The "\b" put a backspace in the text
Code: String strVar = "HelloJ\bava";
As you can see the letter J in java has been removed.

Next is the \', \" and \\ characters, the purpose of these characters is to insert single quote, double quote and backslash in the text, now we know the other way to put single and double quotes in our text the first one is by using the unicode or octal escape and the second way is this, let's try these characters.
Code:
String strVar = "\'HelloJava\'";
String strVar = "\"HelloJava\"";
String strVar = "\\HelloJava\\";
These characters are much preferred to use than their unicode or octal counterpart.


Conventional naming for numeric literals


we can use the underscore in between digits to increase readability of the integer,float and double literals like this:
Code:
long longVar = 10_000_000_000L; double b = 300_50.5_000_50;
Remember, you can only use underscore in between digits you can't use the underscore in the beginning or to the end of the number or after the literal suffix if you try what I said you will encounter an error.


Declaring Multiple Variables using ","


Next is the other way to declare variables, if we are declaring multiple variables with the same type you can declare them on one line by using the comma to separate each variable like this:
Code: boolean booleanOne,booleanTwo,booleanThree;

Then you can initialize them by adding the equal sign to each variables like this:
Code: boolean booleanOne = true,
booleanTwo = false,booleanThree = true;



No comments:

Post a Comment