Sunday, 12 June 2016

Javascript - String

JavaScript strings are used for storing and manipulating text.It is an object that represents sequence of characters.

A JavaScript string simply stores a series of characters like "John Smith".
A string can be any text inside quotes. You can use single or double quotes.

Eg:
var name= "Bob";
var name= 'Bob';

String length
Below is the code for find the length of  a string

var name = "John Smith";
var val = name.length;

JavaScript String Methods
Let's see the list of JavaScript string methods with examples.

  • charAt(index)
  • concat(str)
  • indexOf(str)
  • lastIndexOf(str)
  • toLowerCase()
  • toUpperCase()
  • slice(beginIndex, endIndex)
  • trim()
charAt ()

var str="hellowworld";
document.write(str.charAt(4)); 

output: o

concat(str)

var str1="hello";
var str2="world";
var str3=str1.concat(str2);
document.write(str3); 

output: hello world

indexOf(str)

var str1="helloworld from javascript";
var num=str1.indexOf("from");
document.write(num);  

output: 11

lastIndexOf(str)

var str1="hellowworld from javascript";
var num=str1.lastIndexOf("java");
document.write(num);  

output: 16

toLowerCase()

var str1="JavaScript toLowerCase Example";
var str2=str1.toLowerCase();
document.write(str2); 

Output: javascript tolowercase example

toUpperCase()

var str1="JavaScript toUpperCase Example";
var str2=str1.toUpperCase();
document.write(str2); 

Output: JAVASCRIPT TOUPPERCASE EXAMPLE

slice()

var str1="abcdefgh";
var str2=str1.slice(2,5);
document.write(str2); 

output: cde

trim()

var str1="     javascript trim example    ";
var str2=str1.trim();
document.write(str2); 

output: javascript trim example

Wednesday, 8 June 2016

Javascript Array

JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
  1. By array literal
  2. By creating instance of Array directly (using new keyword)
  3. By using an Array constructor (using new key

1) JavaScript array literal

Below syntax is creating an array.
var arrayname=[value1,value2.....valueN];
Eg: var cars = ["Hyundai", "Volvo", "BMW"];

2) JavaScript Array directly (new keyword)

The syntax of javascript array using new keyword is as below.
var arrayname=new Array();  
Eg: var cars = new Array("Hyundai", "Volvo", "BMW");

3) By using array constructor

Here, you need to create instance of array by passing arguments in constructor .

Syntax:
var arrayname=new Array("param1","param2","param3")
Eg:
var emp=new Array("Hyundai","Volvo","BMW")



Thursday, 19 May 2016

What is Nashorn?

Brief description about Java Nashorn

               Nashorn is a Javascript Engine developed by Oracle in Java Platform. It is a part of Java 8. The Nashorn name is the German translation of rhinoceros which came from the cover of Javascript book of O'Reilly Associates. The performance of the Nashorn is several times better than the old Javascript Engine Rhino. You can invoke Nashorn from a Java application using the Java Scripting API to interpret embedded scripts, or you can pass the script to the jjs or jrunscript tool. Nashorn is the only JavaScript engine included in the JDK.




               Nashorn's goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. This Project intends to enable Java developers embedding of JavaScript in Java applications via JSR-223 and to develop free standing JavaScript applications using the jrunscript command-line tool.

               This Project is designed to take full advantage of newer technologies for native JVMs that have been made since the original development of JVM-based JavaScript which was started in 1997 by Netscape and maintained by Mozilla. This Project will be an entirely new code base, focused on these newer technologies. In particular the project will utilize the MethodHandles and InvokeDynamic APIs described in JSR-292.


Invoking Nashorn from Java Code


               To invoke Nashorn in your Java application, create an instance of the Nashorn engine using the Java Scripting API.



To get an instance of the Nashorn engine:


1. Import the javax.script package.

2. Create a ScriptEngineManager object.

                The ScriptEngineManager class is the starting point for the Java Scripting API. A ScriptEngineManager object is used to instantiate ScriptEngine objects and maintain global variable values shared by them.

3. Get a ScriptEngine object from the manager using the getEngineByName() method.

             This method takes one String argument with the name of the script engine. To get an instance of the Nashorn engine, pass in "nashorn". Alternatively, you can use any of the following: "Nashorn", "javascript", "JavaScript", "js", "JS", "ecmascript", "ECMAScript".

               After you have the Nashorn engine instance, you can use it to evaluate statements and script files, set variables, and so on. The below example provides simple Java application code that evaluates a print("Hello, World!"); statement using Nashorn.

Example :




//Evaluating a Script Statement Using Nashorn

import javax.script.*;

public class EvalScript {

public static void main(String[] args) throws Exception {

// create a script engine manager

ScriptEngineManager factory = new ScriptEngineManager();

// create a Nashorn script engine

ScriptEngine engine = factory.getEngineByName("nashorn");

// evaluate JavaScript statement

try {

engine.eval("print('Hello, World!');");

} catch (final ScriptException se) { se.printStackTrace(); }

}

}

Invoking Nashorn from the Command Line


There are two command-line tools that can be used to invoke the Nashorn engine:

  • jrunscript

This is a generic command that invokes any available script engine compliant with JSR 223. By default, without any options, jrunscript invokes the Nashorn engine, because it is the default script engine in the JDK.

  • jjs

This is the recommended tool, created specifically for Nashorn. To evaluate a script file using Nashorn, pass the name of the script file to the jjs tool. To launch an interactive shell that interprets statements passed in using standard input, start the jjs tool without specifying any script files.

Saturday, 30 April 2016

break Statement as a exit for a loop

How to use break statement as an exit from a loop?


               break statement can be used as an exit from a loop bypassing the conditional expression and the remaining code inside the loop. When break statement comes inside a loop, the loop terminates immediately and program control resumes at the next statement following the loop. 

               Following are few points to remember when use the break as a terminator from the loops. 


  • When we use the break statement inside a set of nested loops, it only break out of the innermost loop. 
  • More than one break statement can be used inside the loop. 
  • The break statement that terminates a switch statement affects only the switch statement and not any enclosing loop. 
  • break statements are not designed to provide a normal means of exit from a loop. break statement should be used to cancel a loop only when some sort of special situation occurs. 


Here is a simple program where the break statement is used as an exit from the loop. 

Program


// Using break to exit from a loop.
class LoopBreak{
public static void main(String args[]) 
{
    for(int i=0; i<100 font="" i="" nbsp="">
    {
        if(i == 11) break; // terminate loop if i is 11
        System.out.println("i: " + i);
    }
    System.out.println("After Loop.");
}
}

Output:


i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10
After Loop.