Monday, 9 April 2018



jQuery - Selectors


jQuery Selectors are used to select one or more HTML elements and once the element is selected then we can perform various operation on that. jQuery Selectors are used to select and manipulate HTML elements as part of jQuery library.

All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the factory function.

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

When a user clicks on a button, all <p> elements will be hidden:

Example

$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});

Usage of Selectors:

Name:  It selects all elements that match with the given element name.

#ID: It selects a single element that matches with the given id.

.Class: It selects all elements that match with the given class.

Universal(*): It selects all elements available in a DOM.

Examples of jQuery selectors

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements




Monday, 12 March 2018

Java Naming Convention

Java naming convention is a simple rule to follow as a developer to decide what to name your identifiers such as class, package, variable, constant, method etc.

Here are rules to follow in Java regarding Naming Convention

Class name: It should start with an uppercase letter and be a noun e.g. Name, String, System, Thread etc.
Interface name: It should start with an uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
Method name : It should start with lowercase letter and be a verb e.g. actionExecute(), run(), print(), println() etc.
Variable name: It should start with lowercase letter e.g. lastName, messageNumber etc.
Package name: It should be in lowercase letter e.g. impl, lang, sql, util etc.
Constants name: It should be in the uppercase letter. e.g. GREEN, YELLOW, MIN_PRIORITY etc.

Examples

Interface  Furnitures
Class Chair implements Furnitures
void changeName(Strung newValue);
void employeeNo(int value);
com.impl.programs.examples

Java strictly follows the camelcase syntax for naming the class, interface, method and variable.
Camelcase syntax: If name is combined with two words, second word will start with uppercase letter always e.g. actionExecute(), lastName, ActionEvent, ActionListener etc.

Wednesday, 7 February 2018

Simple Java program to print current date and time.


Java program to display current date.

Date function in Java Programming code.



/*
Java Date example.
This Java Date example program describes how Java Date function from utility is being used in Java language.
*/

import java.util.*;

public class JavaDateProgram{

          public static void main(String args[]){
            /*
              Create date object with current date and time.
            */
 Date dateandtime = new Date();
  System.out.println("Current Time is " + dateandtime);

  }
}

Output:


Current Time is Sat Feb 08 16:10:21 IST 2018

Tuesday, 29 November 2016

Facts about Variable Length Argument in Java

Variable Length Argument Rules in Java


                 Java included a feature that simplifies the creation of methods that require variable number of arguments. This is known as vararg. vararg is the short for of Variable Length Arguments.

5 Facts about Variable Length Argument Rules in Java


1. A variable-length argument is specified by three periods (…).

     Eg:

            static void TestVariableArgument(int ... v) {
            }

         This syntax tells the compiler that TestVariableArgument( ) can be called with zero or more arguments.

2. In the case of no arguments, the length of the array is zero.

3. A method can have “normal” parameters along with a variable-length parameter and the variable-length parameter must be the last parameter declared by the method.


4. Overloading a method that takes a variable-length argument is possible.

5. If a method call conflicts with two methods that implements variable argument or other leads to error. 

Thursday, 24 November 2016

JQuery - Introduction

jQuery is a small, light-weight and fast JavaScript library. It is cross-platform and supports different types of browsers. It is very useful for data manipulation.
  • jQuery is a small, fast and lightweight JavaScript library.
  • jQuery is platform-independent.
  • jQuery means "write less do more".
  • jQuery simplifies AJAX call and DOM manipulation.
jQuery features:
  • HTML manipulation
  • DOM manipulation
  • DOM element selection
  • CSS manipulation
  • Effects and Animations
  • Utilities
  • AJAX
  • HTML event methods
  • JSON Parsing
  • Extensibility through plug-in
To starts with,
  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

jQuery Syntax:

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".


Tuesday, 22 November 2016

Initializing a blank final variable in Java


How to initialize a blank final variable in Java?


