Categories
Dart

Dart Instance Variable vs Reference Variable

Instance variables and reference variables are very useful concepts of object oriented programming structure to deeply understand the class and object concept.

So let’s get started with instance variable.

What is Instance Variable ?

Instance variable is a variable declared inside the class but outside any function(method) or any block of code.

Basically, instance variables are the properties of class. every object of a particular class has  individual copy of all instance variables.

Instance variables are created with object creation and gets destroyed with object destruction.

The scope of instance variables differs from object to object of particular class. Which means each copy of instance variables belongs to particular object of that class.

For ex :

class Avengers{
  int rank;
  String Name;
  Avengers(int avengerRank,String avengerName){
    rank=avengerRank;
    Name=avengerName;
    print("Rank of " + Name + " is " + rank.toString());
  }
}

void main() {
  Avengers marvel=new Avengers(1,"Captain Marvel");	
  Avengers thor=new Avengers(2,"Almighty Thor");
  Avengers hulk=new Avengers(3,"The Hulk");
}

Output :

Rank of Captain Marvel is 1
Rank of Almighty Thor is 2
Rank of The Hulk is 3

In above example, there are 3 objects Captain Marvel, Thor and Hulk of a particular class Avengers. Marvel, Thor and Hulk will get their separate copy of instance variables (i.e., Name and Rank) generated at the time of object creation. It is not required to create or declare properties for each object of class.

The default values for uninitialized variables of any data type in dart is null. Because everything else in dart is an object.

What is Reference Variable?

The reference variable reference to or point to the memory storage allocated for particular object created.

In simple language, reference variable is the alias or identifier for the declared objects.

For ex :

class Test{
}
void main(){
int x;	// x point to some random location like 0x02304 for object of type(class) int variable declared.

String y;	// y point to some random location like 0x089540 for object of type(class) String variable declared.

Test T1=new Test();	// test points to some random like 0x02560 for  object of type(class) Test declared.
}

In above example, x, y and T1 are different variables pointing to their respective objects stored in the memory.

They are just references of the objects to easily access them.

At a time, a reference variable can refer or point to the single object of the class. But, multiple reference variable can refer or point to same object.

For ex :

class Books{
}

void main(){
/* New Object of Class Book is created and referenced by the Reference variable B1.*/
	Book B1=new Book();	

/* Reference Variable B2 is created and ultimately refers to the same object referred by B1.*/
	Book B2=B1;	

/* New Object of Class Book is created and referenced by the Reference variable B3. */
	Book B3=new Book();	

/* Reference Variable B3 is created and ultimately refers to the same object referred by B2. */
	B3=B2;
}

In above example, the first statement will create a new object and will get some random storage location in memory. Let say, 0x0001 which is referenced by Reference variable B1.

The second statement will now have another reference variable B2 which will refer to the same object which is referenced by Reference variable B1 i.e., location 0x0001.

The third statement will create a new object and will get some random storage location in memory. Let say, 0x0003 which is referenced by Reference variable B3.

In 4th Statement reference variable B3 will now refer to the same object which is referenced by Reference variable B2 i.e., location 0x0001.

So now we have 2 Objects of class Book and 3 Reference Variables B1, B2 and B3 all pointing to the first object only. While, second object is not referenced by any reference variable.​

So this is the brief explanatory section for instance variable and reference variable.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Constructors

Dart constructor is an interesting topic which is used to initialise the objects of the class.

What is Constructor?

Basically, constructors are the special type of methods with the same name as the class but with no return type.

Constructors are used to initialise the data members(properties and behaviours) of an object at the time of object creation.

Syntax

// ConstuctorName must be same as the class name
ConstuctorName(){               
}

Types of Constructors

There are three types of constructors available in dart language.

  • Default Constructor
  • Parameterised Constructor
  • Named Constructor

Default Constructor

Constructor with no arguments is known as Default Constructor.

Each class can have only one Default Constructor.

If user don’t create the Default Constructor for particular class then compiler creates a Default (No-argument) Constructor for the class.

For ex :

class Television
{
  Television()
  {
     print("Television On!");
  }
}

void main()
{
/* new Keyword is not necessary with Dart 2 Release.*/
/* Round braces after Class Name  (i.e., Television) will Initialise the object and
 Call the Default Constructor whether you have created it or not.*/

  Television T1 = new Television();
}

Output :

