Wednesday, January 30, 2019

Java tutorial: Typecasting(primitive types)

Typecasting(primitive types)

Type casting in java is casting a type explicitly or implicitly to another type in their respective data type group. In other words, you can only cast a primitive type to another primitive type and an object type to another object type, for example, you can cast int to float and class instance to another class instance. 

In this tutorial we will focus on casting primitive data types, casting reference types will be covered in future tutorials. Also, you can somewhat cast a primitive to a reference type, for example, int primitive to Integer reference type and that topic will be also covered in future tutorials. There are two distinct type of typecasting in java, the widecast or upcast and the narrowcast or downcast.

Upcast is also called implicit conversion because once you convert a specific type to another type it will be converted automatically without writing some extra explicit cast syntax. Downcast or explicit conversion, on the other hand, needs an extra explicit syntax to cast a specific type to another type with a possible of data loss.

You might wonder: "if downcast can cause data loss then it is not a good idea to do a downcast because it will ruin the value of the data that i want to convert". Well, that's one of the possible reason why java restricts automatic conversion when doing a downcast, In other words, We are downcasting because we know what we are doing.

These are the several reasons that can cause data loss when downcasting: casting a floating-point to integer for example casting float to int, when you cast float to int the decimal or fractional part of that float will be lost. Next is, casting a large data value that exceed the size of the destination type. For example, if you convert int to byte and the int value is larger than the size of the byte that it can hold, the int value may lose some of its value.

Here's a figure guide for java primitive type casting.







To clearly understand typecasting and all of the thing that we discussed let's test it on actual coding. First create a java source file in our workspace folder, then name it "SampleConversion" and then write the basic code structure of our source file the public class and the main method.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   
 }

}
Then, let's declare and initialize some primitive variables in the main method.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 0;
   byte byteVar = 0;
 }

}
Notice that we initialized the variable in the main instead of initializing it on the top of the main method. These variables are called a local variables. Local variables will cease to exist when the execution leaves the method where they reside.

Upcasting Primitive Type

Now, Let's try the upcast, to do that assign the byte variable to the int variable then compile and run.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   byte byteVar = 100;
   int intVar = byteVar;

   System.out.println("byte: " + byteVar);
   System.out.println("int: " + intVar);
 }

}
As you can see the int variable has a value of 100 which is the same value of our byte variable. You might wonder that the byte variable value should move to int variable since we assigned it to int. Well, java copied byteVar value and assigned the copied value to intVar. When doing upcast or widecast be sure to follow the order of data type in the upcast figure that I showed earlier.

Downcasting Primitive Type

Next is the downcast, to do downcast follow me, let's try to downcast int to byte as an example, we did the upcast earlier and now we will be doing the downcast which is the reverse process of upcast. Assign a 100 value to the int variable then assign the int variable to byte.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 100;
   byte byteVar = intVar;

   System.out.println("byte: " + byteVar);
   System.out.println("int: " + intVar);
 }

}

When we run this now we will receive an error, try to run the code. As you can see an error occurred, I already demonstrated this in previous tutorial so I suppose you're familiar with it. To remove that error type, we need to specify the target type in parentheses like this (target-type) before the primitive type that we want to convert, then compile and run.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 100;
   byte byteVar = (byte)intVar;

   System.out.println("byte: " + byteVar);
   System.out.println("int: " + intVar);
 }

}

As you can see we discarded the error, we cast an int value to byte and our program runs normally.

Downcasting a Value That Exceeds Destination's Capacity

Now, let's try to convert a larger int value to byte let's try 1000, If we assign 1000 to a byte data loss will occur let's try it! change the value of int variable to 1000 then compile and run.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 1000;
   byte byteVar = (byte)intVar;

   System.out.println("byte: " + byteVar);
   System.out.println("int: " + intVar);
 }

}
As you can see the converted value is too far off from the original value. You might asked yourself "Why the converted value is -24, How's that happened?". If you want to have a deep understanding about the situation I recommend you to study decimal and binary number system, one's and two's complement, adding and subtracting binary numbers. I won't cover those topic here, those topic are not part of this tutorial maybe I will cover them in my future tutorials.

To have a better understanding on how the converted value end like that we will use the windows calculator instead of computing it manually. Open the calculator type then switch to the programmer's mode, then make sure decimal or Dec radio button is selected and select the dword radio button,we will use dword which is a 32-bit value, since int data type is 32-bit.

Switching to Programmer's mode