Example Java Program to demonstrate the initialization of blank final variable using Constructor

                  
                  A field can be declared as final. Doing so prevents its contents from being modified, A final variable that is not initialized at the time of declaration is known as blank final variable. The blank final variable can be only initialized using its constructor method.

                   
                  As per the coding convention, it is common to use all upper case letters to represent a final variable. 


Example: 

  
                    final in REGNO = 15480;

Progam:


//Java Program to demonstrate the initialization of blank final variable using Constructor
class FinalInitialize
{
     final int VALUE;
     FinalInitialize(){       // Constructor
          VALUE=10;           // Initialized final variable inside constructor
          System.out.println("Final Value is : "+VALUE);
     }
}
public class InitializeFinal {
     public static void main(String[] args) {
          new FinalInitialize();
     }
}

               In the above program, The FinalInitialize() constructor initiate the value of the final variable VALUE.

Sunday, 13 November 2016

Java Program to find the Volume of a Box

Volume of a Box in Java


                  The below program demonstrates simple class creation and perform volume calculation of a box.


Program:


class Box {
double width;
double height;
double depth;
}
public class BoxJavaProgram {
    public static void main(String[] args){
        Box mybox = new Box();
        double vol;
        mybox.width = 20;
        mybox.height = 30;
        mybox.depth = 10;
        vol = mybox.width * mybox.height * mybox.depth;
        System.out.println("Volume is " + vol);
    }
}

Output:


Volume is 6000.0

Thursday, 10 November 2016

Difference between Instance and Object in Java

Difference between class object and class instance in java

               
               The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Object and Instance in Java
Difference between object and instance in Java

It is obvious to get confused by the words class object and class instance. A class is a template for an object and an object is an instance of a class. To make it clear, we can also say that the instance of a class is object.

There is no need of differentiating the words object and instance as both doesn’t make any difference when is used interchangeably.

For Example:

class Animal

Object of class Animal and instance of class Animal are same. When you create an instance of the class animal, the instance is an object and the type of that object is “class Animal”.

Sunday, 2 October 2016

Javascript Date


The Javascript Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)

Simply for displaying dates its like below:
<script>
document.getElementById("demo").innerHTML = Date();
</script>

The important methods of date object are as follows:

MethodDescription
getFullYear()returns the year in 4 digit e.g. 2015. It is a new method and suggested than getYear() which is now deprecated.
getMonth()returns the month in 2 digit from 1 to 31.
getDate()returns the date in 1 or 2 digit from 1 to 31.
getDay()returns the day of week in 1 digit from 0 to 6.
getHours()returns all the elements having the given name value.
getMinutes()returns all the elements having the given class name.
getSeconds()returns all the elements having the given class name.
getMilliseconds()returns all the elements having the given tag name.

Current date example:
<script> 
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>

Current Time example:
<script> 
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script> 

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.

Wednesday, 27 April 2016

JavaScript Objects

A javaScript object is an entity having state and behavior (properties and method).
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.

Creating Objects in JavaScript
There are 3 ways to create objects.

  1. By object literal
  2. By creating instance of Object directly (using new keyword)
  3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal

Syntax:
object={property1:value1,property2:value2.....propertyN:valueN}  

2)By creating instance of object 
Syntax:
var objectname=new Object();  

3) By using an Object constructor
The this keyword refers to the current object.

Example:
<script> 
function student(id,name,age){
this.id=id;
this.name=name;
this.age=age;
}
st=new student(103,"Vimal Jaiswal",12);
 
document.write(st.id+" "+st.name+" "+st.age);
</script> 


Javascript Functions


JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.

Syntax:
function functionName([arg1, arg2, ...argN]){
 //code to be executed
}  

Example:
function firstFunction(x1, x2) {
    return x1 * x2;              // The function returns the product of x1 and x2
}


Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument.


Example:
function getVal(num){
alert(num*num*num);
}  

Function with return value

Example:
<script> 
function getData(){
return "hello first program";
}
</script> 
<script> 
document.write(getData());
</script>

