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.

Categories
Dart

Dart Runes

Dart Runes are the UTF-32 unicode points of a string.

Unicode values are nothing but Standard for representing characters as integers.

Unicode defines a unique number value for each letter, digit and used in all of the world’s popular languages(Writing Systems);

For ex :

0 to 9, Capital letters(A,B,…,Y,Z) etc. have unique Unicode values to identify easily by the Machine.

Rune is nothing but an integer representing unicode codepoint.

For ex :

Character A has Rune value \u{0041} and Unicode is U+0041.

For More Details you should visit and check details at website.

Different emojis, letters and also digits have unique unicode codepoints. which implies they also have unique Rune Values(code points).

we can express a Unicode code point as \uXXXX, where XXXX is a 4-digit hexidecimal value. and u stands for unicode.

For ex :

the heart character (?) is \u2665.

To specify more or less than 4 hex digits in Runes, place the value in curly brackets.

For ex :

the thumbsup emoji (??) is \u{1f44d}.

For ex :

void main()
 {

        Runes clapping = new Runes("\u{0050}");
        print(clapping);
        print(new String.fromCharCodes(clapping));

        Runes input = new Runes('\u2665  \u{1f605}  \u{1f60e}  \u{1f47b}  \u{1f596}  \u{1f44d}');
        print(new String.fromCharCodes(input));
}

Output :

(80)
P
? ?? ?? ?? ?? ??

In dart, string class has several properties and methods to extract the rune information.

Runes Common Properties

For ex :

main() {
  Runes clapping = new Runes("\u{0050}");
  Runes clappingData = new Runes("ABCD");
  print(clappingData.first);
  print(clappingData.last);

  print(clapping.single);
  print(clapping.hashCode);
  print(clapping.runtimeType);
  print(clapping.isEmpty);
  print(clapping.isNotEmpty);
  print(clapping.length);
}

Output :

65
68
80
31123396
Runes
false
true
1

Runes Common Methods

For ex :

main() {
  Runes clappingData = new Runes("ABCD");
  print(clappingData.toString());
  print(clappingData.skip(1));
  print(clappingData.contains("C"));
  print(clappingData.contains((67)));
  print(clappingData.toList());
  print(clappingData.toSet());
}

Output :

(65, 66, 67, 68)
(66, 67, 68)
false
true
[65, 66, 67, 68]
{65, 66, 67, 68}

Practice different properties and methods of dart runes by yourself to understand the better use of it.

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 Maps

After the list data structure, we will learn one of the most important data structure i.e., Map.

Map also acts as the built in data type for dart programming language.

The map data structure has unique pattern of storing data in key-value pair.

The type of key and value in map can be of any data type.

Each key can occur only once(means every key should be unique), but you can use the same data for value multiple times. user can also provide any data to the value even NULL.

Maps can grow and shrink at runtime by adding the key-value pairs.

Maps in dart are supported using map literals(a notation for representing a fixed value) and map constructor.

Map using map literals

To declare a map, we need to enclose the key value pairs in between a pair of curly braces “{}”.

Syntax :

var variableMapName = { key:value, key2:value2, key3:value3 }

Map using map constructor

For ex :

void main() { 
  var dataMap = {'Name':'Bill','Surname':'Gates','Designation':'Developer'}; 
   print(dataMap); 
}

Output :

{ Name: Bill, Surname: Gates, Designation: Developer }

To declare a map using constructor, first create the map instance and then initialise the map objects.

Syntax :

var variableMap = Map(); // declare the map
variableMap [key] = value; // initialise the map

For ex :

void main() { 
   var deviceMap = {'Device':'Motorola','Model':'Moto G5','Manufacturer':'Motorola'}; 
   deviceMap['Brand'] = 'Google'; 
   print(deviceMap); 
}

Output :

{ Device: Motorola, Model: Moto G5, Manufacturer: Motorola, Brand: Google }

We can also define the data types for key-value pair at the time of map declaration.

For ex :

void main() { 
   var deviceMap = Map<String,int>(); 
   deviceMap['Age'] = 100; 
   deviceMap['Number'] = 200; 
   print(deviceMap); 
}

Output :

{Age: 100, Number: 200}

For above example, user can only pass the key of string data type and assign the value of Int data type. Otherwise, it will generate the compile time error as data type of key-value pair are defined already.

In this way you can define the data type for key value pair in dart maps.

Several built in properties and methods are defined to perform data related operations very quickly and efficiently.

Map Common Properties

For ex :