Setting our calculator


Then input the int value which is 1000, then click the binary or bin radio button to convert the int value to binary. Also, focus on the bits that is highlighted in red

Converting 1000 from decimal to binary


When java converts the int value to byte some bits of int value to the left will be discarded, so to do that in the calculator all we need to do is to click the byte radio button to change the bit size to 8 bits which is the size of byte data type in java.

Converting int bits to byte bits


As you can see the left bits at the left side was discarded. Then, click the dec radio button to convert the binary to decimal and as you can see the answer on the calculator is the same as the output on the console.

Converting binary to decimal


If you know how the general conversion of binary to decimal you might say that this binary is equal to 232 when converted to decimal. Well, That's true when you convert an unsigned numbers to binary, unsigned numbers means a data that has no negative value just a plain whole numbers, but we're converting a signed numbers and to convert a signed number java uses the two's complement method.

We did use two's complement on the calculator earlier and we didn't notice that we used it because the calculator did most of the work for us. The procedure that we used earlier at the calculator can also work on other integers like long and short if you have spare time try to downcast other data types like long to int or short to byte then compute the output using calculator.

Casting a Type to Character Primitive

What about casting a type to char, Since char is separated from integer data types such as byte,short,int and long and floating-point data types like float and double, downcasting is needed.

Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 1000;
   byte byteVar = (byte)intVar;
   char charVar = (char)intVar;

   System.out.println("byte: " + byteVar);
   System.out.println("int: " + intVar);
   System.out.println("char: " + charVar);
 }

}
What about downcasting a type to boolean? I suppose we can't downcast any data type to boolean. Remember, when downcasting, don't forget the parentheses then the data type in the parentheses.

Non-Floating Point Typecasting During Operation

Apart from boolean and long type, When two non-floating points are both operands in one operation, the result is upcasted to the primitive type with the highest bits which is int.

Actually, long(64 bits) is the primitive type with the highest bits to all non-floating point numbers. However, when we exclude long then the primitive type with the highest bits is int(32 bits).
public class SampleConversion{

  public static void main(String[]args){
    short s1 = 50;
    
    //valid
    int intOne = s1 + 100;
    
    //error: possible lossy conversion
    //from int to short 'cause the
    //result is int
    //short s2 = s1 + 100;
    
    //invalid
    //result is converted to int
    //byte b1 = 25;
    //short s1 = 50;
    //byte b2 = b1 + s1;
    
    //valid
    //result is long since long
    //has higher bits than int
    long longOne = 100 + 100L;
    //invalid
    //int intOne = 100 + 100L;
    
    //valid
    int intTwo = 'c' + 5;
    
    //if char and an integer literal
    //are both operands in one operation
    //and the result is gonna be stored
    //in a char variable then, the result
    //is gonna be char type
    
    //valid
    char character = 'c' + 5;
    
    //invalid
    //int intOne = 5;
    //char character = 'c' + intOne;
    
  }
}

Casting a Floating-Point to a Floating Point

Float primitive type can be upcasted to double and double can be downcasted to float.
public class SampleConversion{

  public static void main(String[]args){
    //upcasting float literal to double
    double doubleVar = 5.55f;
    System.out.println(doubleVar);
    
    //converting double literal to float
    //Just like other primitive types,
    //downcasting double to float can
    //cause data loss if the double
    //value that is gonna be casted exceeds
    //the bit range of float. Double is
    //64bits whereas float is 32bits
    float floatVar = (float)200.598333d;
    System.out.println(floatVar);
  }
}
Casting a Floating Point to a Non-Floating Point

What about casting a floating point to a non-floating point? When we cast a floating-pont to non-floating-point then the decimal places will be discarded.
Code:
public class SampleConversion
{

 public static void main(String[]args)
 {
   float floatVar = 55.5f;
   byte byteVar = (byte)floatVar;

   System.out.println("byte: " + byteVar);
 }

}
When we run this code, we will see that the decimal part of floatVar has been truncated.

Casting a Non-Floating Point to a Floating Point

Casting a non-floating point to a floating point is simply like upcasting.
public class SampleConversion
{

 public static void main(String[]args)
 {
   int intVar = 100;
   float floatVar = intVar;
   System.out.println("float: " + floatVar);
   
   long longVar = 100000L;
   double doubleVar = longVar;
   System.out.println("float: " + doubleVar);
 }

}
Floating and Non-Floating Point Conversion During Arithmetic Operation

