Wednesday, November 14, 2018

Learn Golang Tutorials - Beginner guide to Functions with examples

Learn Golang Tutorials - Beginner guide to Functions with examples

Golang Functions

This article covers the following things related to functions in  Go language 
  • why Function are required?
  • Function Declarations
  • Multiple return values
  • Named return values
  • Defer
  • closure
  • Anonymous functions
  • The function assigned as the value
  • passing arguments to the function
  • function slice to an array

why Function is required?

Functions are a program or multiple lines code written to achieve specific functionality. every functionality is defined as a function in Go Langauge.
Every Runnable code in golang has main() function.k The functions can be called by some other code at a different location. The advantages with functions are duplicate code and maintenance of code.
Few key points of a function in golang.
  • Functions are code statements designed to achieve some tasks 
  •  It takes input and executes the code and returns the output
  •  Functions executed  when functions are called by some other code
  •  functions are also called subprograms, methods, procedures
The syntax for defining functions
func functionname([argument1 datatype,argument2 datatype])[returnvaluename returntype]{
code block statement(s)
}
To design functions in any programming language, Following things are required
  • Function Header 
  • Function Body 
  • Function Caller
Function declaration contains header and body.
Few notes about the syntax of the function.
  • func keyword - func is a keyword in golang. Every function declaration always starts with this keyword.
  • functionname - It is function name which is being used to execute by the caller in other location code base 
  • argument1 -  These also called parameter, which will be enclosed with ( and ). The syntax for argument declaration is the argument name followed by data type. Multiple parameters can also be declared separated by a comma. These are optional ie empty parameters also valid.
  • return type - Function return multiple values. declaration of return type contains name and type. Type is optional. Any number of return types can be declared. It is an optional type.
  • Function body - It is actual code written to achieve some tasks which is placed between { and }
  • Function caller - Once the function is declared,  we need to execute a function by calling it. Once the function is called, control goes to function body  and executes it and return the value, once done, control transfer to caller code

Example

We will see various features of functions with various and examples in below sections.

Empty Function declaration

The following is an empty function which has no input parameters and it is not returning anything. This is also a valid function.
func printmessage() {  
 fmt.Println("Hello world")
}
Basic Function with input and output here is an example for function The below function has two input parameters - value1 and value2 of data type int. The return type is also int which returns the sum of these two numbers.
package main

import "fmt"

func sum(value1 int, value2 int) int {
 return value1 + value2
}
func main() {
 fmt.Println(sum(1, 2))

}
We have declared a function. Now we have to call the function. the function is called with function name by giving function parameters. the syntax is sum(1, 2) and the output of the above program is
3
Multiple parameters of the same type 
when there are multiple parameters of the same type are declared side by side, We can avoid by declaring type multiple times with simple syntax as follows
func sum(value1, value2 int) int {
 return value1 + value2
}

Return Multiple values from a functions 

In Other programming languages like Java and javascript always returns a single value. Functions in Golang returns multiple values. Declared IncrementAndDecrement  function with two parameters of the same type, first parameters is incremented by one, the Second parameter is decremented by 1. finally both return the values. if function is returning multiple values, return types must be declared with ( and ). return types in header and body are separated by the comma
func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}
The output of the above program code is
6 4
 
Please have a look of below code where return types are not declared in ( and ). It gives compilation error missing function body, unexpected comma after the top-level declaration,non-declaration statement outside the function body
func IncrementAndDecrement(value1, value2 int) int, int {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 value1, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d  %d", value1, value2)
}
The complete error report is
A:\Golang\work>go run First.go
# command-line-arguments
.\First.go:5:6: missing function body
.\First.go:5:51: syntax error: unexpected comma after top level declaration
.\First.go:8:2: syntax error: non-declaration statement outside function body

Blank Identifier - subset return values

We already saw multiple return values support in golang. the function is returning two values, the caller has to get the only a subset of data ie one value should be returned from the function. Then we will use the blank identifier for this. _ is called as a blank identifier. on which any type of value accepts and not returned from function The IncrementAndDecrement function returns two values, But the caller needs only one value, Another value place should be replaced with a blank identifier (_)
package main

import "fmt"

func IncrementAndDecrement(value1, value2 int) (int, int) {
 var incrValue = value1 + 1
 var decrValue = value2 - 1
 return incrValue, decrValue
}
func main() {
 _, value2 := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", value2)
}
Output is
4

Named return values from a Function 

In all above examples, We are just providing return type in the function declaration. We can also provide return name and type In the below function declaration, the returned statement contains name and type and both are enclosed in ( and )
func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return v1
}
func main() {
 value1 := Increment(5)
 fmt.Printf("%d", value1)
}
valid cases for multiple values return for the above code. It is not required to return the value manually. Just return statement is enough. named return value(v1) in declaration ie (v1 int) and body ie.v1 = value1 + 1 should have same name for this case
func Increment(value1 int) (v1 int) {
 v1 = value1 + 1
 return // not required to have return value
}
This is also valid as named value v1 is different from v2, but return statement must be declared with new variable
func Increment(value1 int) (v1 int) {
 var v2 = value1 + 1
 return v2
}
The following code is not valid as return statement in the header is missing ( and ) and it gives compilation error - missing function body syntax error: unexpected int after top-level declaration
func Increment(value1 int) v1 int {
 v1 = value1 + 1
 return v1
}

Variadic functions - variable arguments 

This is one more feature of a function in golang. Function can be declared with variable number arguments. Println is inbuilt in function which accepts variable number of arguments. the syntax for this function declaration
func functionname (arguments ...datatype)
these functions are declared with ellipse (three dots ) in the arguments. This should be declared as last argument.
package main

import "fmt"

func IncrementAndDecrement(nums ...int) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}
func main() {
 res := IncrementAndDecrement(5, 5)
 fmt.Printf("%d", res)
 res1 := IncrementAndDecrement(5, 1, 7)
 fmt.Printf(" %d", res1)
}
and the output is
13
The below code gives compilation error - can only use ... with final parameter in list numbs arguments are not final or last arguments of the function declaration.
func IncrementAndDecrement(nums ...int, string s) int {
 result := 0
 for i := range nums {
  result += nums[i]
 }
 return result
}

closure or anonymous functions 

Golanguage supports function declared without a name. These are called anonymous functions in other programming languages in java and javascript. closure is one type of anonyms functions that can access the variables defined outer function itself. We will see various examples of this two features Function can be used as value and assigned to variable Here function without is declared and assigned to variable, This is being called in other place using variable name with ( and )
var functionName = func() string { // this assigns anonymous function to variable
 return "testvalue"
}