Television On!

Parameterised Constructor

Constructors with one or more parameters (arguments) are known as parameterised constructor.

In dart, class can have only one parameterised constructor. But, can have more than one named constructor.

Syntax :

constructorName(parameterList);

For ex :

class Television
{
    Television(int a, int b)
    {
       print("Sum of 2 Numbers is " +(a+b).toString());
    }
}
void main()
{
  Television T1=new Television(5,4);
}

Output :

Sum of 2 Numbers is 9.

Named Constructor

In dart, class can’t have multiple constructors. A class can have either 1 default constructor or 1 parameterised constructor. To fulfil your multiple constructor requirement dart has a concept called Named Constructor.

Named Constructors are defined as ClassName following with “.” following VariableConstructorName.

Syntax :

ClassName.ConstructorName(parameterList){
}

For ex :

class Television
{
    Television(int a, int b)
    {
        print("Sum is : ${a+b}");
    }
    Television.Channel(String a, String b)
    {
        print("Channel 1 is " + a +" And Channel 2 is "+b);
    }
    /* Named Constructors can be defined as a private constructor by starting the constructor name with _ */
    Television._Channel(String a, String b,int c)
    {
        print("Channel 1 is " + a +" And Channel 2 is "+ b + " And Channel Rank is " + c.toString());
    }
}

void main()
{
    Television T1 = new Television(5, 4);
    Television T2 = new Television.Channel("Movie TV", "Sports TV");
    Television T3 = new Television._Channel("Movie TV", "Sports TV", 5);
}

Output :

Sum is : 9
Channel 1 is Movie TV And Channel 2 is Sports TV
Channel 1 is Movie TV And Channel 2 is Sports TV And Channel Rank is 5

In this way, constructors are useful to initialise the class members or initialise the resources which you want at the time of object creation.

It would be better to understand another topic “This Keyword” at this Moment to better enhance the use of constructors.

This Keyword

This keyword is used to refer the current instance(Object) or methods of the class.

General purpose of this keyword is to differentiate the parameters passes in method and instance variables if they have same name.

For ex :

class Actors
{
    String Name;
    int Age;
    Actors(String Name, int Age)
    {
        Name = Name;
        Age = Age;
    }
}
void main()
{
    Actors actor = new Actors("Tom Cruise", 40);
    print(actor.Name);
    print(actor.Age);
}

Output :

null
null

In above case, Name and Age will generate ambiguity for compiler. As instance variables and parameters passed in constructors have the same name.

So the values assigned in constructor to the Name and Age will not be assigned to the instance variable’s Age and Name.

In that case This keyword takes place to remove this kind of ambiguities introduced for compiler.

Let me explain this concept by correcting above example.

class Actors{
	String Name;
	int Age;
	Actors(String Name,int Age){
		this.Name=Name;
		this.Age=Age;
		// this.Test(); is same as the Test(); Function Call
		this.Test();
		
	}
	void Test(){
		print(“This Keyword”);
	}
}
void main(){
	Actors actor=new Actors("Tom Cruise",40);
  	print(actor.Name);
print(actor.Age);
}

Output :

Tom Cruise
40
This Keyword

Here you can see we have used this.Name and this.Age is used for referencing the instance variables of the class.

Here we also have made function call for Test() method in constructor using this keyword.

So “this keyword” is helpful to referencing the instance variables or methods of the class.

You can have command over the constructor and this keyword by practicing conventional programs.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Classes and Object

Almost every OOP languages uses Classes and Objects concepts to organise program code or Syntax Structure in a way that is helpful to achieve smoother code structure, better flow control, code reusability, more efficiency , testability and many more features.

Since dart is also an object oriented programming language. Therefore it’s not an exception to class-object code structure.

Classes and Objects are Interconnected. They can’t be distinguished from each other. So, we’ll discuss class and objects relatively to each other.

Class

A class is a blueprint or template used to construct the objects. A class consists of different variables, constructors, objects and methods. It can have many properties and methods that are common to the objects of that particular class.

A class is a Structure which tells us that what will be the behaviour of the object and what things will an object contain?

Objects

Object is an entity which represents state and behaviour.

Object is the instance of the class. In simple words, object is the specific type or kind of the class.

Let’s understand the class and objects terminologies by our day-to-day examples.

For ex :

If Car is a Class then what can be the objects of the class Car ?