main(){
  var mapData=new Map<String,String>();
  mapData['King']="Arthur";
  mapData['Queen']="Alizabeth";
  mapData['Prince']="Harry";
  print(mapData);

  print(mapData.length);
  print(mapData.keys);
  print(mapData.values);
  print(mapData.isNotEmpty);
  print(mapData.isEmpty);
  print(mapData.runtimeType);
  print(mapData.hashCode);
}

Output :

{King: Arthur, Queen: Alizabeth, Prince: Harry}
3
(King, Queen, Prince)
(Arthur, Alizabeth, Harry)
true
false
JsLinkedHashMap
540333345

Map Common Methods

For ex :

main(){
  var mapData=new Map<int,String>();
  var mapData2={1:"A",2:"B",3:"C"};
  mapData[101]="Good";
  mapData[102]="Very Good";
  mapData[103]="Best";
  mapData[104]="Smarter";
  print(mapData);

  print(mapData.containsKey(111));
  print(mapData.containsValue("Best"));
  print(mapData.remove(104));
  print(mapData.toString());
  
  mapData.clear();
  mapData.addAll(mapData2);
  print(mapData);
  
  mapData.putIfAbsent(105, ()=>"hello");
  print(mapData);
}

Output :

{101: Good, 102: Very Good, 103: Best, 104: Smarter}
false
true
Smarter
{101: Good, 102: Very Good, 103: Best}
{1: A, 2: B, 3: C}
{1: A, 2: B, 3: C, 105: hello}

This all methods and properties describes that dart maps are very handy and dynamic data collection. So, user can anonymously use dart map for storing data in key-value pair.

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 Lists

From, now on we are gonna discuss about the data structures(as name suggests structures used for manipulating different data).

I think, there are 2 data structures a programmer must learn for manipulating and storing the data which are List and HashMap.

So, in this tutorial we are gonna talk in deep about the list data structure.

List is also the built in data type for dart programming language.

Lists is the very common data structure used in almost all of the languages.

Lists is the very handy way to manage data of different objects.

List is the collection of ordered or group of objects of the same data type in general.

In dart, arrays are not used. Instead Arrays will act as the List Objects.

Even dart virtual machine predicts the list as the array objects.

The basic list structure can be described as follow:

For ex :

var list = [10, 20, 30]; // list with only 3 Elements

Above example has 3 list elements 10, 20, 30.

List has the zero based index, which means above list has value 10 at the index 0, value 20 at the index 1 and value 30 at the index 2.

So, which means particular values stored in the list are elements.

While, each elements stored in the particular position in the list is Index.

and therefore, size of the list = [size of the elements] – 1
and size of the list = [size of the last index] // as we know that index starts from 0 to expand up to [total elements-1]

List Syntax :

var list_name=new List(list_size);

With above syntax, fixed size list can be created and we can store data elements up to the specified list size.

we cannot shrink or expand the list size.

List Initialisation :

list_name[index]=value;

the List initialisation is used to assign the values to the list elements.

For ex :

void main()
	{
		var avengers=new List(3);
  		avengers[0]="Hulk";
  		avengers[1]="Thor";
  		avengers[2]="Ironman";
  		print(avengers);
	}

Output :

[Hulk, Thor, Ironman]

The size of the above list is 3 if you try to add 4th element in the list it wiil give you ( Index out of range) exception.

We can also initialise the list at the time of declaration as following :

For ex :

void main(){ 
    var player_list = ["Roger","Rafael","Novak"];    			 
    print(player_list); 		
}

Output :

[Roger, Rafael, Novak]

we can also, create the dynamic list with no specified size. in which, we can add the elements in the list according to our neeeds using add() function defined in List class.

For ex :

void main() { 
   	var languages = new List(); 
   	languages.add("C"); 
	languages.add("Dart");
  	languages.add("Java");
 	print(languages); 
}

Output :

[C, Dart, Java]

List creates an unspecifeid length list using the empty List() Constructor from the List Class.

Lists class have many pre-defined properties and functions to perform efficient tasks for manipulating the data inside the List Structure.

you can also store the data of group of objects with different data types like, String, boolean, integer etc.

For ex :

void main() { 
   	var dataList = new List(); 
   	dataList.add("Toastguyz"); 
   	dataList.add(true);
   	dataList.add(123456);
   	print(dataList); 
}

Output :

[Toastguyz, true, 123456]

List Common Properties

For ex :