When a floating point and a non-floating point are both operands in one operation, the result is converted to floating point.
public class SampleConversion{

  public static void main(String[]args){
    
    //error: lossy conversion from float to
    //int 'cause the result is float
    //int intOne = 20 + 30.5f;
    
    //downcast the float literal to int first
    //if you want the result to be converted
    //to int
    //int intOne = 20 + (int)30.5f;
    //System.out.println(intOne);
    
    //valid
    float floatOne = 20 + 30.5f;
    System.out.println(floatOne);
  }
}

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;



Tuesday, January 1, 2019

Java tutorial: variables, data types, instantiate class

References/Link: http://pasted.co/dd01a501

Chapters

Hello everybody! This is brainy ghosts and today we're gonna discuss variables, the assignment operator, data types, naming java identifier syntactically, Instantiate class, the print() method and some tips to avoid some beginner's error. Some of these topics must be familiar because I mentioned some of them in previous tutorials. 

Naming Java Identifier/s

Alright! Let's start at naming java identifier syntactically. Identifiers are the names of variables, methods, classes, packages and interfaces. Here are the rules for naming java identifiers: 

1.) All identifiers should begin with a letter, currency($) character or an underscore(_).

2.) Identifiers can have any variation of character after the first character.

3.) Identifiers can't use reserved keywords

4.) Identifiers are case sensitive.

I already mentioned the last two rules in previous tutorial so you must be familiar with it. Here are some example of legal and illegal identifiers:
legal:(e.g. $income, profit, _wrapper).
Illegal:(e.g. 1dude, +oneForU, 7UP).

Java Variables

Next is variables, A variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value. 

Variable is a combination of data type and an identifier. Here are some examples of declaring a variable in java.
Variable declaration without value
int myInt;

Variable declaration with value
int myInt = 10;

Variable declaration that instantiate(create) object
String myString = new String("String");
Data Type

Data type or simply type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support various types of data. Java has two groups of data type: the primitive and reference type.

Primitive Type

Primitive data types stores only one value and acquire a certain amount of memory space. Java defines 8 primitive types.

Eight Primitive Types






Reference Type

Reference or object types are any classes that can be instantiated as well as arrays. Here are some reference/object types in java.

Reference Types




Notice the first 8 references, some of them looks like primitive types but they are not. Remember java is case-sensitive so boolean is different from Boolean.

boolean vs Boolean


Arrays and more reference data types will be covered in future tutorials I'll only show some reference data types here.

You can create your own object types by creating custom classes that will be discussed in future tutorials. Remember all of the things that has been discussed here and try to take notes if possible so that you can review those information easily when those information is applied at coding. 

Applying Identifiers, types and variables to our code

create a source file in the package folder that we used in previous tutorial then name it "Beginner" then write the basic program structure that we learned.

Basic Program Structure


Alright! let's apply those information that we discussed earlier. First, let's declare a variable, to declare a variable, follow this general variable syntax:
datatype identifier;
or
datatype identifier = value;

Declaring a variable


This type of variable is called "primitive variable" because its data type is primitive. This variable is also consider as an "instance variable". 

Instance and Local Variables

Variable can be defined by its data type and location. When variable is declared in the class but not in its nested blocks like intVar variable then it is called an instance variable. When variable is declared in class nested block like constructor, method, etc. then it is called local variable. 

Local variables are only accessible in its block and the nested blocks in that block. It will be removed once the compiler is done executing the block.

Primitive and Reference Default Values

When we declare a primitive variable we see that it has no value, but when instantiate(we will learn class instantiation later) our class, the declared variable will implicitly initialize. Here are the default values of primitive and reference types.

You might ask: "What is a nested block?" To put it simply, blocks are elements in java that have pairs of braces({}). Nested block is a block in a block.

Primitive and Reference Default Values

Here are the default initial values of each primitive variables when implilicity initialized. Notice the character default value in single quotation mark, in previous tutorial, we use the double quotes in the println() method. Well, the difference is that the text or number that is in the single quotes is a character literal which is a char type while the text or number in the double quotes is String literal which is a string type.

Declaring Various Primitive Types

Okay! let's try to declare variables with different primitive data types, after that we will use the println() method to display their default initial value.

Declaring Additional Primitive Variables

All we need to do now is to write println() method in the main and put the variable name in the parentheses. Let's give it a try! And compile our code after.

println() method to print variable value

"non-static variable to static context" error 

