Friday, February 1, 2019

Java Tutorial: Operators

Chapters

Hello everybody! this is brainy ghosts and today we're gonna discuss the java operators. Java has several operator groups, operators are one of the essential part of every programming language for obvious reasons like computing,comparing,etc.

Assignment Operator


Let's create a java file in our workspace folder, then name it "JavaOperators", then write the basic code structure. 

Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
  
  
  
 }
 
}
Alright! let's start with the assignment operator(=), you probably know this operator since I explained it in previous tutorials. This operator assigns the value on its right to the operand on its left.
public class JavaOperators
{
 
 public static void main(String[]args)
 {
  
   int intVar = 100;
  
 }
 
}
To understand that definition let's examine this code elaborately. The variables or numbers from the left and right of the operator are called operands. So, assignment operator assigns the operand value from the right to the left operand. From that explanation we can assure that the assignment operator evaluates from right to left. Operators have different ways of evaluation, some evaluates from right to left and vice versa, we will encounter some operators that evaluate from left to right.

Arithmetic Operators

Let's move on to arithmetic operators, Arithmetic operators are easy to understand because its operation and operator symbols are mostly like in mathematics, all arithmetic operators evaluate from left to right. Let's start at the additive(+) operator or the plus sign, This operator adds operands like literals and variables. Note: Unlike the "+" operator, other arithmetic operators like "-","*","/" and "%" doesn't work in String.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
    String str = "Hello";
    String str2 = "Java!";
    int intVar = 100 + 1;
    String str3 = str + " " + str2;
    System.out.println(intVar);
    System.out.println(str3);
 }
 
}
Next is the subraction(-) operator, This operator substracts operands.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = 100 - 1;
   System.out.println(intVar);
 }
 
}
Next is the multiplication(*) operator which multiply operands.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = 100 * 2;
   System.out.println(intVar);
 }
 
}
Next is the division(/) operator which divides operands.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = 100 / 2;
   System.out.println(intVar);
 }
 
}
Next is the modulus(%) or the remainder operator, This operator divides operands then return a remainder as a result of the operation.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = 7 % 5;
   System.out.println(intVar);
 }
 
}
The result is 2, because 7/5 = 1 remainder 2. Also, when the dividend(left) is less than divisor(right) the operator will return the dividend as a result. try 5 % 7 and the result is 5.

Unary Operators


unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Unary Plus(+) Operator

Let's start with the unary plus(+), This operator is rarely used because this operator indicates if the operand or expression is a positive value and since omitting this operator will automatically makes the operand positive, programmers tend to omit the plus unary to save time and reduce ambiguity when writing a code.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = +7 + +7;
   System.out.println(intVar);
 }
 
}
In this example, we can see that "+" operator can be a unary plus or an additive operator.

Unary Minus(-) Operator

Next is the unary minus(-) which negates an operand or expression, The usage of this operator is similar to unary plus.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intVar = -7 - +7;
   System.out.println(intVar);
 }
 
}

In this example, we see that "-" can be a unary minus or a subtraction operator. To reduce the ambiguity of unary plus and minus, it is better to enclose the operands in parentheses.

Code: int intVar = (-7) - (+7);

Logical Complement(!) Operator

Next is the logical complement operator(!), this operator is used at boolean value and inverts it.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   boolean boolVar = !true;
   System.out.println(boolVar);
 }
 
}
Increment(++) and Decrement(--) Operator

Next is the increment(++) and decrement(--) operator. These two operators can be applied before or after the operand, The effect of the operator on the operand depends on its position. Let's define their usage first and we will use their postfix form where the operator position is at the end of the operand. The increment operator increment its operand by one and decrement operator decrement its operand by one. Now, that we know their general usage let's code their prefix and postfix positioning. let's start with postfix position.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   System.out.println(intOne);
   System.out.println(intTwo);
   intOne++;
   intTwo--;
   System.out.println(intOne);
   System.out.println(intTwo);
 }
 
}

