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{
}
*/

No comments:

Post a Comment