There's an error when we compile our code, the compiler said "non-static variable varBoolean cannot be referenced from a static context." this means we cannot reference non-static instance variable directly to a static context.

Note: "cannot be referenced" means cannot be used. It means that, We can't put a non-static variable in a static context. We can think of "static context" as context that is related to static elements like methods, fields, etc.

"non-static variable to static context" error 


But why? that's because non-static instance variable need to obviously exist in order to use, in contrast to static context because static context already exist.

Remember this, non-static instance variables like these variables and other non-static context in the class belongs to its instance whereas static variables and other static context belongs to the class itself. 

There are two ways to fix this error:

First, we declare each variable static, the solution is not good in this case because it's tedious to do(Note: too much use of static context is not a good practice). The second solution is to create a class instance in the main method.

We will use the second solution because it's easier to type, we don't need to type static keyword in each variable and it is an efficient solution to our problem. To create or instantiate a class we need to declare a class first. Declaring a class is just like declaring a variable that we did earlier, just follow this general class declaration syntax: class-name identifier-name;

Declaring a class(variable)
(Note: Java is case-sensitive so, "Beginner" with capital first letter is the class-name and "beginner" with small first letter is the identifier-name)

After that use the println() method and reference our reference variable to it.

println() method

"might not have been initialized" error

When we compile this code we will receive another error. The error is "variable (class-name) might not have been initialized." we encounter this error because in java, local variables should be initialized explicitly, in other words we are the one that will assign a value to local variables.

"might not have been initialized" error

line number error indicator

Notice the number on the error "(filename).java:(number)" it means that the error in the source file
(filename).java is on the line (number).(Note: If you want to clear all the messages on the console type the command "cls" and execute the command)

line number error indicator

Brief Introduction to Java errors and warnings

Java compiler throws an error and a warning, when the compiler encounter an error our code won't compile  but when the compiler throws a warning, the compiler will still compile our code but that doesn't mean that we will just ignore the warning that the compiler throws.

Java throws a warning because of a poor and inefficient syntax writing or using java obsolete features, It means that our syntax is correct but it is written poorly. We will learn  more about compiler warnings in future tutorials.

Assigning values to our reference variable

To assign a new value to our reference variable we will use the assignment operator, then we will use the new keyword, new keyword allocates memory in heap memory, then type the class name and put an empty parentheses then semi-colon.

Class Instantiation

Let's examine this syntax. First is the data type which is the class-name then the variable name then the assignment operator, assignment operator("=") assigns the value on its right to the operand on its left. It means that the right side operand which is the new class-name(); will be assigned to the left side which is the (class-name identifier), the class-name with a parentheses after the new keyword is called the class constructor. Constructor is beyond to be covered in this tutorial and will be explained in future tutorials so just keep the information in your mind for now.

We can generally call the variable "Beginner beginner;" in the main() a reference local variable, Since the variable data type is a class type and it's a local variable.

Brief Explanation of Heap and Stack Memory

You might be wondering: "what is heap?", java stores values to the heap and stack memory. Heap memory stores objects and the instance variables that the object owns. Stack memory stores method calls and local variables.


Another way of instantiating a class or assigning a value to a variable

There's another way to instantiate a class, the first one that we did was a shortcut, this is the other way to instantiate a class, write a declaration statement, then on the next line type the reference variable identifier first then the assignment operator then the next syntax is the same as the first class declaration syntax.

syntax: class identifier;
             identifier = new Contructor();

These syntaxes that we used are applicable to other types of variables.

Alternative Way to Assign a Value to a Variable

Displaying instance variable values on the console

Now, let's display the initial value of these variable on the console using the println() method. To access the instance variable of the object on this reference variable type this in the println() parentheses, (syntax: class-name.instance-variable-name;), 

Assigning instance variable to println()

We will display multiple values on the console so will use multiple println() method.

Using Multiple println() to display instance variables values

You might notice that the value in the println() parentheses is not enclosed in double quotes but in previous tutorial we see that the println() message is in the double quotes. Well, the text or number that is in the double quotes is a string literal which is an acceptable value in println().

this time we want to display the value of variables so we use the variable name as a value to println() then println() will get the value of that variable and display that value on the console. Also, print() and println() method accept lots of data types as values, you will see the print() method in a moment. 

When we compile and run the code we will see the default values of these variable.

Multiple println() Printing Multiple Values

Introducing print() method