So, we can think like, the properties and methods(behaviours) satisfied by any entity can be the objects of the class.

So, what can be the states of a Car Class ?

A car can have color, Wheels, Fuel Level, Brake , Accelarator etc.

Now, what can be the Behaviour for a Car class?

A car can run at high speed, it can horn, it can turn right or left, reverse turn etc. are the behaviours of that class.

So, the entities which has state(properties) and behaviour of the Car class are the objects of the class.

So, Maruti 800, Suzuki Swift, Chevrolet cruze, Audi A6, Buggatti Veyron, Aston Martin and many more are the examples of the Car class.

Let’s take another example to understand more briefly the meaning of the objects and the class.

Let’s say If Person is a class then what can be the objects for the person class.

Now, to understand what can be the objects of a Person class we can think of the properties and behaviours of a Person.

Properties of a Person are

2 Legs, 2 Eyes, 2 Hands, 2 Ears, a Nose, a Mouth, a Breakable Heart, Many More Bones and also you can think other human properties as well to understand this class and object concept.

Behaviours of a Person are

A person can eat, think, drink, speak, play, run and many more behaviours you can imagine of.

So, Now the elements or entities in the universe who can fulfill the properties and behaviours of the person class are the objects of the Person class.

You and I are also satisfy the person class properties. so, we are also the objects of the person class.

This is the simplest way to undestand and imagine the Class-Object Concept.

To write a program In object oriented dart programming langauge, the class structure is required to simplify the program.

Class Syntax :

class ClassName{

//variables
// constructors
// methods

}

Class keyword is required to declare a class structure. and an object is required to access the states(properties) or behaviours(methods in case of programming) of a class.

For creating object or instance of class like below,

Syntax :

ClassName objectName=new ClassName();

Here, new keyword is used to create an Instance or object of a particular class. And then we can access or say use the properties and methods of that particular class.

To access any property or methods of a class a . operator is used. It is also known as Member Access operator.

For ex :

class Test{
  int a=5;			// a is an instance variable
}

void main() {
  Test test=new Test();	// new keyword is used to create instance of a class.
  print(test.a);		// “.” is a Member Access operator
}

Output :

5

this is the basic Introduction to the Class and Object.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Functions

Functions or methods are the main body part of the program.

Different functions are defined for different behaviours or business logics you want to perform to achieve your goal(i.e, functionality/feature of the program).

In programming languages, a function is a set of statements/instructions, which are processed(executed) to produce the desired output for the user.

A function cannot be written inside function.

We will understand the functions in 3 step process.

  • Function Definition
  • Function Call
  • Function Return

Function Definition

Function definition is the set of instructions written in function which represents which tasks need to be done with what kind of processing.

Syntax :

ReturnType FunctionName(Arguments){
            // set of statements to perform business logic
}

Return type is the data type of the variable, which we want to return at the end of the execution of the function. So that we can use returned variable for other useful purposes.

Function name can be anything as per choice except which conflicts the keyword naming conflicts.

Arguments or parameters can be useful when you want to use them for processing your business logic inside functions.

Inside function you need to write the programming code for your business logic.

For ex :

// void is used if you don’t want to return anything from function.
void main(){
	print(“Hello”);
}

Function Call

Function call is passing the execution flow to the specific function called in program.

If you’ve written the function in the program, but you never call the written function to execute then it will never gets executed. So, function definition is useless without function calling.

For ex :

class Programming{
      Programming(){
            // Function Call
            ExecuteFunction();
     }

     //Function Definition
     ExecuteFunction(){
            print("Program Execution");
     }
}

void main(){
      Programming programming = new Programming();
}

In above program,  ExecuteFunction() gets called from the constructor. If you’ve never called the  ExecuteFunction() then defining that function is useless.

Function Return

Generally, function returns some specific value computed using your business logic. So that returned value can be used for more useful purposes further in the program.

For ex :

class Competition{
  int marks;
  String name;

  Competition(int competitionMarks,String studentName){
    this.marks=competitionMarks;
    this.name=studentName;

//calculateMarks() returns int value so it is assigned to variable of int data type. So, it can be used further to check if user is winner or looser.
    int data=calculateMarks();

//getName() returns String value so it is assigned to variable of String data type. So, it can be used further to get the name of looser or winner.
    String user=getName();

    if(data>33){
      print(user + " is "+ "Winner...");
    }else{
      print(user + " is "+"Looser !!");
    }
  }

// function returning int value
  int calculateMarks(){
    return this.marks+25;
  }
// function returning String value
  String getName(){
    return this.name;
  }
}