Monday, 18 April 2016

Javascript Loops


The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact. It is mostly used in array.

That means,
Instead of writing,
val+= name[0] + "
"
;
val+= name[1] + "
"
;
val+= name[2] + "
"
;

you can use
for (i = 0; i < name.length; i++) {
    val+= name[i] + "
"
;
}

Different Kinds of Loops
JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

1) JavaScript For loop: 

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.

syntax:
for (initialization; condition; increment)
{
    code to be executed
}  

example:
for (i = 0; i < 5; i++) {
    val+= "The value is " + i + "
"
;
}

2)The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

example:
var name= {fname:"Ravi", lname:"k"umar, age:25};
var val= "";
var x;
for (x in person) {
    val+= name[x];
}

3) JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is not known. 
syntax:
while (condition)
{
    code to be executed
}  
example:
<script>
var i=10;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

4) JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at least once whether condition is true or false. 
syntax:
do{
    code to be executed
}while (condition);  

example:
<script>
var i=20;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

Saturday, 9 April 2016

Use of break statement with switch

How break is useful with switch statement in Java?


               The break statement is used to terminate the statement sequence in a switch statement. If we do not use break statement, the control of flow of the switch continue as usual and just work like an else-if ladder. 

               The below program print the month name on the screen according to the provided number. 

Program:


import java.util.Scanner;
public class SwitchBreakDemo {
    public static void main(String[] args) {

        int month;
        System.out.println("Enter a number to display its corresponding Month Name");
        Scanner in = new Scanner(System.in);  
        month=in.nextInt();
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

Output:


Enter a number to display its corresponding Month Name
5
May


Jump Statements in Java

Java Jump Statements : break, continue and return


               Java supports three jump statements. They are

                          1. break
                         2. continue
                         3. return

1. break:


               break statement in Java can be used in three ways. Other-words, the break statement has three used in the application. They are as follows

  • It terminates a statement sequence in a switch statement.
  • break statement is used to exit from a loop.
  • It can be used for a goto form of operation as Java doesn't have a goto keyword/statement as its own.


2. continue:


               continue statement is used to force an early iteration in a loop. i.e, if you wish to discard the remaining code part inside a loop and go back to the iteration part, the continue statement will do the job for you. In while and do-while loop, the continue statement transfer control directly to the condition expression of the loop

               In the case of for loop, control goes first to the iteration part and then transfer to the condition expression. 

Example program for continue statement in Java

3. return:


               The return statement is used to explicitly return from a method. The return statement can be used to terminate from a method and return control to its caller position. 

Example program for return statement in Java

Tuesday, 5 April 2016

For Each Loop in Java

How to use for each loop in Java


               The for each loop is designed to cycle through a collection of objects in sequential fashion from beginning to end. The collection of objects can be an array. 


Syntax:



for(type iteration-variable: collection)
{
           Statement block;
}

               Here type is same as the data type used in the array/collection. The iteration variable collect data from each element in the array. 


for each Example Java Program


/* Java program to take the sum of first 10 digits using 
   for each loop */

public class ForEachLoopExample {

    public static void main(String args[]){        

      int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      int sum = 0;
      for(int x: nums) sum += x;
      System.out.println("Sum is: " + sum);

   }

    
}


Output: 


Sum is: 55

Note: There is no keyword named foreach to perform the foreach style of loop operation in Java. 

Monday, 4 April 2016

Javascript - Switch statement


The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement that we have learned in previous page.

Syntax for javascript switch statement

switch(expression){
case value1:
 code to be executed;
 break;
case value2:
 code to be executed;
 break;
......

default:
 code to be executed if above values are not matched;
}  



Example:
<script>
var color='C';
var result;
switch(color){
case 'A':
result="one";
break;
case 'B':
result="two";
break;
case 'C':
result="three";
break;
default:
result="No Color";
}
document.write(result);
</script>

Output: three  

Here the default keyword specifies the code to run if there is no case match