Now, the values are displayed on the console but the message is not very informative so we will add some labels to every value to make it more informative, In this situation we can use the print() method,the difference between print() and println() is the newline that is being added after the message. print() method display a message but it doesn't add a newline while println() method display a message and add a newline at the end of the message.

Let's put the print() method at the top of each println() method.

print() method

After that, let's compile and execute our code and as you can see the console message is now more informative.

Result When print() Method Added To Our Code

Understanding the difference between print() and println() method

If you can't still understand the difference of print() and println() method try this, remove all the print() method then change the println() to print().

Changing Some Portion of Our Code


then run and compile the code. As you can see the values are all on the same line that's because the print() method doesn't add a newline at the end of the message.

Effect of print() method on the console

We will learn more about the newline in the escape sequence topic. After that return the code structure.

Our Code Original Form

Windows cmd Up and Down Command Shortcut

Let's run our code again, and by the way, if you're using cmd like me you can use the Up and Down key to reuse the command that you already typed as long as the cmd is still active, if you close the cmd, the Up and Down key won't work until you don't type another command and execute it. 

char default value

When we run our code you might notice that all of the primitive types have default values except for char type. Well, we can't see the char default value because its default value is a null character, the char default value '\u0000' represent a null character, null means nothing so you know the logic. 

Difference between char null value and reference type null value

Don't be confused with the null default value of an object and the null character, They represent nothing but their usage is different, the null can be used as an object value while the null character can be used as a char value.

If you want more clarification let's try it into our code remove all the code in the main except for the class variable declaration.

remove codes in main() except class variable declaration


If you're text editor that can only undo once like notepad, it's better to cut the code by pressing the ctrl+x and paste it back again so you don't need to type it again, Atom can undo multiple times so it's not necessary to do that.

Let's assign a null value to this variable then put it to println().

Assigning null value to reference variable

Then, run and compile the code, as you can see the value of this variable is null.

null value

Now try to put the default character value then run and compile the code.

assigning null character value to reference variable 

As you can see there is an error, this error means that this value the null character is not compatible to this data type.

"incompatible types" error

Same goes when we assign the null value to a char variable.

assigning null value to char type


Let's undo the changes that we made.

Our Code Original Form


Some tips on how to avoid certain beginner's error

And before I end this tutorial I'll give you some tips on how to avoid certain beginner's error for example: 

1.) In this type of class instantiation(line 17 and 18) we used two lines, when our code execute, it will declare this variable first then create an instance of class and point it to "beginner" reference. When you try to switch these two codes you will receive an error. That error means that you were trying instantiate a class to the undefined identifier, in other words the compiler couldn't instantiate the class because the variable that we put on the left side of the assignment operator didn't exist or declared.

2.) Next tip is the arrangement of your codes for example, when we execute our code the main method execute from the first line to the bottom of its block that's why the printed message on the console is arrange like that, if you try to switch the print() and println() you can see that the printed message arrangement changes too. As you can see code fragments arrangement are also important so be careful when arranging the codes in your source file, you might get an error or unexpected result.

The var Type Name

The var was introduced in java10 and its purpose is to infer types of local variables by looking at the actual type that is assigned to the variable. The use of var is limited to local variables like in for and for-each loops parentheses.
public class SampleClass{
  
  //invalid: can't use var
  //keyword as type of
  //instance variable
  //var myVar = false;
  
  void meth1(){
    //var can be used in this
    //block
    var str = "String";
    
    //var can be used in for loop
    //parentheses
    for(var i = 0; i < 3;i++)
      System.out.println(str);
  }
  
  //invalid: var can't be used as
  //type of method and constructor
  //parameter
  //void meth2(var param){}
  
  public static void main(String[]args){
    //var can be used here 'cause main()
    //is a method like meth1()
    var chararacter = 'c';
    
    //var can't be used as type of an array
    //var[] myStr = new String[]{"A","B"};
    
    String[] str = new String[]{"A","B"};
	
    //var can be used in for-each loop
    //parentheses
    for(var s : str)
       System.out.println(s);
  }
}
var is a reserved type name, not a keyword, which means that existing code that uses var as a variable, method, or package name is not affected. However, code that uses var as a class or interface name is affected and the class or interface needs to be renamed.
public class SampleClass{
  
  //valid method name
  static void var(String s){
    
    //valid variable name
    var var = s;
    System.out.println(var);
  }
  
  public static void main(String[] args){
  
    SampleClass.var("Hello!");
  }
}

//compile-time error
/*
class var{
}
*/