main() {
  var list=new List<String>();
  list.add("Sachin");
  list.add("Sehwag");
  list.add("Dhoni");
  list.add("Kohli");
  list.add("rohit");

  print(list.length);
  print(list.reversed);
  print(list.first);
  print(list.hashCode);
  print(list.isEmpty);
  print(list.isNotEmpty);
  print(list.iterator);
  print(list.last);
  print(list.runtimeType);
}

Output :

5
(rohit, Kohli, Dhoni, Sehwag, Sachin)
Sachin
42153199
false
true
Instance of ‘ListIterator’
rohit
List<String>

List Common Methods

For ex :

main() {
  var listValues = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009];
  var list = new List<int>();
  list.add(107);
  list.add(108);
  list.add(109);
  list.add(110);
  list.add(101);
  list.add(102);
  list.add(103);
  list.add(104);
  list.add(105);

  list.removeLast();
  print(list);

  list.sort();
  print(list);

  list.insert(6, 106);
  print(list);

  list.setRange(2, 7, listValues);
  print(list);

  list.remove(110);
  print(list);

  list.asMap();
  print(list);

  print(list.indexOf(109));
  print(list.sublist(3));
  print(list.contains(2004));
  print(list.skip(5));
  print(list.elementAt(2));

  list.addAll(listValues);
  print(list);

  list.shuffle();
  print(list);

  //  print(list.clear());
}

Output :

