Saturday, March 24, 2018

Some ways to iterate set

Below are some of the ways to iterate set in java. However still lot of other ways to do the same. But these are the basic you can use at any time easily.

Let see with an example.

1. Using Iterator
2. An  enhanced for loop
3. An enhanced for loop with java8

1. Using an Iterator


import java.util.HashSet;
import java.util.Iterator;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("One");
     hset.add("Two");
     hset.add("Three");
     hset.add("Four");
     hset.add("Five");
 
     Iterator<String> it = hset.iterator();
     while(it.hasNext()){
        System.out.println(it.next());
     }
  }
}

Output:
Five
One
Four
Two
Three

Note: No ordered here.- Check output carefully.

2. An enhanced for loop


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("First");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     for (String temp : hset) {
        System.out.println(temp);
     }
  }
}

Output:

Second
Third
First
Fourth
Fifth



3. An enhanced for loop with java8


import java.util.HashSet;
import java.util.Set;

public class IterateHashSet{ 
  public static void main(String[] args) {
     // Create a HashSet
     Set<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("Test");
     hset.add("Second");
     hset.add("Third");
     hset.add("Fourth");
     hset.add("Fifth");
 
     hset.forEach(System.out::println);
  }
}

Output:

Second
Test
Third
Fourth
Fifth







Friday, March 23, 2018

Date parse with String

The syntax for far Date.parse is ,

Date.parse(str)

You should pass string as a parameter and The string format should be: YYYY-MM-DDTHH:mm:ss.sssZ.

Explanation:

YYYY-MM-DD – is the date: year-month-day.

The character "T" is used as the delimiter.

HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds.

Z is an optional denotes the time zone. A single letter Z that would mean UTC+0.

You can pass short like YYYY-MM-DD or YYYY or YYYY-MM also possible.



let ms = Date.parse('2018-01-21T13:45:50.417-09:00');

alert(ms);

Output: 
1516574750417


let date = new Date( Date.parse('2015-01-23T13:41:50.417-05:00') );

alert(date);
Output:
Sat Jan 24 2015 00:11:50 GMT+0530 (India Standard Time)







Accessing Date

Below are some of methods in java script to access date object.

1. getFullYear()
                            It will give the year in 4 digits. Some developers may get confuse with getYear() method. Please remember this was deprecated and sometimes it will give you two digit year. So it may lead you to provide wrong output.

2. getMonth()
                            It will give the month, means from 0 to 11.

3. getDate()
                            It will give the day of the month, from 1 to 31.

4. getHours() , getMinutes(), getSeconds() and getMilliseconds()

                           The above all will give you the corresponding time components.

5. getDay()
                           It will give day of the week and its starting from 0 (Sunday) to 6 (Saturday). Remember, the first day is always Sunday only.

6. getTime()

                           It will returns the timestamp for the date (milliseconds from the January 1st of 1970 UTC+0).








Creating Date and time

Date and Time in javascript is an in-built object.

Date Creation

There are some ways you able to create date. 

1. new Date() - No need to pass any arguments here. It will directly give the current date and time.



let now = new Date();
alert( now ); // display current date/time


2. new Date(milliseconds) - Pass milliseconds as argument.Here date calculation will be calculated after Jan 1st of 1970 UTC+0.


let Jan01_1970 = new Date(0);
alert( Jan01_1970 );

Output :
Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)


3. new Date(datestring) - Pass a string date here.


let date = new Date("2017-01-26");
alert(date);

Output : 
Fri Jan 26 2018 05:30:00 GMT+0530 (India Standard Time)

4. new Date(year, month, date, hours, minutes, seconds, ms) -  

The year must have 4 digits: Example 2018 2020 etc.,

The month count starts with 0 (Jan), up to 11 (Dec). Remember month starting from zero. 

The date parameter is actually the day of month, if not then 1 will be considered.

If hours/minutes/seconds/ms is absent, they could be considered as 0.



new Date(2011, 0, 1, 0, 0, 0, 0); // // 1 Jan 2011, 00:00:00
new Date(2011, 0, 1); // the same, hours etc are 0 by default







Thursday, March 22, 2018

Special Characters in Javascript

Below list of some special characters,

Character Description

\b                            Backspace
\f                            Form feed
\n                            New line
\r                            Carriage return
\t                            Tab

\uNNNN                    A unicode symbol with the hex code NNNN, for instance \u00A9 – is a
                                    unicode  the copyright symbol ©. It must be exactly 4 hex digits.

\u{NNNNNNNN}     Some rare characters are encoded with two unicode symbols, taking up to 4                                           bytes. This long unicode requires braces around it.


alert( "\u00A9" ); // It will print you copyright symbol.

alert( "\u{1F60D}" ); // It will print you smiley symbol.


All special characters should start with backslash \'.

Example I :


let specialList = "Specials:\n * One\n * Two\n * Three";

alert(specialList);
//Output: Specials:
* One
* Two
* Three



Example II :


alert( 'I\'m the World!' ); // I'm the world!

we have to prep-end the inner quote by the backslash \'. Else javascript will consider that as string end. So that we should add backslash.


Example III :


alert( `Adding backslash symbol: \\` ); // Output : Adding backslash symbol: \


To add backslash symbol in your string add lie above.





Saturday, March 10, 2018

Cloning Object in javascript

Last post , we have seen How object reference is working.But in some cases(very rare) if you want to copy exact object, means cloning, what you should do? How do you do that.

Its really a dull or tedious process.

Let see by code example,

let user = {
  name: "Kamal",
  age: 30
};

let clone = {}; // Going to clone into this empty object

// copy all properties from original into target
for (let key in user) {
  clone[key] = user[key];
}

console.log(clone);

Explanation: 

user is our original object and you have created one empty object called clone. After that , we have used for loop to iterate all the property of user object and assign the same to clone object. This loop will execute for all the properties of user. 

Checking with console log, all were copied to clone(target) object. Now you can modify your cloned object and check console. It will not affect user object. Since now cloned object is independent.

However, we have another simple way for cloning. Let see that too,

Object.assign:

Above we have used loop to iterate all the properties. So its look like some wide process. But using Object.assign() will make the process simpler.

Syntax is
Object.assign(destination[, src1, src2, src3...])

destination - Targeted object for clone
src1, src2,src3 etc., - Source object where you have to copy.

let user = { name: "Surya" };

let business = { businessType: "Cinema" };
let type = { isActor: true };

// copies all properties from business and type into user
Object.assign(user, business, type); console.log(user);

Output:
{name: "Surya", businessType: "Cinema", isActor: true}

Now everything is copied into our targeted user object.







Thursday, March 8, 2018

Objects copying by Reference

Generally, copying the object means, its not copy the exact object. Just Its copying the object reference. So exact object is different and reference is different.

We can discuss clone in next post.

Example:


let person = { name: 'Kannan', age: 21 };

let employee = person; // applied employee reference

employee.name = 'Rajni';

console.log(person.name); // Rajni

Initially person.name is Kannan but after modification by reference like employee= person, its reference will be considered and changes will reflected. please check the console log.

How do you compare ?

Once you have reference you would get a chance to check object reference. We can do it by == and === operator. However , I always use ===.



let a = {};
let b = a; // applied copy reference

alert( a == b ); // true, pointing same reference of object
alert( a === b ); // true, this also true