In this example, we see the postfix position of increment and decrement operator. Let's try prefix next.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   System.out.println(intOne);
   System.out.println(intTwo);
   ++intOne;
   --intTwo;
   System.out.println(intOne);
   System.out.println(intTwo);
 }
 
}
When we compile and run this example, we see that the result of this code and the code before are the same. So, what's the difference between prefix and postfix? Well, in simple cases like this we can use the prefix and postfix form interchangeably but in complex cases like in multihreading or complex loops, it is essential to know their differences. Let's do an example to unveil their differences.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = ++intOne;
   System.out.println("pre: " + intTwo);
   intOne = 1; //resets intOne to 1
   intTwo = intOne++;
   System.out.println("post: " + intTwo);
 }
 
}

In this example, "++" prefix increments intOne by 1 before assigning intOne value to intTwo, that's why the first println result is 2. Next, "++" postfix assigns the value of intOne to intTwo before incrementing intOne value by 1. That's why the second println result is 1. The explanation here can work with "--".

Equality and Relational Operators


The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

"equal to"(==) operator

Let's start with the "equal to"(==) operator, this operator compare two operands, returns true if two operands are equal, otherwise, returns false.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   boolean bool = intOne == intTwo;
   System.out.println("Is intOne equals to intTwo? " + bool);
 }
 
}
In this example, the operator returns true because intOne and intTwo values are equal. When "==" operator is used with reference variables, then "==" operator will return true if the reference address of both variables are equal, otherwise, returns false.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   String strOne = "String";
   String strTwo = new String("String");
   System.out.println("Is intOne equals to intTwo? "
                      + (strOne == strTwo));
 }
 
}
In this example, strOne and strTwo have the same value but the result is false, that's because strOne reference is different from strTwo reference. We will learn how strOne and strTwo have different reference in future tutorials. To compare String values, use the equals() method.

Code: System.out.println("Is intOne equals to intTwo? " + strOne.equals(strTwo));

"not equal to"(!=) operator

Next is "not equal to"(!=) operator, this operator is the opposite of "equal to" operator. This operator returns true if two operands that being compared are not equal, otherwise, returns false.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   boolean bool = intOne != intTwo;
   System.out.println("Is intOne not equals to intTwo? " + bool);
 }
 
}
Greater than(>) and less than(<) operators

Next is the greater than(>) operator, you saw this operator once in your math class, This operator returns true if the left operand is greater than the right operand, otherwise, returns false.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 2;
   int intTwo = 1;
   boolean bool = intOne > intTwo;
   System.out.println("Is intOne greater than intTwo? " + bool);
 }
 
}

Next is the less than(<) operator, this operator is the opposite of greater than.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 2;
   int intTwo = 1;
   boolean bool = intOne < intTwo;
   System.out.println("Is intOne less than intTwo? " + bool);
 }
 
}

greater than or equal to(>=) and less than or equal to(<=) operators

Next is the "greater than or equal to"(>=) and "less than or equal to"(<=) operators, >= operator returns true if the left operand is greater than or equal to the right operand, otherwise, returns false. <= operator is the opposite of >= operator.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   System.out.println("Is intOne greater than or equal to"
              +" intTwo? "+ (intOne >= intTwo));
   System.out.println("Is intOne less than or equal to"
              +" intTwo? "+ (intOne <= intTwo));
   System.out.println("Increment intOne");
   intOne++;
   System.out.println("Is intOne greater than or equal to"
              +" intTwo? " + (intOne >= intTwo));
   System.out.println("Is intOne less than or equal to"
              +" intTwo? " + (intOne <= intTwo));
 }
 
}

"=" operator vs "==" operator

Remember that "=" operator and "==" operator are different. "=" operator is the asssignment operator that assigns a value whereas "==" operator is the equal to operator that compare two operands and returns a boolean value. Some beginners get confuse with this two operators.

Conditional Operators


Conditional-AND(&&) and Conditional-OR(||) operators