void main(){
	Competition c=new Competition(5,"Novak");
	Competition c1=new Competition(10,"Rafael");
	Competition c2=new Competition(17,"Roger");
}

Output :

Novak is Looser !!
Rafael is Winner…
Roger is Winner…

If you don’t want to return any value from function you can simple use “void” keyword. That means “void” is used when function is not returning any value.

Note :

main() function in dart starts the program execution. Which has return type void.

Functions are the core functionality or body of any program. Each class consists of variables, constructors and functions. So, functions are the necessary requirement for any programmer to learn.

To be a better programmer, you must have an upper hand for creating functions as per your requirements. So, practice hard for getting a better hand on creating different functions.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Looping

Looping is the statements written in sequence which are performed continuously until the desired condition is satisfied.

Looping is the concept used for code reuse and improve the efficiency by not writing the same code many times.

In short, looping is generally used to perform some operation or specific block of code repeatedly until specific condition satisfies.

Dart supports the following looping structures.

  1. do-while loop
  2. while loop
  3. for loop
  4. for each loop

All the loops are used for performing operations iteratively. But, they all differ from each other with syntax, condition checking as well as performance.

The conditional expression for any looping must have boolean values i.e., either true or false.

Do-while loop

Do while loop is a loop which executes at least once. After that it evaluates the boolean conditional expression for further iteration of the loop.

Do while loop is generally used when you want to iterate your loop at lease once. Do-while loop will execute at lease once even if it doesn’t satisfies the boolean expression.

In do-while loop, boolean expression comes at the end of the loop. That’s why the loop or block of code gets executed before the boolean expression evaluation.

You must have to pass a condition expression in a do-while loop.

Do and while are the keywords required to use do-while loop.

Syntax :

do{

// block of code or statements

}while(conditional_expression); // conditional_expression must have value of type boolean

For ex :

void main() {
int i=1;
do{
print(“I am the best”);
i++;
}while(i<=2);
}

Output :

I am the best

I am the best

To make a do-while loop infinite pass an expression whose value is always true and you don’t change it any way.

For ex:

void main(){
	do{
	    print(“Infinite loop”);
	}while(2>1); // 2>1 is always true. So, it will iterate for infinite time.So,it will hang your system and your UI will not respond.
}

while loop

While loop is generally used when you don’t know or unsure about the iterations required for the looping.

While loop is executed only if it satisfies the conditional expression.

You must have to pass a condition expression in a while loop.

While is the keyword required to use while loop.

Syntax :

// conditional expression must have value of type boolean.

while(conditional_expression){

// block of code

}

Similarly, to make a while loop infinite pass an expression whose value is always true and you don’t change it any way.

For ex :

void main(){
	// the value of “true” will always be true. Hence, this while loop will iterate infinitely.
		while(true){
		print(“Infinite loop”);
	}
}

for loop

It is the most used loop out of all.

It is generally used when you are sure about the iterations required for the looping.

For is the keyword required to use for loop.

A conventional for loop consists of four parts.

Initialisation

Initialisation is executed only once. it is the set of statements used for initialising different variables.

You can write multiple initialisations for different variables.

Conditional Expression

Conditional expression is tested each time and used to check whether particular loop will iterate further or not. In short, if conditional expression evaluates to true then loop will executed else the loop will break and jump to the next statement after the for loop.

Block of code

It is the main body of the for loop. If Conditional expression evaluates to true then control flow will move inside the for loop where statements(block of codes) are written will be executed.

Increment/Decrement

It is executed every time after the block of code or statements executed.

It is used to increment or decrement any loop control variables.

You can have multiple increment/decrements in one for loop.

Syntax :

// the value of conditional expression must be true to enter inside for loop.

for(Initialisation;Conditional_Expression;Increment/Decrement){

// block of code
}

For ex :

void main(){
  for(int i=0,j=2;i<5 && j<5 ; i++,j++){
    print(i);
  }
}

Output :

0123

If you don’t pass any values for initialisation, conditional expression and increment/decrement it will turn in to infinite for loop and your UI will be stuck.

For ex :