func main() {
 fmt.Printf("%s", functionName())
}
output is
testvalue 
Anonymous functions with inline arguments
The above function can be written in another way by appending argument value inline using ( and )
func main() {
 //Anonymous functin assined to variable by appending argument value inline
 var functionName = func(s string) string {
  return "testvalue " + s
 }("cloudhadoop")
 fmt.Printf("%s", functionName)
}
output is
testvalue cloudhadoop
passing function as an argument
the function can also be passed as an argument to other function, In the following example, Function2 is declared with function argument This function2 is called with supplying argument
func funciton1(value int) int {
 return value * value
}
func funciton2(functionargument func(int) int) int {
 return functionargument(5) 
}
func main() {
 fmt.Printf("%d", funciton2(funciton1))
}
Output is
25
Return type as a function from other function
function declaration contains return type as anonymous function declaration function1 is declared with return type as an anonymous function with argument and return type function caller should be two parameters enclosed ( and ) separately here closure applied as accessed value1 variable inside an inner anonymous function
func function1(value1 int) func(int) int {
 var result = func(value2 int) int { return value1 + value2 }
 return result
}
func main() {
 fmt.Printf("%d", function1(4)(5))
}
Output is
9
Closure with nested function 
a function declared inside other function, outside function variables are accessed inner function nested function is declared inside the main function. fmt class is being declared in the main function and accessed inside nested function value2 is declared in the main function and being accessed in nested function
func main() {
 var value2 = 12
 var nestedFunction = func(value int) int {
  fmt.Println(value)
  return value + value2
 }
 fmt.Println(nestedFunction(6))
}
and output is
6
18

defer statement 

defer is a keyword which is used as a statement in language. Defer is used in function as its execution before function return its value. defer logic always executes before declared function returns its value. defer keyword is declared before a function is declared of a outer function
package main

import "fmt"

func myfunction() (value int) {
 defer func() {
  value = 25
 }()
 return value
}
func main() {
 fmt.Println(myfunction())

}
output is
25

arrays as slice of arguments 

Functions can be passed with an array as an argument, Instead of declaring an array in the function declaration, We can slice the array Function declaration accepts variable arguments using ellipse symbol function caller accepts slicing arrays like myfunction(array1...)
func myfunction(params ...int) int {
 result := 0
 for _, value := range params {
  result += value
 }
 return result
}
func main() {
 var array1 = []int{1, 2, 7}
 fmt.Println(myfunction(array1...))

}
And output is
10
Conclusion
Like every programming language, Functions are building blocks and most useful in go language. There are lot features that functions supported in this language.

Please share your valuable comment or feedback and share it Social Media .

Learn Golang tutorials - Switch case statement guide with examples

This article covers the Switch case statements with expressions and types with various syntax examples.
Learn Golang tutorials - Switch case statement guide with examples

Golang Switch case statements

Switch case is used to execute a particular code block when we have multiple code blocks based on condition. It is an alternative syntax for writing if-else block. Unlike other programming languages like Java and C+, where, the break is needed to stop its execution. Go language is automatically stopped its execution when matching case executed. Break keyword is not required.

There are two types of Switch types in Go Programming language.
  • Expression Switch - In this case, Switch expression are compared with case expressions.
  • Type Switch -Switch expressions types are compared with case expressions.

Expression Switch 

expression switch is used to compare expression with a value of case expressions.
Here is a syntax for switch case
switch (variable|boolean-expression|Integer type){
case boolean-expression | integer type
     Block of code contains statements
case boolean-expression | integer type
     Block of code contains statements
default: // default  case and it is optional
   Block of code contains statements
}
Following are the keynotes of expression switch
  • Switch executes from top to bottom, Stop its execution when a matching case occurs
  • It contains any number of case statements with each case statements contains expression and a colon.
  • the default case is optional. This will be executed when the matching case is not executed. This placed last case and break is not required 
  • Switch expression and case expression must be evaluated to the same type, Otherwise, it gives a compilation error. For example, Switch evaluates to float and case evaluates to float only. 
  • curly braces for case body is optional. 
  • if there are many matched cases, first matched cases are executed.

Example

Here is a basic example of switch case statements
In the below example, Number is declared with value 1. In the switch, number compares with the value of number against all case statements. Here cases are evaluated from top to bottom. Matched first executes its code block, In this case, 1 is matched, 1 matched is displayed to console. switch expression can be enclosed with parenthesis and without parenthesis - both switch number or switch (number) are allowed and valid code.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
Output is
1 matched
Following is various examples of the switch case

The duplicate case with same values are not allowed 

In the below code, the duplicate case is declared with the same values - case 3 is declared two times. The compiler gives compilation error - duplicate case 3 in switch previous case at
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 3:// duplciate case is declared here - Compilation error
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}

Default case when the matched case is not declared

what will happens when the number is given as 10? to the same example. the matching case for the number is not defined in code, hence default case will be executed and printed default matched text is printed to the console output

package main

import "fmt"