[107, 108, 109, 110, 101, 102, 103, 104]
[101, 102, 103, 104, 107, 108, 109, 110]
[101, 102, 103, 104, 107, 108, 106, 109, 110]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109, 110]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109]
[101, 102, 2001, 2002, 2003, 2004, 2005, 109]
7
[2002, 2003, 2004, 2005, 109]
true
(2004, 2005, 109)
2001
[101, 102, 2001, 2002, 2003, 2004, 2005, 109, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
[2005, 2003, 2001, 101, 2003, 2002, 2004, 2008, 2006, 2007, 109, 2002, 2001, 2005, 2009, 2004, 102]

Again, I must say that list is the important topic to have grip on it. so, make more and more practice with lists to be a better Programmer.

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 Boolean

Booleans are the data types which can have only 2 values true and false.

Now, you’ll think how a data type with only 2 values can be so useful in programming logic.

But, you will know that Booleans are so useful to test any conditional expression.

For ex :

do you want to go to School? //It can have only 2 values ‘Yes’ or ‘No’.

So, similarly Boolean data type uses true and false values which acts as the conditional results for different situations.

To declare any variable as Boolean, bool keyword is used.

For ex :

void main()
{
  bool value;
  print(value);
}

Default value for booleans is null.

You can directly provide the values to boolean variables like,

For ex :

void main()
{
  bool value=false;
  print(value);
}

Similarly we can use booleans for testing different situations according to our logic.

For ex :

void main()
{
  	int A=10,B=20;
	if(A>B)	// conditional expression a>b can be true or false only.
	{	
		print("A is greater than B");
	}else{
		print("B is greater than A");
	}
}

As booleans can have only true or false values. General purpose usage of boolean data type is to evaluate the conditional expressions.

So, if A>B is true then condition satisfies and your program execution enters inside if branch, otherwise program execution moves to else branch.

So, in this way you can Implement Boolean data type anywhere in the programming code to check conditional expressions.

Practice with so many conditional Program definitions to be more familiar with the Booleans.

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 Strings

A data type String is a sequence of UTF-16 code units.

Data type String is the representation of sequence of characters.

Data type String is used for storing values other than numbers like words, sentences etc. in variable.

To declare any varible as String, “String” keyword is used.

You can represent String with words or sententences or quotes in between the single or double quotes.

For ex :

String variableName=”Toastguyz”;
String variableName=’Toastguyz’;

But, dart also provide facility for declaring String variable values in between n number of starting quotes and n number of ending quotes.

For ex :

String variableName=””ToastGuyz””;

You cannot use String variables starting with 4 quotes and ending with 10 quotes for storing the string values.

For ex :

String variableName=””ToastGuyz”””””’; // will generate the compile time error.

We can use string for storing different kind of values like words, sentences or data information etc.

For ex :

void main(){
	String name="ToastGuyz";
	String hobbies="I Love Coding";
	String sarcasm="Are you Smart?";

	print(name);
}

String Manipulation

You can add/append one String value to another String value to generate a new String is termed as Concatenation(Interpolation).

To concatenate one String to another +(plus) operator is used.

For ex :

void main(){
	String firstName="Bill";
	String lastName="Gates";

	print("Name = " + firstName + lastName);
}

Therefore, string manipulation can be helpful to format the String data in appropriate manner as well as for individual needs.

We can use ‘$’ identifier for dynamically change the value of the expression within Strings.

For ex :

void main()
{
		int value=10;
		print("My Favourite Number is $value");
}

Output :

My Favourite Number is 10

You can also manipulate the expression within Strings using ‘${expression}’

So using ‘${}’ identifier we can also manipulate the expression in very neat and handy manner.

For ex :

void main()
{
	int a=10;
  	int b=20;
	print("Total of the Sum is ${a+b} ");
}

Output :

Total of the Sum is 30

Users can also manipulate the 2 string variables in between the expressions like,

For ex :

void main()
{
    		String a='Strongest';
    		String b='Avenger';
    		print("Hulk is the ${a+b}.");
}

Output :

Hulk is the StrongestAvenger.

Manipulating strings in different ways using your logic is fun.

String Common Properties

For ex :

void main()
{
		String a='Strongest';
  
  		print(a.length);
  		print(a.codeUnits);
  		print(a.runes);
  		print(a.runtimeType);
  		print(a.isEmpty);
  		print(a.isNotEmpty);
}

Output :

9
[83, 116, 114, 111, 110, 103, 101, 115, 116]
(83, 116, 114, 111, 110, 103, 101, 115, 116)
String
false
true

String Common Methods

For ex :

void main()
{
	String a='Strongest';
  	String b="Avenger";
  	String c="ABCDEF";
  	String d="abcdef";
        String e="  ab cdefghi ";
  	String f="def";
  	String g="dek";
  
  	print(a.substring(2,5));
  	print(a.codeUnitAt(5));
  	print(a.startsWith("Str"));
  	print(a.replaceAll("ron","toytoy"));
  	print(a.split("n"));
  	print(a.contains("ron"));
  	print(a.indexOf("r"));
  	print(c.toLowerCase());
  	print(d.toUpperCase());
  	print(e.trim());
        print(a.endsWith("est"));
  	print(f.compareTo(g));
  	print(a.toString());
}

Output :

ron
103
true
Sttoytoygest
[Stro, gest]
true
2
abcdef
ABCDEF
ab cdefghi
true
-1
Strongest

In this way, different built-in properties and methods of String data type makes it easy and efficient for performing some handy work.

So practice the String data types with more and more programming definitions to get grip on it.

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 Numbers

Dart Number is the Super type(parent) of the integer and double.

Starting with the first data type numbers, which is divided in to 2 types,

  1. Integer
  2. Double

Numbers can have value from -2^63 to 2^3-1 but as we all know that Dart is converted to javascript directly so, it allows only values in range from -2^53 to 2^53-1. Beyond this range Dart VM will give you a garbage value.

For ex :

Numbers can be 1,-5,3.5,-45.25 etc. So, In this tutorial we will briefly discuss about integer as well as doubles.

Integer

Integer contains all the numbers which does not have decimal values.

You cannot assign the decimal value(fractional value) to an integer data type variable. Dart VM will give you a compile time error if you do so.

Integer variable cannot have values larger than 64 bits. Dart has integer data type range from (-2^63) to (2^63-1) (i.e,-9223372036854775808 to +9223372036854775807) which means you cannot assign the value beyond this range(-2^63 to 2^63-1) to the variable. By, assigning value beyond this range Dart VM will you give you compile time error.

To declare any varible as integrer, int keyword is used.

For ex :

int variableName=7;

User can also provide hex values to the integer variables. which is used to store different color codes.

For ex :

int hex = 0xABCDEF;

User can also perform bitwise shift(<<,>>) ,AND(&) and OR(|) operators. we will briefly discuss about it later.

For ex :

print(3<<6); // which gives value 192

Double

64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.

Integer cannot have fractional(decimal) values. so, double is introduced to achieve the desired requirements.

To declare any variable as Double, double keyword is used.

For ex :

double variableName = 7.7;

User can also store exponential values to the integer variables. which is used to store different color codes.

For ex :

double value= 1.42e5; // value=142000
where, e is the 10 base to power 5

User can perform basic arithmatic operations(+,-,*,/) with the Number data types(int and double included).

The operations performed using either int or double data type can also be performed using num data type as Number is the SuperClass for int and double.

Parsing Numbers

The parse() static function is used to get the number values(either int or double) stored in String variable.

For ex :

void main() {
  String i='10';
  print(num.parse(i)); 
  print(num.parse('10.10')); 
}

User cannot parse any string variables with values other than numeric values.

Number Common Properties

For ex :

void main() {
  int x1=556;
  int x2=-200;
  double y1=121.6;
  double y2=-1000.45;
  
  print(x1.isEven);
  print(x1.isOdd);
  
  print(x1.hashCode);
  print(y1.hashCode);
  
  print(x1.bitLength);
  
  print(x1.isFinite);
  print(y1.isFinite);
  
  print(x1.isInfinite);
  print(y1.isInfinite);
  
  print(x1.isNaN);
  print(y1.isNaN);
  
  print(x1.isNegative);
  print(y1.isNegative);
  
  print(x1.runtimeType);
  print(y1.runtimeType);
  
  print(x2.sign);
  print(y2.sign);
  
}

Output :

[true, false, 556, 121, 10, true, true, false, false, false, false, false, false, int, double, -1, -1]

Number Common Methods

For ex :

void main() {
  int x1=556;
  int x2=200;
  int x3=-9999;
  double y1=121.6;
  double y2=1000.45;
  double y3=-6666.66;
  
  print(x1.toString());
  print(y1.toString());
  
  print(x1.toRadixString(5));
  
  print(x3.abs());
  print(y3.abs());
  
  print(x3.toUnsigned(3));
  print(x3.toSigned(2));
  
  print(x1.round());
  print(y1.round());
  
  print(x1.floor());
  print(y1.floor());
  
  print(x1.ceil());
  print(x2.ceilToDouble());
  print(y1.ceil());
  print(y2.ceilToDouble());

  print(x1.compareTo(x2));
  print(y1.compareTo(y2));
  
  print(x1.gcd(x2));
  
  print(x1.remainder(x2));
  print(y1.remainder(y2));
  
  print(x1.toDouble());
  print(y1.toInt());
  
}

Output :

[4211, 556, 121.6, 9999, 6666.66, 1, 1, 556, 122, 556, 121, 556, 200, 122, 1001, 1, -1, 4, 156, 121.6, 556, 121]

So, we can apply Numbers in many ways ,either as int or double to achieve our desired requirements. Further, we will discuss about Strings in Dart.

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 Variable Scope

The scope of variables is the lifetime of the variable.

The variable scope is the lifetime of a variable for which a particular block of code is executed.

Variable scope can be decided using the type of variables,

  1. Local Variable
  2. Global Variable

Local Variable

A local variable is a type of variable declared inside programming blocks(i.e., for loop, if else, switch and many more) or functions.

It can only be used inside that particular code of block or function in which it is declared or defined.

Once that particular code of block or functions is executed, the scope of a variable is finished or say that the local variable is destroyed.

For Ex :

void main()
{
       int x=1;
       for(int i=0;i<2;i++)
       {
    	 print(i);
	 x++;
	 print(x);
       }
}

Output :

0213

In above example, the scope of variable i is limited inside the loop only. As it is defined inside the loop. As the loop execution completes the scope of variable i get finished.

Similarly, the scope of variable x is limited to only the main function execution. As the execution of main function completes, the lifecycle or scope of the variable finishes and variable gets destroyed as well.

So, the scope of local variable is limited to the block of code under which it is declared or defined whether it ls a function, a loop , a parameter or a block of code.

Global Variable

Global variables are defined outside the function and used to access from anywhere.

The scope of global variable is limited from the start of the program to the end of the program.

For ex :

class Sample
{
  int id=1;
  String name="toastguyz";
  test()
  {
    print("Sample "+id.toString());
  }
}
// global variable
int a=10;
void main()
{
	for(int i=0;i<2;i++)
        {
            print(i);
            print(a);
        }
  Sample S=new Sample();
  S.test();
}

Output :

0
10
1
10
Sample 1

In the above example, the scope of the global variable is from the beginning of the program to the end of the program. While the scope of the local variable i is limited to the end of the execution of the for a loop.

One other example of global variables are instance variables.

Instance variables are the variables declared inside the class but outside the method.

We have discussed about it prior. Checkout our tutorial on instance variable to get familiar with it.

Instance variable acts as global variable for the object of the particular class. The scope of the instance variable starts from the creation of the object and ends with the object destruction.

In the above example, instance variables id and name can be accessed globally for the object S in the class Sample.

So, a local variable is used whenever they need to manipulated inside a block of code only while global variables are used whenever the necessity to access the variable from anywhere in the program is required.

As local variables get destroyed as soon as the block of code gets executed while global variables will obtain the memory till the end of the program. So, both types of variables have their own specific purpose to use. So prefer to use a local variable in general wherever it is possible for memory efficiency. Because a single global variable requires a greater amount of memory in comparison to a local variable

It will be useful to understand the local and global variable usage to become a better developer.

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.