// Also passing a true value in conditional expression which never changes will also turn your loop in to infinite loop same as while and do-while loop.
for(;;){
	print(“Hello friendsssss !!”);
} 

for-in loop

For-in loop is the enhanced form of the for loop.

It just have different syntax structure.

For and in are the keywords required to use for-in loop.

It is used to traverse or iterate different collections(like, array-list) easily.

Syntax :

// dataType is the type of the collection values stored.

for(dataType variableName in collection){

// block of code

}

For ex :

void main(){
// List is the type of the collection
  List<String> companies=["Google","Amazon","Apple","Microsoft"];

	// here String is the dataType of values stored inside collection companies.
  for(String companyName in companies){
    print(companyName);
  }
}

Output :

Google
Amazon
Apple
Microsoft

In this way, we can easily achieve our goal of not rewriting the same code many time and improve the efficiency and performance of the developer in easiest way.

It is better if you have a command over looping concept as it is almost used in each and every programming languages and programs.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Switch

Switch statement is a type of branching control flow statement.

Switch statement takes an expression (which results the constant value) and many block of codes are written for different constant values.

The constant expression taken by the switch statement compares the different constant values and the constant value which equals the value of the expression is selected and the code associated with that constant value gets executed.

The different constant values for which different code blocks are written are known as cases.

The structure of the switch case is neat and clean.

Syntax :

switch(constant expression){
            case value 1 :
                        // the block of code gets executed if constant expression equals value11).                                break;
            case value 2 :
                        // the block of code gets executed if constant expression equals value2.
                        break;
                                    …..
                                    …..
            default :
                        // the block of code gets executed if the constant expression doesn’t match any case.
}

In switch statement, there is another keyword called default. default keyword is used as the case whose block of code gets executed when the value of the constant expression of the switch statement doesn’t match to any case value.

In dart, the block of code written for any switch case must end with a break statement. For default case it’s not necessary to write break statement at the end.

For ex :

For ex: 
switch("sunday"){
    case "sunday":
      	print("sunday");
     	break;
     case "monday":
      	print("monday");
      	break;
      case "tuesday":
      	print("tuesday");
      	break;
    default : print("wednesday");
  }

Output :

sunday

default statement is optional. If you don’t write default case and the switch case expression doesn’t match any cases it will run the program without any error.

In switch statement, there is no place for duplicate switch cases.

So switch statement is another type of branching flow statement. It is used to control the flow of execution based on constant expression of switch statement.

assert :

assert statement is used to terminate the normal execution of the program when the expression evaluates to false.

Syntax :

assert(expression);

For ex :

void main(){
	int i=0;
	assert(i>5);
	print("Hi");
	print("Hello");
}

Output :

Uncaught exception: Assertion failed.

Assertion stands for “Confirmation”. Also, in above example, assert confirms that if the value of the i is greater than 5(i.e., assert expression evaluates to true), only then further execution of the program will take place. Otherwise(i.e., assert expression evaluates to false), an assertion exception will be thrown with the program termination.

So, these control flow statements are directly or indirectly helpful for us to control the flow of the program execution.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Branching (if else)

Dart branching or decision making is used whenever we have to use the conditional test.

Dart supports branching using,

  • if
  • if else
  • if else ladder (Nested if else)

If

If is used whenever we need to perform tasks or operations based on decision making.

For ex :

if the condition satisfies then and then you can perform that particular task.

Syntax :

if(conditional test){

// statements

}

For ex :

void main() {
   var a,b;
   a=10;
   b=5;

  if(a>b){
  print("a is greater than b");
  }
}

In above program, print statement will be executed only when the condition a>b satisfies.

if and else

if and else is used whenever there is conditional possibilities and you have to behave accordingly.

Syntax :

if(conditional test)
{

// statements

}
else
{

// statements

}

For ex :

void main(){
  	var a=10, b=5;
	if(a>b){
		print("a is greater.");
	}else{
		print("b is greater.");
	}	
}

if else ladder (Nested if else).

It is an extended version of if else branching.

It is used to test multiple conditions and perform the satisfied operation.

For ex :

if(conditional test)
{

// statements

}
else if(conditional test)
{

// statements

}
else
{

// statements

}

For ex :