Next is the conditional operators. "&&" and "||" operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 1;
   int intTwo = 1;
   boolean bool = (intOne == 1 && intTwo == 1);
   System.out.println("is intOne and intTwo equals to 1? "
                      + bool); //1st println
   intOne = 2;
   intTwo = 1;
   bool = (intOne == 1 && intTwo == 1);
   System.out.println("is intOne and intTwo equals to 1? "
                      + bool); //2nd println
   intOne = 1;
   intTwo = 1;
   bool = (intOne == 1 || intTwo == 1);
   System.out.println("is intOne or intTwo equals to 1? "
                      + bool); //3rd println
   intOne = 2;
   intTwo = 1;
   bool = (intOne == 1 || intTwo == 1);
   System.out.println("is intOne or intTwo equals to 1? "
                      + bool); //4th println
   intOne = 2;
   intTwo = 2;
   bool = (intOne == 1 || intTwo == 1);
   System.out.println("is intOne or intTwo equals to 1? "
                      + bool); //5th println
 }
 
}
"&&" checks the left and right conditions or operands, if you will. When both conditions are true then the result is true otherwise, the result is false.On the first println(), the result is true because intOne is equal to 1 and intTwo is equal to 1. If the left condition is true then "&&" operator checks the right condition next, if the right condition is true then the overall result is true, otherwise, false. On the second println() the result is false because intOne is not equal to 1. In this case, the left condition is false, therefore "&&" operator doesn't check the right condition and return false as a result. Thus, exhibiting "short-circuiting" behavior.

Next, "||" operator checks the left and right condition, when both or just one condition is true then the result is true, if both conditions are false then the result is false. On the third println() the result is true because both conditions are true, In this case, the left condition is true, therefore, "||" doesn't need to check the right condition. Thus, exhibiting "short-circuiting" behavior. On the fourth println(), the result is still true because, intTwo is equal to 1, In this case, though, the left condition is false, therefore, "||" checks the second condition and since one of the condition is true, the result is still true. The 5th println() result is false because both conditions are false.

Ternary(?:) Operator

ternary(?:) operator can be thought of if-then-else shorthand, if-then-else is part of the control flow statement topic so I won't cover if-then-else but I will demonstrate the ternary operator so you will have an idea on how if-then-else works.
Ternary operator general form: condition ? value1 : value2;
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = 2;
   int intTwo = 1;
   int intThree = (intOne > intTwo) ? intOne : intTwo;
   System.out.println(intThree);
 }
 
}
In this example, if the condition(intOne > intTwo) is true then value1 will be returned to intThree, if the condition is false, then value2 will be returned to intThree. That's why the result is 2 because intOne is greater than intTwo and in our ternary operation intOne is value1.By the way, The parentheses in condition are optional.

Type Comparison Operator


The type comparison operator or instanceof compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. instanceof is used in typecasting objects.
General Form: object instanceof object-type;
Note: Since java14, instanceof now throws a compilation error instead of runtime error when the two operands are not compatible with each other.
Code:
interface I{}

class A{}

class B extends A implements I{}


public class JavaOperators
{
 
 public static void main(String[]args)
 {
   A a = new A();
   B b = new B();
   
   System.out.println("a instance of B? "
              + (a instanceof B)); //1st println()
   System.out.println("b instance of A? "
              + (b instanceof A)); //2nd println()
   System.out.println("a instance of I? "
              + (a instanceof I)); //3rd println()
   System.out.println("b instance of I? " 
              + (b instanceof I)); //4th println()
   
 }
 
}

In this example, we created an interface and two classes, then we instantiated those classes and compare if they are an instance of an object. On the first println we compare a to class B, and the result is false because class A is a parent class of class B. On the second println() the result is true because B is a subclass of A. On the third println() the result is false class A is not related to interface I. On the fourth println() the result is true because B implemented interface I. Remember that instanceof works with objects and doesn't work with primitive types.

If we reference a null value to a reference variable and use it in instanceof, instanceof will return false.
Code:
interface I{}

class A{}

class B extends A implements I{}


public class JavaOperators
{
 
 public static void main(String[]args)
 {
   B b = null;
   
   System.out.println("b instance of A? " + (b instanceof A));
   
 }
 
}
Don't be overwhelmed by those new keywords and syntax in this example, we will tackle those as we progress further. Just focus on the function of instanceof for now.

Bitwise and Shift Operators


Next is bitwise and bit shift operators. bitwise and bit shift operators are used to manipulate data bits. These operators are less commonly used.

Unary bitwise complement(~) operator

Let's start with the "unary bitwise complement"(~) also called binary ones complement operator, this operator inverts a bit pattern, just like one's complement, let's try it! For the sake of simplicity we will use the byte data type for some bitwise example so we can easily understand the operators that will be discussed here. Unary bitwise can be categorized in unary operators group or in bitwise and shift operator, I just put it in bitwise and shift operator because I think this operator is more related in this category.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   int intOne = ~1;
   System.out.println(intOne);
 }
 
}
In this example, the result is -2. To check if the result is correct open windows calculator if you're using windows go to programmer mode, click the Dword radio box, click the initial number(1) and click the "Not" button.

