Categories
Dart

Dart Polymorphism

Polymorphism is one of the four fundamental concept for learning object oriented programming.

The word polymorphism has been derived from 2 greek words “poly” and “morph” where poly means many and morph means form.

Polymorphism means an object have different forms and each different form performs same action/task in multiple/different ways.

Polymorphism is generally used to achieve the inheritance mechanism.

Let’s see polymorphism with real word example,
Tony can speak three languages i.e., Gujarati, Hindi and English.

Now Tony will speak Gujarati language with the person who knows Gujarati. Similarly, tony will speak English with the person who knows English and speaks Hindi with the person who knows Hindi.

Here Tony perform one single task that is Speaking. But, the implementation of speaking is different based on language tony speaks. Here, speaking can be in three forms.

So here Tony is the object of the class and speaking is the polymorphism.

Polymorphism in dart is supported only in form of runtime polymorphism (For ex : method overriding etc).

Here we need to understand some concepts before learning polymorphism which are

  • Up-Casting
  • Down-Casting

Up-Casting

Up-Casting is the process of converting a reference of the subclass type to the super class type.

However converting the reference of subclass to superclass will not convert the object to its super type.

It just converts the child object to a more general form(base form) or say it treats the child object as super object.

For ex :

class Shape
{
}

class Triangle extends Shape
{
}

void main()
{
	// Up-casting
	Shape s=(Shape) new Triangle();
	// It is same as Shape s=(Shape) new Triangle();
	Shape s=new Triangle();     
        // Up-casting is done automatically via system.
}

Down-Casting

Down-casting is the process of converting a reference of the superclass type to the sub class type.

Down-casting needs to be done manually by programmer.

For ex :

void main()
{
        // here runtime type of a is Triangle()
	Animal anim=new Triangle();	
	Triangle tri=a;
}

Down-casting is casting the superclass object reference to subclass reference.

Down-casting can be done only if the runtime type of the superclass (i.e., anim’s runtime type is Triangle) must be to the specific subclass reference(i.e., tri’s runtime type is Triangle) in which we are Down-casting.

For ex :

void main()
{
	// here runtime type of a is Animal()
	Animal anim=new Animal();	
	Triangle tri=a;
}

Here runtime type of superclass reference doesn’t match with the subclass reference in which we are Down-casting. Which will generate ClassCastException.

That’s why Up-casting is safer than Down-casting as it is done automatically.

Up-casting and Down-casting both are done at runtime.

Unlike other object oriented programming languages, Dart only supports runtime polymorphism(for ex : function overriding)

Runtime Polymorphism

Runtime polymorphism is the process of calling the overridden function at runtime(at the time of program execution) instead of compile time.

Let’s take an example to understand the polymorphism in better way.

Suppose, we want to draw shapes for different classes. So, we’ll create a class Shape with method drawShape() which draws a Circle Shape.

Let’s create a Shape class which has a method drawShape().

class Shape
{
            drawShape()
        {
                        print(” Circle Shape”);
            }
}

Now there are 3 more sub-classes Triangle, Square and Hexagon of Shape class. All these subclasses will call drawMethod() to draw circle shape.

Now, you will be thinking why we’re creating a Parent class shape and creating a method drawShape() in it.

Because it’s a better way to create a one single method drawShape() and access that method from each classes who wants to draw shape instead of writing that method in each class(writing the same method will consume your memory as well as time).

That’s why we will use the reusability concept of inheritance.

For ex :

class Shape
{
	drawShape()
        {
		print(" Circle Shape");
	}
}
class Triangle extends Shape
{
}
class Square extends Shape
{
}
class Hexagon extends Shape
{
}
void main(){
// Upcasting
	Shape T=new Triangle();
	Shape S=new Square();
	Shape H=new Hexagon();

	T.drawShape();
	S.drawShape();
	H.drawShape();
}

Output :

Circle Shape
Circle Shape
Circle Shape

Now, if triangle class don’t want to draw circle shape from its super class. So, what we can do is that we’ll create a drawShape() method in Triangle class with its own implementation.

For ex :

class Shape
{
	drawShape()
        {
		print(" Circle Shape");
	}
}

class Triangle extends Shape
{
	drawShape()
        {
		print("Triangle Shape");
	}
}
class Square extends Shape
{
}
class Hexagon extends Shape
{
}
void main()
{
        // Upcasting
	Shape T=new Triangle();
	Shape S=new Square();
	Shape H=new Hexagon();

	T.drawShape();
	S.drawShape();
	H.drawShape();
}

Output :

Triangle Shape
Circle Shape
Circle Shape

So in above class when you called the method with the object of class Triangle T, it will first check the method drawShape() in Triangle class. If it’s present then drawShape() method from class Triangle will be implemented else it will check for the accessible drawShape() method in its superclass Shape.

If it’s present in Shape class then drawShape() method of Shape will be executed else it will further check for the accessible drawShape() method in its Super class.

This process will be continued till either the required method drawShape() is found or the highest super class is reached.

This process is known as method overriding.

Polymorphism is the process in which the output of your program depends on the inputs you provide.

For ex :
In above case, the drawShape() method of which class will be depends on the object of particular class accesses it.

So explore more cases of polymorphism by performing some critical programs and practice it to make your development code more convenient to use.

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 Inheritance

Dart supports Inheritance which is one of the core concept of the object oriented programming language.