func main() {
 number := 11
 switch number {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
of the above program is
default matched
The default case is an optional case. It is advisable to be last case statement but there is no effect on the way of switch case functionality

Switch with No expression or Condition 

The switch can also be declared without expression or condition. When no expression is used, It treats switch case as a true value. switch with no expression or condition or value always equals to switch true. case expression always should be expression or condition
package main

import "fmt"

func main() {
 number := 11
 switch {
 case number > 10:
  fmt.Println("Number is greater than 10")
 case number > 20:
  fmt.Println("Number is greater than 20")
 case number > 30:
  fmt.Println("Number is greater than 30")
 default:
  fmt.Println("default matched")
 }
}
and output of the program code is
number is greater than 10
when no expressions in the switch case, case expression must be non-constants
package main

import "fmt"

func main() {
 number := 11
 switch {
 case 1:
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
the above code is not compiled The reason is switch without expression code should have case non-constants The compilation error is invalid case 1 in a switch (mismatched types int and bool) Complete error for the command is go run filename
.\First.go:8:2: invalid case 1 in switch (mismatched types int and bool)
.\First.go:10:2: invalid case 2 in switch (mismatched types int and bool)
.\First.go:12:2: invalid case 3 in switch (mismatched types int and bool)
.\First.go:14:2: invalid case 4 in switch (mismatched types int and bool)

Switch case contains multiple expressions or conditions 

Case contains multiple expressions separated by comma symbol


package main

import "fmt"

func main() {
 weekday := "tuesday"
 switch weekday {
 case "monday", "tuesday", "wednesday", "thursday", "friday":
  fmt.Println("Working Day")
 default:
  fmt.Println("Not working day: weekend")
 }
}
The output of the above program is
Working Day
the above code, Code cheks weekday is working day or not. the case is defined with multiple strings which are declared as working days.

fallthrough keyword in the case body 

Normally when the matched case is found with switch case, the code inside matched case executes and control exit from switch case. fallthrough statement is special functionality used to jump the control from next immediate available case fallthrough is a keyword in golang, hence it will not be used as variable or function names.
package main

import "fmt"

func main() {
 number := 1
 switch number {
 case 1:
  fmt.Println("1 matched")
  fallthrough
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
1 matched
2 matched
3 matched
without fallthrough statement, The output is
1 matched
In the above code, Control comes to the matched case, case 1 is matched, fallthrough statement exists, Control transfer to the first line of code of next case 2 statement. fallthrough statement is the last statement inside the code of case statement. if you declare fallthrough as not line of code, It gives compilation error the following code gives fallthrough statement out of place
func main() {
 number := 1
 switch number {
 case 1:
  fallthrough // not allowed as first or middle - compilation error
  fmt.Println("1 matched")
 case 2:
  fmt.Println("2 matched")
  fallthrough
 case 3:
  fmt.Println("3 matched")
 case 4:
  fmt.Println("4 matched")
 default:
  fmt.Println("default matched")
 }

switch case floating values

Switch and case expression can also be declared with floating values and it is valid code. Other languages are not supported to be used in switch case expressions. Golang has no issues with it. The below program contains floating numbers, matched case with floating values are evaluated. In this case, 6.5 matched is printed to the console.
func main() {
 number := 6.5
 switch number {
 case 5.5:
  fmt.Println("5.5 matched")
 case 6.5:
  fmt.Println("6.5 matched")
 default:
  fmt.Println("default matched")
 }
}
and output of the above program is
6.5 matched 

switch case String literals 

allowed Expression can also be string literals. String literals are a group of characters enclosed in double quotes. It checks the exact match of string literals. In the below code, Case contains String literals, Switch expression contain string variable, the Matched case is evaluated, and output is TWO matched
func main() {
 number := "TWO"
 switch number {
 case "ONE":
  fmt.Println("ONE matched")
 case "TWO":
  fmt.Println("TWO matched")
 default:
  fmt.Println("default matched")
 }
}
The output of the above program is
TWO matched

Break statement to exit from the loop

break statement can also be used in switch cases. It is used to exit from the inner loop inside the switch. When you are using for loop with switch case, break keyword will be used. Here is an example without break statement for loop iterates with 3 values, Inside the loop, Switch is declared, and matched cases values are printed.


func main() {
 var numbArray = [3]int{1, 2, 5}
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched
2 matched
Now we will rewrite the code with break and named labels in switch case statements In the below loop code, for the first matched case, break label is used, It exists from the named label and output only 1 matched case.
func main() {
 var numbArray = [3]int{1, 2, 5}
MyLoopName:
 for _, numb := range numbArray {
  switch numb {
  case 1:
   fmt.Println("1 matched")
   break MyLoopName
  case 2:
   fmt.Println("2 matched")
   break
  case 0:
   fmt.Println("0 matched")
  }
 }
}
Output is
1 matched

Functions can be used as Expression in switch and case 

the expression can also be a function named calls and valid in go language Following is an example for functions in switch expressions. In the below example, the Simple function is declared, It just returns the passed parameter no value is processed. This is being used in Switch expression as well as case expression.
func myfunction(parameter string) string {
 return parameter
}
func main() {
 switch myfunction("mon") {
 case myfunction("mon"), myfunction("tue"), myfunction("wed"), myfunction("thu"), myfunction("fri"):
  fmt.Println("working day")
 case myfunction("sat"), myfunction("sun"):
  fmt.Println("Not working day: weekend")
 }
}
Output is
working day

Type Switch

Type switch is mostly used in interfaces Type switch is do multiple type checking and evaluates first matched type case. These are mostly used to type assertions Difference between the expression switch and type switch, the Normal switch is compared values with case values. Type switch compares types not values with case types.
Here is a syntax for type switch
switch variable.(type){
case type:
  Code block statements
case type:
  code block statements
default:
  code block statements
}
variable.(type) represents type assertion that contains specific type as "type" Following are key points of the type switch expressions
  • You can define any number of case statements
  • The expression defined in this type always of interface type variable
  • Like a normal switch expression, Default is also optional and last declared, the break is not required.
  • Switch type and case type must be of the same type or follows is-a principal.
  • When switch type and case type is matched, matched case code body is executed, exit from the switch code, Break is not required 

switch type assertion interface example

 In the below example, interface() is an empty interface type that can accept any type of value.
package main

import "fmt"

func main() {
 var interfaceDemo interface{} = 45

 switch interfaceDemo.(type) {
 case string:
  fmt.Println("string type matched")
 case int:
  fmt.Println("int type matched")
 default:
  fmt.Println("default type matched")

 }
}
The output is
int type matched

a type switch struct example 

Type switch case can be used with struct data types. struct types contain custom type which contains multiple types.
package main

import "fmt"

func main() {
 type Employee struct {
  ID   int
  Name string
 }
 emp := Employee{1, "Kiran"}
 var empInterface interface{}
 empInterface = emp
 switch empInterface.(type) {
 case Employee:
  fmt.Println("Employee type matched")
 case string:
  fmt.Println("String type matched")
 default:
  fmt.Println("default type matched")
 }
}
output
Employee type matched
Please share your valuable comments and feedback:) and share it on facebook

Tuesday, November 13, 2018

Learn Golang Tutorials - foreach loop with range keyword examples

In this blog post, We are going to learn for each loop with range in go language with example
for each loop in golang to iterate array,strings,unicode chars,maps

Golang for each loop 

the foreach loop is a for loop with range keyword. It is used iterate each element from Array, Slice, Map, and Strings. This is always useful to iterate the elements of a data structure without getting the length of data structure Syntax of the for with range loop is as follows
for key, value := range collection{
// body
}
During an iteration of the collection, each iteration contains key or index, value or element at index.
Few key points for loop with range keywords
  • This is used to iterate elements of a collections types
  • Each iteration data contains two parts, One is key or index, the second is a value or an element at index 
  • The iterated elements order is not ordered or preserved in a collections
  • use the key as _ for retrieving values during array iteration
  • for array and slice, the first element is an index, the second value is an element at index position for each iteration
  • if the array or slice is empty, It returns nothing

For each array range iteration example

Below is an example for iterate the array of numbers
package main

import "fmt"

func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for key, value := range numbers {
		fmt.Printf("%d = %d\n", key, value)
	}
}
Output is
0 = 6
1 = 9
2 = 3
For array iteration, the First variable for iteration value can be passed _
func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for _, value := range numbers {
		fmt.Printf("%d ", value)
	}
}
Output is
6 9 3
another way is using the index parameter of iteration value to traverse the elements of the array
func main() {
	// Iterate numeric array
	numbers := [3]int{6, 9, 3}
	for i := range numbers {
		fmt.Printf("%d ", numbers[i])
	}
}
Output is
6 9 3

Iteration examples with range keyword

The below example covers the following things
  • Iterate elements in Numeric Array 
  • Loop elements in String Array 
  • Iterate elements in Unicode characters of a string
  • Iterate elements in Map
package main

import "fmt"

func main() {

	// Create Numeric array
	numbers := [3]int{6, 9, 3}
	// Iterate numeric array
	for key, value := range numbers {
		fmt.Printf("%d = %d\n", key, value)
	}
	// Create String array
	strs := [3]string{"one", "two", "three"}
	// Iterate String array
	for key, value := range strs {
		fmt.Printf("%d = %s\n", key, value)
	}

	/* create a map*/
	emps := map[string]string{"1": "John", "2": "Franc", "3": "Kiran"}

	/* Iterate map using keys*/
	for emp := range emps {
		fmt.Println("Emp Id: ", emp, " Name: ", emps[emp])
	}
	/* Iterate Unicode charactes of a String*/
	for index, character := range "本語日" {
		fmt.Printf("%#U  position %d\n", character, index)
	}

}
The output of the above program code is
0 = 6
1 = 9
2 = 3
0 = one
1 = two
2 = three
Emp Id:  1  Name:  John
Emp Id:  2  Name:  Franc
Emp Id:  3  Name:  Kiran
U+672C '本'  position 0
U+8A9E '語'  position 3
U+65E5 '日'  position 6

Monday, November 12, 2018

Learn Golang tutorials - For Loop beginner guide with examples

This blog post covers the For Loop with a break, continue, goto keywords with examples in Go Language.
Golang - for loop, break,continue,goto label keywords examples

Golang For loop

For loop is used to execute the code block at a specific number of times. it is one more control structure type in go language. Following is a syntax of for loop
for initialization; conditional Boolean expression; increment|decrement {
 // Code block
}
following are notes of for loop syntax
  • initialization are variables that can be declared and initialized with starting value.
  • the conditional Boolean expression is that results true or false always, if it is true, code block or one iteration executes. Otherwise, the controller will terminate from loop execution. These expressions are created using Comparing operators like ==,!=,= etc.. Expression can be single or multiple. Multiple expression can be combined using logical operators -  &&,||,!
  • Increment/decrement is to change the variable value after code block is executed. parenthesis is not required for this loop.
Here is an example for For Loop. This loop executes 10 times and prints each iteration variable value.
package main
import "fmt"
func main() {
 for i := 0; i < 10; i++ {
  fmt.Print(i)
 }

}
The output of the above code is
0123456789
initialization and increment/decrement are not required of a for loop Here is an example without initialization variable
func main() {
 i := 0
 for ; i <= 10; i++ {
  fmt.Print(i)
 }
}
Here is an example without increment/decrement variable
func main() {
 i := 0
 for i <= 10 {
  fmt.Print(i)
  i++
 }
}
The output of the all the above code is
0123456789

Break statement 

the break is a keyword in golang. It is used to terminates the for loop execution, Controller will be delegated to the next statement after for loop code. This can also be used in a nested loop to terminates the nested loop execution and the controller executes outside loop normal Syntax is
break;
Here is an example of for loop with break statement In this example, Loop executes from 1 to 10 iterations, During 5th iteration, break keyword terminates from For loop execution, and executes the statements after loop code.
func main() {
 i := 0
 for i <= 10 {
  fmt.Print(i)
  if i == 5 {
   break
  }
  i++
 }
 fmt.Print("End")
}
The output of the above program is
012345End
break keyword can also be used with label statements which break the termination Here is an example break label statements
package main

import "fmt"

func main() {
LOOPSECTION:
 for i := 1; i <= 10; i++ {
  if i%2 == 0 {
   break LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
Output is
1End

Continue statement

Continue is a keyword which is used to continue the next loop execution after stop the current execution here is syntax
continue;
Here is an example of for loop with continue keyword usage
func main() {
 for i := 1; i <= 10; i++ {
  if i%2 != 0 {
   continue
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
Output the code is
246810End
continue keyword can also be used with label statements which jump the execution from the current execution
func main() {
LOOPSECTION:
 for i := 1; i <= 10; i++ {
  if i%2 == 0 {
   continue LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")
}
Output is
13579End

goto label Statement 

goto is a keyword in go language. it is used to jump the iteration to the label statements without checking condition. goto is not recommended to use in any language. The syntax is as follows
goto LabelName;

LabelName: code;
Here is an example for goto label statement of for loop for loop iterates from 1 to 10, When 5 iteration is encountered, It skips the 5th value to console.
func main() {
 i := 1
LOOPSECTION:
 for ; i <= 10; i++ {
  if i == 5 {
   i++
   goto LOOPSECTION
  }
  fmt.Print(i)
 }
 fmt.Print("End")

}
The output of the above code is
1234678910End

Learn Golang tutorials - While loop beginner guide with examples

This blog post covers learn while and do while loop guide with examples in Golang.
Golang - while or do while loop examples

Golang while loop 

Like other programming languages, There is no while loop or do while loop in go language. Instead, it provides for loop with a boolean expression. This will executes code of block multiple times until conditional expression is true. if conditional expressions result false, It exits the control from the loop block. Each iteration is executed once the condition is true. Conditional expressions are evaluated and executed before each iteration. Here is the syntax for the while loop alias for loop with a boolean expression
for boolean-expression {
// code block
}
boolean-expression results true of false always. These expressions are created using comparison operators. multiple-expression can also be defined using logical operators. Infinite for loop code block executes infinite times. This conditional boolean expression will never be true. We can write in multiple ways using for expression for without boolean expression. In this case, Condition expression is omitted
func main() {
 number := 1
 for {
  number++
  fmt.Println(number)
 }
}
or other way using for with true boolean values. The boolean expression is always true.
func main() {
 number := 1
 for true {
  number++
  fmt.Println(number)
 }
}
The above programs return the output as follows
1
2
3
...
Infinite times

while loop sleep - wait a time before looping 

while loop alias for loop used to loop the code block. we are going to use sleep function in time package waits for controller before looping code block. time is a builtin package as part of golang. This package provides different functionalities dealing with time-related things. package time inbuilt sleep function waits 300 milliseconds for each iteration during an infinite loop
package main

import (
 "fmt"
 "time"
)

func main() {
 number := 1
 for true {
  number++
  fmt.Println(number)
  time.Sleep(300 * time.Millisecond)// control stops here and sleeps for 300 milli seconds

 }
}

Learn Golang Tutorials - if else statement examples

In this blog post, we are going to learn control flow structures - if-else statements in Go Language with examples.
Learn Golang Tutorials - if else statement examples

golang if statements

Like many programming languages, Go Language provides control structures for decision making. if and else statements are one of type.if statements are used to execute a piece of code based on the conditional expressions, if the condition is satisfied, code block will be executed.
This blog post covers examples and syntaxes for the following things
  • simple if statements
  • if shorthand statements
  • if else statements
  • if else nested statements
Here is Syntax for if statements in Golang
if(Conditional Expression) {
Code Block
}
conditional expression is evaluated and always results true or false. the expression can be made of simple boolean values or complex expression created using comparison operators ==,= or !=. the expression can be single or multiple. Multiple expressions are joined with logical operators like &&,||,! operators. Conditional Expressions are not required to be enclosed with parenthesis, But code block must be enclosed with curly braces In golang, curly braces are required for code block which contains sing statements.

simple if statement 

This example evaluates the expression if the expression is true, the code block is executed and return "Event Number test passed " to console The below is an example for simple if the conditional expression
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable%2 == 0 {
		fmt.Printf("Event Number test passed ")
	}
}
the output of the above code is
Event Number test passed 
below example code give a compilation error, The reason is if statements code block has no curly braces, It throws syntax error: unexpected newline, expecting { after if clause
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable %2 == 0 
		fmt.Printf("Event Number test passed ")
}
Multiple expression can be combined with logical operators
var number = 2
if  number >= 1 && age <= 10 {
	fmt.Println("Number is between 1 to 10")
}	

if with shorthand statements 

In this, if statement always contains the shorthand statements, before going control to the conditional expression. shorthand statements can contain variable declaration and the scope of the variable are the scope of this block only
func main() {
	var numerVariable = 10
	if result := numerVariable % 2; result == 0 {
		fmt.Printf("Event Number test passed ")
	}
}
if you include shorthand syntax in if statements, the parenthesis is not required. It gives compilation error - syntax error: unexpected :=, expecting ), if parenthesis is in shorthand syntax
func main() {
	var numerVariable = 10
	if (result := numerVariable % 2; result == 0) {
		fmt.Printf("Event Number test passed ")
	}
}

if and else statement 

This syntax contains else block for if statement. if conditional expression is true if the block is executed, otherwise else block is executed.
if (conditional expression){
if true this block of code is executed
}else{
if false block of code is executed
}
example for if else statement
package main

import "fmt"

func main() {
	var numerVariable = 10
	if numerVariable%2 == 0 {
		fmt.Printf("Event Number if block ")
	} else {
		fmt.Printf("Odd Number else block")

	}
}
the output of the above program is
Event Number if block

multiple if else - nested if statements 

if the statement contains if else statements that contain chains of if else statements
package main

import "fmt"

func main() {
	var numerVariable = 1001
	if numerVariable <= 100 {
		fmt.Printf("Number is less than 100")
	} else if numerVariable > 100 && numerVariable <= 1000 {
		fmt.Printf("Number is greater than 100 and less than 1000")
	} else { // else statements
		fmt.Printf("Number is greater than 1000")
	}
}
The output of the above program is
Number is greater than 1000
Compilation error if any line breaks before else statement as like below example the below program gives syntax error: unexpected else, expecting }
func main() {
	var numerVariable = 1001
	if numerVariable <= 100 {
		fmt.Printf("Number is less than 100")
	} else if numerVariable > 100 && numerVariable <= 1000 {
		fmt.Printf("Number is greater than 100 and less than 1000")
    } 
    else { // else statements
		fmt.Printf("Number is greater than 1000")
	}
}

Learn Golang Tutorials - Data types Basic Guide with examples

In this blog post series, We are going to learn basic inbuilt predefined data types in golang tutorials with examples.
Learn Golang Tutorials - Data types Basic Guide

Go language data types

Go is a modern opensource programming language from Google.
It is a static type language which means type checking will be done at compile time. Variable can be declared a type or inferred from type inference.
datatypes in golang define the same type of data that can be used to allocates memory size for storing the particular value.

It has several built-in types similar to any programming language.

There are several data types that can be categories based on similar data types
  • Numeric types - This represents numeric numbers which can be divided into Integers, Floating and other types
  • String types - This represents a group of characters
  • Boolean types - It represents boolean values - true or false
  • Custom Data types - It Contains different types like pointers, Array, Struct, Union, Map, and Channel types

Integer data types

These are used to store the positive and negative numbers including zero. It has various types based on size and signed types.

Signed Integer types

signed integer allows the values positives and negatives including zero. it also has int data type which changes based on machine environment
Inbuilt Type Size in bytes Range of values
int8 1 Byte -128 to 127
int16 2 Bytes -32768 to 32767
int32 4 Bytes -2147483648 to 2147483647
int64 8 Bytes -9223372036854775808 to 9223372036854775807

Unsigned Integer types 

Unsigned integer allows the values positive values including zero. It does not allow negative values
Inbuilt Type Size in bytes Range of values
uint8 1 Byte 0 to 255
uint16 2 Bytes 0 to 65535
uint32 4 Bytes 0 to 4294967295
uint64 8 Bytes 0 to 18446744073709551615
Other Numeric types 
There are other numeric types byte etc..


Inbuilt Type Size in bytes Range of values
byte 1 Byte same as uint8
rune 2 Bytes int32
uint 4 Bytes or 8 bytes based on Environment
int 4 Bytes or 8 bytes/td>Based on Environment
uintptr 4 Bytes or 8 bytes/td>unsigned int to store pointer bits

Example

This example covers the following things
  • Type inference example
  • The octal number always prefixed with 0
  • Hexadecimal number prefixed with 0x
This has no char data type in java language. byte and rune are used to represent char types. a byte represents characters in ASCII values. rune represents in UNICODE character in the UTF-8 format
package main
import "fmt"
func main() {
 var int16Variable int16 = 12
 var intVariable = 85 // Type inference example
 var uintVariable uint = 40
 var hexVariable = 0xBC  
 var octalVariable = 013 
 fmt.Printf("%d, %d, %d, %#x, %#o\n", int16Variable, intVariable, uintVariable, hexVariable, octalVariable)
 var byteVariable byte = 'C'
 var runeVariable rune = 'a'
 fmt.Printf("%c - %d and %c - %U\n", byteVariable, byteVariable, runeVariable, runeVariable)

}
The output of the above program is
12, 85, 40, 0xbc, 013
C - 67 and a - U+0061

Floating numeric types 

Like any programming language, These are used to represents numbers with decimal values(3.21) for example, when you declared float value like this, compiler infer the type as float64. The default type is float64
var floatVariable = 47895.587
And also complex data type default type is complex128. type inference applied on complex number also complex128
var complexVariable = 1 + 6i  
Type Size in bytes Description
float32 4 Bytes IEEE-754 Floating numeric values
float64 8 Bytes IEEE-754 Floating numeric values
complex64 8 bytes Complex numbers with float32 real and imaginary parts
complex128 4 Bytes or 8 bytes/td>Complex numbers with float64 real and imaginary parts

Boolean Datatypes 

Go language has data type bool to store boolean values. It has predefined values true or false

var boolVariable = true
var booleVariable1 bool = false

String Datatype 

The string is a group of characters. Characters in golang treated as bytes. The string can be declared using double quotes or backticks. Double quotes enclosed strings cannot be multiple lines but contains newline characters \n. Backticks enclosed string can contain multiple lines
var str1 = "Cloud Hadoop Blog"

var str2 = `This is programming blog for 
   full stack technolgies`
 

Java Unique Number Generator - UUID or GUID with examples

In this blog post, We are going to learn java Unique Number Generator-  UUID or GUID with examples.

You can also check my previous articles on 
There are two types of unique identifiers. UUID is a universally unique identifier, GUID is a globally unique identifier, The difference between UUID and GUID, Both are returning 126 bits,
GUID is Microsoft implementation of UUID functionality. Both generates 16 bytes hexadecimal separated by a hyphen in four groups.
UUID or GUID can be used in the following in real time

  • Used to represent a primary key in a database table
  • can be used as Session ID in web applications, Transaction Id in enterprise applications
  • Can also be used as unique identifier for doing CRUD operations in  REST API applications
  • Represents to identify big data spread across multiple servers
  • Naming static resources for storing and retrieving files.
Java provides java.util.UUID class for providing UUID implementation in java

java.util.UUID class 

This class is specified as an immutable universally unique identifier (UUID).  This class has following notes about it
  • Generates 128 bit or 16 bytes that contains hexadecimal values 
  • Implements Serializable, Comparable interfaces
  • Extends Object class.
There are multiple variants for creating UUID. It has methods for operating Leach-Salz variant. but it has a constructor to support all variants
Constructor
UUID(long mostSigBits, long leastSigBits)
It has only one constructor which takes two parameters to create a new UUID mostSigBits - most significant bits 64 bits of UUID
leastSigBits - least significant 64 bits of UUID
UUID has four types of versions
  • Version 1 represents time-based - UUID V1 
  • Version 2 represents DCE security - UUID V2 
  • Version 3 represents name-based - UUID V3 
  • Version 4 represents Random generated - - UUID V4

Example

The below example generates UUID V4 string
import java.util.UUID;

public class UUIDDemo {

 public static void main(String[] args) {
  
  UUID uuid = UUID.randomUUID();
  String uuidString = uuid.toString();
  System.out.println(uuid.variant());  // 2
  System.out.println(uuid.version());  // 4
  System.out.println(uuidString);  //3d795ac3-2cea-4ed2-92d8-3d71a2539cf2

 }

}

java-uuid-generator maven 

In maven applications, java-uuid-generator is a dependency from com.fasterxml.uuid. This is a java library for generating UUID with all versions

<dependency>
    <groupId>com.fasterxml.uuid</groupId>
    <artifactId>java-uuid-generator</artifactId>
    <version>3.1.5</version>
</dependency>
The below example generates the following thins

  • UUID V1 Generation using timebase generator 
  • UUID V3 Generation using UUID.nameUUIDFromBytes method as well as name based
  • UUID V4 Generation using randomBasedGenerator 
  • UUID V5 Generation using SHA digester 
import java.util.UUID;

import com.fasterxml.uuid.Generators;

public class HelloWorld {
 public static void main(String[] args) {
  // UUID V1 generation
  UUID v1 = Generators.timeBasedGenerator().generate();
  System.out.println("UUID V1 value: " + v1.toString());
  System.out.println("version  : " + v1.version());
  System.out.println("variant  : " + v1.variant());
  // UUID V3 generation
  //  create byte array and initialize it
  byte[] byteArray = { 0, 1, 4 };
  // Create uuid from byte array
  UUID v3 = UUID.nameUUIDFromBytes(byteArray);
  System.out.println("UUID V4 value: " + v3.toString());
  System.out.println("version  : " + v3.version());
  System.out.println("variant  : " + v3.variant());
  // UUID V4 generation
  UUID v4 = Generators.randomBasedGenerator().generate();
  System.out.println("UUID V4 value: " + v4.toString());
  System.out.println("version  : " + v4.version());
  System.out.println("variant  : " + v4.variant());

  // UUID V5 generation
  UUID v5 = Generators.nameBasedGenerator().generate("cloudhadoop.com");
  System.out.println("UUID V5 value: " + v5.toString());
  System.out.println("version  : " + v5.version());
  System.out.println("variant  : " + v5.variant());


 }
}
Output of the above program code is
UUID V1 value: 04272c28-e69d-11e8-be73-df7930994371
version  : 1
variant  : 2
UUID V4 value: be489ef3-af30-3d20-b50a-5c504ecc5294
version  : 3
variant  : 2
UUID V4 value: 1c4e3ff8-bf58-4081-8e3f-f8bf58908109
version  : 4
variant  : 2
UUID V5 value: cdecd331-e6c2-5e7f-ad1d-3ee766052560
version  : 5
variant  : 2

How to create UUID from a String 

UUID class provides fromString() method which generates UUID from a given string. This is an example for Converting String to UUID. This method throws Exception in thread "main" java.lang.IllegalArgumentException: Invalid UUID string: 150e064ff8d6, if string is not 16 bytes in length

import java.util.UUID;

public class fromStringExample {

 public static void main(String[] args) {

  UUID uuid = UUID.fromString("d4578015-0e06-4ff8-9780-150e064ff8d6");
  System.out.println("UUID  value: " + uuid.toString());
  System.out.println("version  : " + uuid.version());
  System.out.println("variant  : " + uuid.variant());
 }

}
The output of the above code is

UUID  value: d4578015-0e06-4ff8-9780-150e064ff8d6
version  : 4
variant  : 2
UUID class methods

UUID class methods

  • clockSequence - this method returns clock sequence for given UUID. It throws Exception in thread "main" java.lang.UnsupportedOperationException: Not a time-based UUID.if it is not time-based UUID version
  • getLeastSignificantBits - This method returns least significant 64 bits of given UUID
  • getMostSignificantBits() - This method returns m significant 64 bits of given UUID
  • nameUUIDFromBytes(bytearray) - this method returns UUID V3  for given byte array
  • node()- This method return node value of given UUID 
  • timestamp() - This return timestamp of given UUID
  • randomUUID - This static method generates random UUID

Other UUID libraries 

There are various UUID libraries available for java language-markup

Learn Golang tutorials - Variables starter guide with examples

In this blog post, It covers the Golang Tutorials variables  guide with examples
Learn Golang tutorials - Variables starter guide with examples

Golang Tutorials variables

Variables usage in go language is same as like another programming language like java. Variables are the name assigned for a space in memory that saves the values.  Variables of different types. Based on each type, memory size will be accommodated

Variables name can be named using letters, digits and underscore characters. Go lang is case sensitive so that upper and lower names are different. Variables in go language are declared using var keyword. before using any variables, you need to first declare it.

Variable declaration

Variables can be declared using var keyword, Once variable is declared, the compiler allocates memory based on the type of the variable. The variable declaration contains three parts 1. var keyword 2. variable name 3. type of variable
var variablename(s) variableType
can be a single variable or multiple variable types are predefined inbuilt types or custom types. Inbuilt types can be byte, int and float32 and string. Following are a various way of variable declaration examples
initialized variables
It can be declared and initialized with values. This can be done in many ways
The following example explains converting different types
package main
import (
	"fmt"
)
func main() {
	m := 42
	n := float64(2.0)
	var o float64 = float64(25.2)
	fmt.Println(m)
	fmt.Println(n)
	fmt.Println(o)

}
Output is
42
2
25.2
Multiple variable declarations 
Here multiple variables can be declared in a single line of the same type
var  a,b,c int;
var (
  m = 1
  n = 20
  o = 3
)
Short variable declarations 
variables can be declared and assigned with initial values. Multiple variables can be declared in a single line and readability is improved and code lines reduced
package main
import "fmt"
func main() {
	var m, n int = 10, 20
	fmt.Println(m, n) // 10 20
}

Global Scope 

variables declared outside function blocks and at the package level. This variable can be accessed across all functions declared in the program. These variables can exist as long as the program is running
package main

import "fmt"

//Global Variables Declaration
var globalVariable="Hello";
func main() {
	fmt.Println(globalVariable);

}
and output of the above code is
Hello

Local Scope 

variables declared inside a function or block of a code is called local variable. The variables cannot be accessed outside the function
package main
import "fmt"
func main() {
	//Local Variables Declaration
    var localVariable="this is test variable";
	fmt.Println(localVariable);

}
and output of the above code is
this is test variable 

Variables default values 

variables are assigned with a default value when variables are assigned with initial values zero for number types like Int, Float etc.. false for Boolean types empty string - "" for Strings


package main

import "fmt"

func main() {
	var intVariable int32
	var floatVariable float32
	var booleanVariable bool
	var strVariable string
	fmt.Printf("%v %v %v %q\n", intVariable, floatVariable, booleanVariable, strVariable) // output 0 0 false ""

}

type inference 

type inference is called When a variable is declared without the type of the variable. variable type can derive the type from the right-hand side of the value. inference can be applied to variables and constants Below example descript using variable expression using = and := operators
package main
import "fmt"
func main() {
	var k int
	l:=k
	var m = 42 
	var n = false 
	p:=3.2 // constant 
	fmt.Printf("variable k datatype is %T\n", k)
	fmt.Printf("variable l datatype is %T\n", l)
	fmt.Printf("variable m datatype is %T\n", m)
	fmt.Printf("variable n datatype is %T\n", n)
	fmt.Printf("variable p datatype is %T\n", p)

}
the output of the above program code is
variable k datatype is int
variable l datatype is int
variable m datatype is int
variable n datatype is bool
variable p datatype is float64

Constants declaration 

Constants are like variables which can not be changed its value once the value is assigned. whereas a variable can be changed. Constants can be declared using := syntax. const can be applied to all types of variables like boolean, strings and numeric types
package main
import "fmt"
func main() {
	const str = "kiran"
	fmt.Println("Hi", str) // Hi kiran
	const booleanValue = true
	fmt.Println(booleanValue) // true
}

How to find a memory or address location of a variable ie variable pointer reference memory

memory for variables in golang can be referenced using  & variable name - ampersand variable. 
  • & the variable is a pointer of a variable which prints memory location of the variable 
  • *& the variable is a value of a variable at memory location
This example prints the pointer of a variable
package main
import "fmt"
func main() {
   var m int
    fmt.Println("memory location for m :", &m, "variable value is ", *&m)
    n:= 15
    fmt.Println("memory location for n :", &n, "variable value is ", *&n)
}
Output of the above code is
memory location for m : 0x416020 variable value is  0
memory location for n : 0x416024 variable value is  15

Learn Golang tutorials - Install and setup Go language on Windows

In this blog post, We are going to learn an easy way to install go language on windows.
Golang installation on windows

Go Language installation 

Go is a modern popular opensource programming language. Go language is developed by Google. It provides binary versions for Windows, MacOS, and Linux officially. If you want to install different environment, You can get the source code and built it to your platform.
Go language provides the following binaries for installation on different environments
  • Windows
  • Apple MacoOS
  • Linux
  • Ubuntu

Installation and Setup on Windows

First get the binary installer for windows ie MSI file from and download it. It downloads MSI file

Once the download is completed, Install MSI file and select A:\Golang location  follow the next steps

Next step is to configure environment variables

Configure Environment Variables

Go to My Computers or This PC --> properties --> Advance System Settings --> Environment Variables, Create a System variable or environment variable GO_ROOT
give the value of  GO_ROOT to A:\Golang folder
Next, configure GO_ROOT to PATH variable ie set PATH to %PATH%\%GO_ROOT%\binary
This installs the Go Language successfully

Check Golang Installation 

To check the installation, first Open command line shell and give "go version" command, This gives go language version correctly

C:\>go version
go version go1.11.2 windows/amd64

C:\Users\Kiran>go env
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\Kiran\AppData\Local\go-build
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=C:\Users\Kiran\go
set GOPROXY=
set GORACE=
set GOROOT=A:\Golang
set GOTMPDIR=
set GOTOOLDIR=A:\Golang\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\Kiran\AppData\Local\Temp\go-build682765038=/tmp/go-build -gno-record-gcc-switches

Create a First sample Program 

using any IDE or editor, Write the first program and save this file as "First.go" package main
package main
import "fmt"

func main() {
    fmt.Printf("Hello, World")
}
To compile First.go file, Use go build command

A:\Golang\work>dir
 Volume in drive A is Work
 Volume Serial Number is C682-8F53

 Directory of A:\Golang\work

12-11-2018  14:54    <DIR>          .
12-11-2018  14:54    <DIR>          ..
12-11-2018  14:49                83 First.go
               1 File(s)             83 bytes
               2 Dir(s)  125,885,014,016 bytes free

A:\Golang\work>go build First.go

A:\Golang\work>dir
 Volume in drive A is Work
 Volume Serial Number is C682-8F53

 Directory of A:\Golang\work

12-11-2018  14:54    <DIR>          .
12-11-2018  14:54    <DIR>          ..
12-11-2018  14:54         1,969,152 First.exe
12-11-2018  14:49                83 First.go
               2 File(s)      1,969,235 bytes
               2 Dir(s)  125,883,043,840 bytes free

A:\Golang\work>
Execute the First.exe file by following command

A:\Golang\work>First.exe
Hello World 

Sunday, November 11, 2018

Learn javascript Array concat method with example

This blog post covers how to combine/join/merge arrays in javascript with inbuilt concat method.
Learn javascript Array concat method with example

Array concat method


This method is used to join or concatenation the one or more arrays and returns the final array. This method returns new array not modifies the existing array.
new array contains the merge of new arrays by order of elements in an array
Syntax

thisarray.concat(List of arrays)
Parameters are a list of arrays ie zero or more array.
The output is returned a new array

Merge arrays using Concat Example 

This is an example for merging arrays using ES5 using Array.concat

var arrayone = ['one', 'two', 'three'];
var arraytwo = ['four', 'five', 'six'];
console.log(arrayone.concat(arraytwo));
// ['one', 'two', 'three','four', 'five', 'six'];

How to merge/join two or more arrays in javascript 

This is an example for merging the arrays without omitting duplicate values. array concat method takes one or more arrays and joins with original array and returns new array. Original Array is not modified There is no inbuilt function to remove duplicate elements. You can iterate the array and do the manipulation to remove duplicates


var one = ["id","1","name","kiran"]
var two = ["id", "2", "name", "john"]
var three = ["id","1","name","kiran"]

var result = one.concat(two,three)
console.log(result);
// ["id","1","name","kiran","id", "2", "name", "john","id","1","name","kiran"];
The same can be done using ES6 array destructing using spread Operator .
const result = [...one, ...two,...three];
Or you can also Lodash or underscore utility libraries to do the same with third-party libraries

Nested array Concat example

 nested arrays are array within the array which can be combined using concat method
var one = ["id","1","name","kiran","a1",["newname","newkiran"]]
var two = ["id", "2", "name", "john"]
var three = ["id","1","name","kiran"]

var result = one.concat(two,three)
console.log(result);
// ["id","1","name","kiran","a1",["newname","newkiran"],"id", "2", "name", "john","id","1","name","kiran"];

Learn javascript math object - mathematical functions with examples

In this blog post, we are going to cover the javascript inbuilt mathematical functions library with examples.
Learn javascript math object - mathematical functions with examples

javascript math object 

Math is a javascript inbuilt object, and it contains various utility mathematical functions. As every programming language provides mathematical operations as part of programming language.
It contains multiple functions and constants and properties.

Constants and properties

The following are constants declared in Math Object in javascript
  • Math.E -  it returns natural base algorithm  - Approximate value is 2.718
  • Math.LN2 - logarithmic  of base 2 -  0.693
  • Math.LN10 -  logarithmic of base 10 - 2.303
  • Math.LOG2E - Log of E for base 2 - 1.443
  • Math.LOG10E -  Log of E for base 10 - 0.434
  • Math.PI -  Outputs PI value - 3.14
  • Math.SQRT1_2 -  Square root of  half of the number 
  • Math.SQRT2 -  Square root of two value

Static Inbuilt Functions

It provides various mathematical inbuilt static functions.

Math.abs() - Absolute value function

This function returns the absolute value of a given number 
The parameter is n,
if the number is greater than zero, returns the same number
if the number is zero, returns zero
if the number is less than zero, return a positive number
Math.abs(5.3) //5.3
Math.abs(-5.3) //5.3
Math.abs(null) //0
Math.abs('test') //NaN

Math.acos() - arccosine value function 

This function returns arccosine of a value. Parameter number takes a value between -1 and 1
console.log(Math.acos(0.1)) //1.4706289056333368
console.log(Math.acos(5)) // NaN
console.log(Math.acos(null)) // 1.5707963267948966

Math.acosh() - hyperbolic arc-cosine value function

This method performs hyperbolic arc-cosine and returns the value

console.log(Math.acosh(0.1)) //NaN
console.log(Math.acosh(5)) // 2.2924316695611777
console.log(Math.acosh(null)) // NaN

Math.asin(x) Math.asinh(x) functions 

  • Math.asin(x) - This method performsn arcsine of a value 
  • Math.asinh(x) - This method performs hyperbolic arcsine of a value
console.log(Math.asin(0.1)) //0.1001674211615598
console.log(Math.asin(5)) // Nan
console.log(Math.asin(null)) // 0

console.log(Math.asinh(0.1)) //0.09983407889920758
console.log(Math.asinh(5)) //2.3124383412727525
console.log(Math.asinh(null)) // 0

arctangent functions 

  • Math.atan(x) - Performsn mathmatical arctangent of avalue 
  • Math.atanh(x) - Performsn mathmatical hyperbolic arctangent of avalue Math.atan2(y, x) - hyperbolic quotient of a value
console.log(Math.atan(0.1)) //0.09966865249116204
console.log(Math.atan(5)) //1.373400766945016
console.log(Math.atan(null)) // 0

console.log(Math.atanh(12)) //NaN
console.log(Math.atanh(0.1)) //0.10033534773107558
console.log(Math.atanh(null)) // 0

console.log(Math.atan2(12,3)) //1.3258176636680326
console.log(Math.atan2(10,4)) //1.1902899496825317
console.log(Math.atan2(null,null)) // 0

Math.cbrt() - cube root calculation 

This function performs cube root of a given number
console.log(Math.cbrt(8)) //2
console.log(Math.cbrt(10)) //2.154434690031884
console.log(Math.cbrt(null)) // 0

Math.ceil() - Rounds the upper number 

This method returns the rounded the upper number

Math.ceil(0.75); //  1
Math.ceil(0.45); //  1
Math.ceil(2); //  2
Math.ceil(4.3); //  4
Math.ceil(-3.2); // -3
Math.ceil(-3.9); // 3 

Math.floor() - Rounds lowest number

This method returns the rounded the lowest number

Math.floor(0.75); //  0
Math.floor(0.45); //  0
Math.floor(2); //  2
Math.floor(4.3); //  4
Math.floor(-3.2); // -3
Math.floor(-3.9); // -4

Math.random()- Random Number Generator 

This function generates random number between 0 and 1
console.log(Math.random()) //0.044142306688350175
console.log(Math.random()) //0.5684720489854178

Math.max() - Find Maximum number

This returns maximum number from zero or more numbers.
console.log(Math.max(4,51)) //51
console.log(Math.max(1,5)) //5
console.log(Math.max(0,null,3)) //3

Math.min() - Find Miniumum number

console.log(Math.min(4,51)) //4
console.log(Math.min(1,5)) //1
console.log(Math.min(0,null,3)) //0

Math.pow() - exponent power base

This function performs exponent power base of a number

console.log(Math.pow(2,3)) //8
console.log(Math.pow(5,3)) //125

Math.round() - Round number 

This method returns the rounded of nearest number
console.log(Math.round(3.1)) //3
console.log(Math.round(-3.1)) //-3
console.log(Math.round(3.9)) //4
console.log(Math.round(-3.9)) //-4

Math.trunc() - truncate number 

This method returns the truncate number, It omits decimal values
console.log(Math.trunc(3.1)) //3
console.log(Math.trunc(-3.1)) //-3
console.log(Math.trunc(3.9)) //3
console.log(Math.trunc(-3.9)) //-3

Math.sqrt() - Square root of a number 

 This method returns the square root of a number

console.log(Math.sqrt(16)) //4
console.log(Math.sqrt(25)) //5
console.log(Math.sqrt(100)) //10
console.log(Math.sqrt(23)) //4.795831523312719

Math.tan(), Math.tanh() - tangent number 

Math.tan() - tangent of a given value
Math.tanh() - hyperbolic tangent of a given argument
console.log(Math.tan(16)) //0.3006322420239034
console.log(Math.tan(25)) //-0.13352640702153587
console.log(Math.tanh(100)) //1
console.log(Math.tanh(23)) //1

Math.sign(), Math.sin() - sign number

Math.sin() - sign of a given argument
Math.sign() - Sign of a given positive,negative or zero number

console.log(Math.sign(16)) //1
console.log(Math.sign(-10)) //-1
console.log(Math.sign(0)) //0
console.log(Math.sin(16)) //-0.2879033166650653
console.log(Math.sin(-10)) //0.5440211108893698
console.log(Math.sin(0)) //0

Wednesday, November 7, 2018

Learn Golang Tutorials - Hello World First Program example Explained

In this blog post, We are going to learn the basics of Go Language tutorial with Hello World Example.
Go Language Tutorials - First Program code

Go Language Tutorials

Go is a popular Opensource programming language released by Google. When you are learning any language, You will write a sample Hello world example.
You need the following things to write and execute the Go Program
  • Go Compiler installation
  • use any code editor like Sublimetext or Atom, Visual studio code, and write code manually like below

Hello World First Sample Program Example

Like java programming language, To run the code, you need to do following things First you need to compile the code to generate machine-readable code which runs the code

// This is sample Hello world programming
package main
import "fmt"
func main() {
    fmt.Println("Hello World Sample First  Program")
}

The above two tasks can be done in many ways in this language
  • go run command 
  • go build command
Go compile and run the program First code needs to do the compilation. the compilation is the process of converting the code into low-level machine understandable code ie assembly code. We can compile the program in many ways using go run or go build commands go run command compiles the code and run the program
go run HelloWorld.go 

Hello World Sample First  Program
Other ways is
go build HelloWorld.go
dir
HelloWorld HelloWorld.go
This command compiles the code and generates an executable file. To run the program, We need to give executable via command line
/HelloWorld
Hello World Sample First  Program
We can use for compile and running the code using either go run or go build commands This program justs prints the string to the console.

Sample program Code explanation 

Here are the main components of the first program
  • Comments Declaration 
  • package keyword
  • import package 
  • Main Function Declaration
  • println function calling
Go code can be always read from Top to Bottom and left to bottom Below will walk through the code with explanations
Comments Declaration
Comments are used to tell the developer about the line of code or a file. These are ignored by Go Compiler Execution. Like java programming language, Comments are declared with starting // In the above program first line is declared with a comment. In Go comments can be declared in two ways for code Single Line comments can be declared as like below
// This is sample Hello world program
Multiple line comments can be declared like /* comment */
/*
* Line 1 Comment
* Line 2 Comment
*/
package keyword with main 

Next line is package main which is a package declaration. package declaration always declared in Go program. Packages are useful to group the code under a single name and can be reusable package main is required for standard libraries execution. The package declaration always the first line of code to be executed in Go Language. if the package is not declared in code, It gives compilation error like can't load package: a package main: expected 'package', found 'import'
can't load package: package main: 
prog.go:2:1: expected 'package', found 'import'
prog.go:3:2: expected ';', found "fmt"
import package 

Import keyword used to import other libraries packages into the current program. Here fmt standard package is imported so that all the classes and utilities can be used in the current code fmt package contains Input and output stream utilities.
Function Declaration 

Functions in any programming language are multiple statements executes in the sequential order and this can be grouped under one name. Functions takes input and executes, return output. Input can be either noting or any values and output can be nothing or any values. func is a keyword used to declare a function in golang. main is the name of the function which is always a starting point execution of go program code. functions are enclosed with braces{}. main() function always executes first when you run the code.
fmt.println() statement

Here fmt package's function is called. Function is println() which is print line to the console. This function takes string input and output the string to the standard console.

With this post, You are able to write a Sample hello world program in go language. Official website for this language is  GoLang