void main(){
	if(a>b){
		print("a is greater");
	}else if(b>c){
		print("b is greater");
	}else{
		print("c is greater);
        }
}

It can have multiple if-else conditions based on your logic.

In above example, If first if condition satisfies then it goes inside that if branch otherwise moves to the second if branch. If the second if condition gets satisfied then will go inside second if brach and performs the operation otherwise moves to the else condition.

In nested if-else branching conditional check starts with the first if-else condition checking to the last if-else. The flow of execution moves to any if branch if particular if condition gets satisfied. Otherwise, the flow of execution moves to the else branch if there is any.

I suggest you to practice if-else branching as much possible because it’s a fundamental concept to achieve better programming skills.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Operators

Operators are the special symbols which stands for specific type of action or operation between operands. For Ex, * is an operator symbol used to perform specific operation which is multiplication between two numbers.

What is operand ?

Operands are the elements which are manipulated by operators.

For ex :

var multiplication = X * Y ;

Here, X and Y are operands which are manipulated by * operator which represents multiplication operation.

There are so many types of operators available in dart as below.

  • Arithmetic operators
  • Equality or relational operators
  • Assignment operators
  • Logical operators
  • Bitwise operators
  • Miscellaneous operators

We will try to cover all the important and useful operators in dart. Let’s start with arithmetic operators.

Arithmetic operators

Arithmetic operators are used to perform basic mathematical operations like, addition, subtraction, multiplication etc.

+Addition between operands
Subtraction between operands
*Multiplication between operands
/Division between operands
~/Division between operands, which gives result in integer value
%Provides the remainder of the division operation

Let’s take an example to briefly understand arithmetic operators.

For ex :

void main(){
  int x = 15, y = 8;
  
  var addition = x + y ;
  print("Addition : ${addition}");
  
  var subtraction = x - y ;
  print("Subtraction : ${subtraction}");
  
  var multiplication = x * y ;
  print("Multiplication : ${multiplication}");
  
  var division = x / y ;
  var remainder = x % y ;
  print("Division : ${division} And Remainder : ${remainder}");
  
  var roundOffDivision = x ~/ y ;
  print("RoundOffDivision : ${roundOffDivision}");
}

Output :

Addition : 23
Subtraction : 7
Multiplication : 120
Division : 1.875 And Remainder : 7
RoundOffDivision : 1

Equality or relational operators

Equality operators are used to generate conditional expressions. Basically, equality opeartors compare two different operands based on relations between them. (greater than, less than , equal to and so on)

==Checks if the compared operands(elements) have equal value
!=Checks if the compared operands(elements) have not equal value
>Checks If the first operand has greater value than second operand
<Checks If the second operand has lesser value than first operand
>=Checks If the first operand is greater value than or equal to second operand value
<=Checks If the second operand has lesser or equal to than first operand value

Let’s take an example to briefly understand equality operators.

For ex :

void main(){
  int x = 15, y = 8, z=8;
  
  if(x > y){
    print (" $x is greater than $y");
  }
  
  if(y < x){
    print (" $y is less than $x");
  }
  
  if(y == z){
    print (" $y is equal to $z");
  }
  
  if(x != y){
    print (" $x is not eqaul to $y");
  }
  
  if(x >= y){
    print (" $x is greater than or equal to $y");
  }

  if(y <= x){
    print ("$y is less than or equal to $x");
  }
}

Output :

15 is greater than 8
8 is less than 15
8 is equal to 8
15 is not equal to 8
15 is greater than or equal to 8
8 is less than or equal to 15

Assignment operators

Assignment operators are used to assign the value to any variable.

Syntax :

// here variable and operand must be of the same data type.
variableName assignmentOperator operand

In above Example, assignmentOperator can be any Assignment operator like, +=, -=, *=, /=, %= etc.

+=Assigns right side addition(+) operation result to the left side variable.
-=Assigns right side subtraction(-) operation result to the left side variable.
*=Assigns right side multiplication(*) operation result to the left side variable.
/=Assigns right side division(/) operation result to the left side variable.
%=Assigns right side division operation remainder(%) result to the left side variable.

For ex :

a+=5; 
/*is equal to a=a+5;Here, a+5 is addition operation between two operands (a and 5) whose result is assigned to the left side variable a;*/

Let’s take an example to briefly understand the Assignment operators.

void main(){
  double x = 15, y = 10;
  
  print("Addition : ${x+=y}");
  print("Subtraction : ${x-=y}");
  print("Multiplication : ${x*=y}");
  print("Division : ${x/=y}");
  print("DivisionRemainder : ${x%=y}");
}

Output :

Addition : 25
Subtraction : 15
Multiplication : 150
Division : 15
DivisionRemainder : 5

Logical operators

These operators are used to combine multiple boolean expressions to perform different logical operations.

&&Logical AND (both boolean expression’s result must be true.)
||Logical OR (any one boolean expression’s result must be true.)

For ex :

void main(){
  int a =15, b=10;
  
  if(a > 0 && a > b){
    print("$a is my favourite number");
  }
  
  if(a < b || a >b){
    print("$b is my favourite number");
  }
}

Output :

15 is my favourite number
10 is my favourite number

For Logical AND operator (&&) both expressions at each side of the operator must be evaluated true. While for Logical OR operator(||) only one expression result should be true.

There is an interesting thing about Logical AND operator that it doesn’t check the second expression if the first expression result is false. As Logical AND operator requires both expression result to be true.

Similarly, Logical OR operator doesn’t check the second expression if the first expression result is true. As Logical OR operator requires only one expression result to be true. Due to this short-trick of easily evaluating logical expressions logical operators are also known as short-hand operators.

Bitwise Operators

Bitwise operators are used to perform bit operations on individual integer numbers only.

Their working is similar to Logical Gates (AND, OR, XOR, etc) available in digital electronics to perform different bit operations on numbers.

Real life use-cases of bitwise operators is communication over usb ports/sockets or in data comparison or encryption.

These operators work on binary values i.e, 0 and 1 to manipulate data bit by bit.

& – Bitwise AND Operators

The & operator compares its both operands using Logical AND operation similar to digital electronics.

If both bits are 1 then It gives resultant bit 1 else resultant bit will be 0.

| – Bitwise OR Operators

The | operator compares its both operands using Logical OR operation similar to digital electronics.

If any of the bit is 1 then It gives resultant bit 1 else resultant bit will be 0.

^ – Bitwise XOR Operators

The ^ operator compares its both operands using Logical XOR operation similar to digital electronics.

If both bits are different resultant bit is 1 else resultant bit will be 0.

Let’s take an example to briefly understand the Bitwise operators.

For ex :

void main(){
  int a =15; // binary value of a is 1111
  int b=10; // binary value of a is 1010
  
  var AND = a & b; // 1111 & 1010 = 1010 which is binary value of 10
  var OR = a | b; // 1111 | 1010 = 1111 which is binary value of 15
  var XOR = a ^ b; // 1111 ^ 1010 = 0101 which is binary value of 5
  
  print("Value of Bitwise AND Operation is $AND");
  print("Value of Bitwise OR Operation is $OR");
  print("Value of Bitwise XOR Operation is $XOR");
}

Output :

Value of Bitwise AND Operation is 10
Value of Bitwise OR Operation is 15
Value of Bitwise XOR Operation is 5

Miscellaneous Operators

In this part, we are going to discuss some other useful operators which have significance usage for different cases.

Let’s start with Increment/Decrement Operators,

Increment / Decrement Operators

Dart has special type of operators known as Increment/Decrement operators.

Increment and Decrement operators are used to increment and decrement the value of the particular value by 1 respectively.

Increment operators are denoted using ++ while decrement operators are denoted using — symbol.

increment/decrement operator symbol prefixed before the variable is known as pre increment/decrement operators. While, operator symbol postfixed after the variable is known as post increment/decrement variables.

pre increment operator (++a)

The value of the variable (a) is incremented by 1 first. Later incremented value is returned or assigned to the expression (++a).

pre decrement (–a)

The value of the variable (a) is decremented by 1 first. Later decremented value is returned or assigned to the expression (–a).

post increment operator (a++)

The value of the variable a is returned or assigned to the expression (a++) first. Later the value of the variable (a) is incremented by 1.

post decrement operator (a–)

The value of the variable a is returned or assigned to the expression (a–) first. Later the value of the variable (a) is decremented by 1.

Let’s take an example to briefly understand the increment/decrement operators.

For ex :

void main(){
  int a =10, b=20, c=30, d=40;

  var preAdd=--a;
  var preSub=--b;
  
  print("value of the a is $a and value of pre increment expression is ${preAdd}");
  print("value of the b is $b and value of pre decrement expression is ${preSub}");
  
  var postAdd=c++;
  var postSub=d--;
  
  print("value of the a is $c and value of post increment expression is ${postAdd}");
  print("value of the b is $d and value of post decrement expression is ${postSub}");
}

Output :

value of the a is 9 and value of pre increment expression is 9 value of the b is 19 and value of pre decrement expression is 19 value of the a is 31 and value of post increment expression is 30 value of the b is 39 and value of post decrement expression is 40

Ternary Operator

Dart has one special operator to simplify the if else condition which is known as conditional operator or ternary operator.

Syntax :

conditional_expression ? expression1 : expression2

In Ternary operator, it first checks the conditional expression. If the condition is true then expression1 is evaluated otherwise expression2 is evaluated.

For ex :

void main(){
  int a=10, b=20;
  b > a ? print("Greater no = $b") : print("Greater no = $a") ;
}

Output :

Greater no = 20

is Operator

Dart has is operator to check whether an object is an instance of the specified type or not.

is operator is generally used while type-casting objects to avoid unnecessary exceptions.

Syntax :

instance is type

For ex :

class Data{
}
class Test{
}
void main(){
 Test test=new Test();
  
// test is an instance of Data class. While Test is the type of the object reference. 
  if(test is Test){
    print("test is the instance of Test class");
  }
  
  if(test is Data){
    print("test is the instance of Data class");
  }
}

Output :

test is the instance of Test class

Member Access Operator (.)

To access any property or methods of a class, Member Access operator is used.

Member access operator is denoted with “.” symbol.

For ex :

class Test{
  int a=5;			// a is an instance variable
}

void main() {
  Test test=new Test();	// new keyword is used to create instance of a class.
  print(test.a);		// “.” is a Member Access operator
}

Output :

5

So, these are different operators available in dart. Which makes our operation very handy and smoother by providing their built-in functionalities


We have tried to cover all the important dart operators. Although you can visit dart’s official site to cover any missing data related to operators. Also feel free to suggest any changes to make our tutorials more interactive and interesting.


Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Enums

Enums or say enumerations are special kind of class used to represent the group of named constants.

An enum is declared using enum keyword.

Enum can’t be instantiated.

Enum Syntax :

enum enumName{

//named contact list separated with “,”

}

Enum class has some default methods and properties.

Each value in enum list can be retrieved using values method while, position of any enum constant can be retrieved using index property.

For ex :

enum ApiResponseCode { 
// list of named constants separated using “,”
   STATUS_CODE_200, 
   STATUS_CODE_400, 
   STATUS_CODE_500
}  
void main(){
  print(ApiResponseCode.values);
  print(ApiResponseCode.STATUS_CODE_500);
  print(ApiResponseCode.STATUS_CODE_200.index);
}

Output :

[ApiResponseCode.STATUS_CODE_200, ApiResponseCode.STATUS_CODE_400,
ApiResponseCode.STATUS_CODE_500]
ApiResponseCode.STATUS_CODE_500
0

Enum constants have zero based index starting from 0, 1, 2,…

Enums can be efficiently used in switch case to check corresponding values regarding different cases.

For ex :

enum Result { 
   PASS, 
   FAIL
}  
void main(){
  var result=Result.PASS;
  
  switch(result){
    case Result.PASS:
      print("Student Pass!!");
      break;
    case Result.FAIL:
      print("Student Fail!!");
      break;
  }
}

Output :

Student Pass!!

In this way, you can use enum for different case as per your requirements to optimise your code.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Categories
Dart

Dart Symbols

A Symbol object represents an operator or identifier declared in a Dart program.

Simply symbol is a mechanism for retrieving metadata of different identifiers.

For ex :

void main(){
// create an identifier or symbol for “Sample” in memory.
 Symbol test =new Symbol("sample");
 print(test);
 print(#test);
// add “#” to create a symbol literal for any object(here, 
 random value xyz).
 print(#xyz);
}

Output :

Symbol(“sample”)
Symbol(“test”)
Symbol(“xyz”)

The symbols are the references created for different identifiers in the program.

Symbol literals(prefixing any identifier with # symbol) are compile time constants.

But, symbols are invaluable for APIs that refer to identifiers by name, because minification changes identifier names but not identifier symbols.

Probably you might never need to use symbols. But, we have introduced symbol for shake hand purpose with dart.

Previously, symbols were supported by different predefined classes like MirrorSystem. But, currently they all are deprecated. So, it’s better to just learn about symbols and move on.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.