When you type 1 pay attention to the bits on calculator then click "Not" button. You see the zeroes have been flipped to ones and ones have been flipped to zeroes. The result is negative because we're dealing with signed bits when using "~" operator.

Bitwise AND(&) operator

Next is the bitwise AND(&), this operator evaluates each bit of two operands at the same time. If two operands bit is 1 then the result is one, then all other cases result to 0. Let's declare another byte variables let's try the values 50 and 25, then use the bitwise AND and compile and run.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   byte byteTwo = 25;
   int intThree = byteOne & byteTwo;
   System.out.println(intThree);
 }
 
}
I used int as intThree data type because the result of the "&" and other bitwise and shift operators are treated as int. If you change intThree data type to byte you will encounter a conversion error. The result of this example is 16. To check if the result is correct laid out their binaries like this:


In this illustration, we see when both operands' bits are 1, the result is 1. When one of the operand bits is 0 then the result is 0.

If you want more proof that our result is correct, open windows calculator if you're using windows, then click the byte radio button, type the first operand, click the "And" button then type the second operand and click "=" button. You see the result is 16.

Bitwise Inclusive OR(|) Operator

Next is the inclusive OR(|) or OR for short. This operator is like the AND but its process is different. If the bits of either operand are 1, the result is 1. all other cases result to 0.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   byte byteTwo = 25;
   int intThree = byteOne | byteTwo;
   System.out.println(intThree);
 }
 
}

The result of this example is 59. To compute the result manually try to laid out their binary like this:


In this illustration, we see that if one of the operand bit is 1 or both operands bit are 1 then the result is 1, if both operands bit are 0 then the result is 0.

If you want more proof that our result is correct, open windows calculator if you're using windows, then click the byte radio button, type the first operand, click the "Or" button then type the second operand and click "=" button. You see the result is 59.

Bitwise Exclusive OR(^) Operator

Next is the exclusive OR(^) or XOR for short. This operator is just like inclusive OR but with different rules. If only one of the operand bits is 1 the result is 1, All other cases result to 0.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   byte byteTwo = 25;
   int intThree = byteOne ^ byteTwo;
   System.out.println(intThree);
 }
 
}

The result of this example is 43. To compute the result manually try to laid out their binary like this:


In this illustration, we see that when one of the operand bit is 1 then the result is 1, when both operands bit are 1 or 0 then the result is 0.
If you want more proof that our result is correct, open windows calculator if you're using windows, then click the byte radio button, type the first operand, click the "Xor" button then type the second operand and click "=" button. You see the result is 43.

Signed Left Shift(<<) Operator

Signed left shift(<<) shifts bits to the left depending on the specified number of shifts, for example, let's try to shift 50 by 2 shifts. The left operand is the one that will be shifted and the right operand is the number of shift
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   int intTwo = byteOne << 2;
   System.out.println(intTwo);
 }
 
}
open the windows calculator then go to programmer mode then type 50 with dec radio button selected then select Dword then click the Lsh button "Lsh" is the left shift operator then type the number of shift you want in our case we need 2 shifts. As you can see the result is 200 which is the same result on the console, but why? When we do the signed left shift it will add zeroes to the rightmost bit this bit is also called Least Significant Bit or LSB for short. Here are illustrations that explains how signed left shift works.


when we shift bits, the leftmost bit also called Most Significant Bit or MSB for short will be lost once they are shifted out from position 31 if int and position 63 if long. See the number on the bottom of bits in the calculator? that's the position that I'm talking about. We can see that the bit index in the calculator starts at 0.




Let's do another example, let's try -50 then left shift it to 8.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = -50;
   int intTwo = byteOne << 8;
   System.out.println(intTwo);
 }
 
}
And the result is -12800. Here is an illustration that explains how we got the result.



If you want to check the result on the calculator: go to programmer mode then type 50 with dec radio button selected then click the "+" with "-" button also called the negate button then select Dword then click the Lsh button then type the number of shifts you want in our case we need 8 shifts.

Signed Right Shift(>>) Operator