Inheritance mechanism is used to consume properties and behaviour of a super class in subclass.

Inheritance is the concept by which one class can derive properties and methods of another class.

The class which derives or inherits the properties from another class is known as child class or Sub Class.

The class whose properties are derived or inherited by other classes is known as parent class or super class.

In Inheritance, child class has access to the properties and methods of its own class as well as its parent class.

In dart, Object class is the Super class of all classes. Hence, each class is derived from at least one class or have at lease one parent class except Object class.

In Dart, extends keyword is used for Inheritance.

There are 2 types of inheritance in dart.

  1. Single Inheritance
  2. Multilevel Inheritance

Single Inheritance

when properties and methods of one class is derived from exact one other class is known as Single Inheritance.

For ex :

class A{
	displayA(){
		print("A");
	}
}
class B extends A{
	displayB(){
		print("B");
	}
}

void main(){
	A a=new A();
	B b=new B();
	a.displayA();
	b.displayA();
	b.displayB();
}

Output :

A
A
B

In Above example, class B has all the properties and methods of its parent class A as well itself.

Multilevel Inheritance

Multilevel Inheritance is the type of inheritance in which a class can be derived from another derived class. i.e., A class will act as the Super class for any particular class and that same class will act as the child class for another class.

For ex :

class A{
  displayA(){
    print("A");
  }
}
class B extends A{
  displayB(){
    print("B");
  }
}
class C extends B{
  displayC(){
  }
}
void main(){
  A a=new A();
  B b=new B();
  C c=new C();
  a.displayA();
  b.displayA();
  b.displayB();
  c.displayA();
  c.displayB();
  c.displayC();
}

Output :

A
A
B
A
B

In above example, class B is derived from class A. So, class B acts as the child or sub class for class A.

Similarly, class C is derived from class B. That’s why class B acts as the parent class or super class for class C.

Also, one point to note down is that the child class will have access to the properties of its immidiate parent class as well as all its non immidiate parent classes.

Output :

class C have access to all the properties and functions of its immidiate parent class B as well as its non immidiate super parent class A.

We also need to understand the code reusability as it is the main purpose of the Inheritance

Code Reusability

It is nothing but accessing or using the properties and methods of existing class while creating a new class as per user requirement.

This concept is used to remove redundant or duplicate code written in the program for optimizing your coding skills and program structure.

Code Reusability can be easily achieved using the inheritance.

For ex :

class Favourite{
  int rank=5;
  Test(){
    print("This is Test Method");
  }
	Calculation(int a,int b){
		print(a+b);
	}
}
class Normal extends Favourite{
  
}
void main(){
	Normal normal=new Normal();
  	normal.Test();
 	print(normal.rank);
  	normal.Calculation(5,10);
}

Output :

This is Test Method
5
15

In above example, class Normal doesn’t have any properties or methods, but it can access all the properties and methods of its super class using Inheritance.

let say, if we define Calculation() function in class Favourite and further we also need Calculation() function in Normal class. So, if Normal class inherits the Favourite class then using Inheritance rules we do not need to define that function again in Normal class.

As all the properties and functions of parent class are also the properties and functions of its child class. Just as you’re parents’ property is yours too.

So, for enhancing the code structure and reusability of your code the Inheritance concept is widely used.

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 Static Variables and Methods

Class is a template or prototype (or say defined model or structure) from which objects (instances) are created. Each instance of class have properties (variables) and behaviours (methods) defined in the prototype class. The scope of instance variables and methods are limited to particular instance’s lifetime only. So, it’s not possible to access or share a single variable to all the instances of a class using instance variables and instance methods etc.

Static Variables and Methods

Static variables and methods are mostly used to store information which can be shared among all the instances of class.

They are initialized only once, at the start of the program execution. Class variables and methods are initialized even before the instance variables or objects of the class.

Static Variables and methods are known as class variables and methods.

To declare a static variable or method static keyword is used in the program.

Static Variable Syntax :

static dataType varaiableName;

Static Methods Syntax :

static returnType methodName(){

// code block

}

Static variables and methods can’t be accessed creating instance of a class.

To access static variables and methods, call them with the className(in which particular static variable or method is declared).

For ex :

class SetTopBox{
  static String Channel;
  static changeChannel(String channelName){
    print("Change Channel : " + channelName);
  }
}
void main(){
// calling static variable Channel using className following . followed by variableName.
  SetTopBox.Channel="Sony TV";  
// calling static method changeChannel using className following . followed by methodName.
 print(SetTopBox.Channel);
  SetTopBox.changeChannel("Star TV");
}

Output :

Sony TV
Change Channel : Star TV

We can also share a static variable or method among different classes as well. To access a static variable or method from other class we need to call them using the className in which they are declared.

For ex :

class SetTopBox{
  static String Channel="Cartoon TV";
  static changeChannel(String channelName){
    print("Change Channel : " + channelName);
  }
}
class AndroidTV{
  AndroidTV(String channelName){
    print(SetTopBox.Channel);
    SetTopBox.changeChannel(channelName);
  }
}

void main(){
  AndroidTV TV=new AndroidTV("Discovery TV");
}

Output :

Cartoon TV
Change Channel : Discovery TV

In this way, we can easily share a variable and method across all the classes of our large projects. Which in turn makes our programming way more easy to handle and manipulate the data.

You must be well aware about static variables and methods for a better programming experience in your different projects.

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