Next is the signed right shift(>>), this operator shifts bits to the right. As you might have notice this operator has similar procedure to signed left shift but their differences are essential, One of their difference is obvious signed left shift shifts bits from right to left while this operator shifts bits from left to right.

Another difference is the signed right shift is sign dependent. You might asked "how signed right shift is sign dependent? you can't put a positive or negative sign to a binary.", Well, I already discussed how binary represents sign numbers I'll just add some additional information here, Open the window's calculator and select the byte radio button, type 127 and notice the binary.


As you can see the last bit position of byte which is position 7 is zero.

next type 128, reset the values on the calculator first then set the radio button to word because we can't type 128 when we're in the byte range, so, click the Word radio button, type 128 then switch back to byte.


Notice that the positive 128 became negative 128 and in the last bit position of byte which is position 7 is now 1, now, did you get what i'm trying to say? well, if not let me tell you, When the last bit position is zero it means that the binary is representing a positive number and when the last bit position is 1 it means that the binary is representing a negative number, this is only applicable on signed type like byte and all signed type in java, this is not applicable to unsigned type like char because unsigned type only represents positive numbers.

Why do we need to know this? Well, signed right shift depends on the last bit position when shifting bits,for example, let's try -50 then shift it to 2 then compile and run.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = -50;
   int intTwo = byteOne >> 2;
   System.out.println(intTwo);
 }
 
}
In this example, the result is -13. Here are illustrations that show how signed right shift works with negative numbers.



In these Illustrations, we see that the two bits from the right side has been lost and two 1's bits were added to the left side.

You can check our result by using windows calculator: go to programmer mode then type 50 with dec radio button selected then click the "+" with "-" button also called the negate button then select byte radio button then click the Rsh button, "Rsh" is the right shift in the calculator then type the number of shifts you want in our case we need 2 shifts.

Now let's try positive 50 then shift it to 2.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   int intTwo = byteOne >> 2;
   System.out.println(intTwo);
 }
 
}
In this example, the result is 12. Here are illustrations that show how signed right shift works with positive numbers



In these Illustrations, we see that the two bits from the right side has been lost and two 0's bits were added to the left side.

Unsigned Right Shift(>>>) Operator

Next is the unsigned right shift(>>>), This operator shifts bits to the right just like signed right shift their difference is that this operator is not sign dependent, it means that this operator will only add zeroes to the right no matter what the value of the Most Significant bit, whereas signed right shift is sign dependent. Let's try an example.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = -50;
   int intTwo = byteOne >>> 2;
   System.out.println(intTwo);
 }
 
}

In this example, the result is 1073741811. How's that happened? Here are illustrations that show how unsigned right shift operator works.



In these illustrations, we see that the bits of -50 on the right side was gone and two zeroes was added on the left side. That's why the result is 1073741811. This operator sometimes doesn't work well with byte and short because the result of >>> operator is treated as int, if we downcast the result of this operator to byte, we might get an unexpected result. But why? You can check my blog about typecasting primitive types and go to the section: "Downcasting a value that exceeds destination's capacity"

Compound Assignment Operators


Next is the compound assignment operators, these operators are shorthand of an operation and assignment. Let's try the "+=" operator, this operator adds the left operand to the right operand and assigns the result to left operand, let's try an example.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne = 50;
   byteOne += 50;
   //byteOne = byteOne + 50; //equivalent equation to: byteOne += 50;
   System.out.println(byteOne);
 }
 
}

In this example, the result is 100. Make sure to initialize the variable first before using the compound assignment, if you don't, you will encounter an error.
Code:
public class JavaOperators
{
 
 public static void main(String[]args)
 {
   byte byteOne += 50; //error
   System.out.println(byteOne);
 }
 
}

There are other shorthands as you see from the figure earlier and their functions are similar to this "+=" operator that I demonstrated, I think these operators are fairly easy so I'll leave it to you to explore and try.

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.


View code with code highlight



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

View code with code highlight



Casting a Floating-Point to a Floating Point

Float primitive type can be upcasted to double and double can be downcasted to float.

View code with code highlight



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.
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.


View code with code highlight


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.


View code with code highlight


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:


View code with code highlight


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


View code with code highlight


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.


View code with code highlight


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.


View code with code highlight


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.


View code with code highlight


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;