Ashwinijk
51 min readOct 22, 2020

--

Learning Java, Python and JavaScript basics side-by-side

Java

→ Definition and features

→ Basic Syntax

→ Java Object and Classes

→ Java Data Types

→ Java Basic Operators

→ Loop statements

→ Decision making statements

→ Arrays

Python

→ Definition and Features

→ Basic Syntax

→ Python Data Types

→ Python Basic Operators

→ Loop statements

→ Decision making statements

JavaScript

→ Definition and Features

→ Basic Syntax

→ JavaScript Data Types

→ JavaScript Basic Operators

→ Decision making statements

→ Loop statements

→ Functions

→ Events

Java

Definition and features

Java is a high-level, object oriented, platform independent, dynamic, multi-threaded, interpreted, high-performance, programming language.

  • High-level It is high-level as it is easy to write for the end-users and doesn’t use much of machine level instructions.
  • object-oriented programing language — In java everything is an object. Java can be easily extendible since it is based on object model.
  • platform independent — Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
  • Dynamic — Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
  • Multithreaded — With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.
  • Interpreted — Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.
  • High-performance — With the use of Just-In-Time compilers, Java enables high performance.
  • Java is guaranteed to be write-once and run-anywhere programming language.

Writing “Hello World” code using Java

Public class MyFirstJavaProgram{

public static void main(Strings []args){

System.out.println("Hello World");
}
}
  • Open notepad and add the code as above.
  • Save the file as: MyFirstJavaProgram.java.
  • Open a command prompt window and go to the directory where you saved the class. Assume it’s C:\.
  • Type ‘javac MyFirstJavaProgram.java’ and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
  • Now, type ‘ java MyFirstJavaProgram ‘ to run your program.
  • You will be able to see ‘ Hello World ‘ printed on the window.
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

Basic Syntax

Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.

Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word’s first letter should be in Upper Case. Example: class MyFirstJavaClass

Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word’s first letter should be in Upper Case.Example: public void myMethodName()

Program File Name − Name of the program file should exactly match the class name.Example: Assume ‘MyFirstJavaProgram’ is the class name. Then the file should be saved as ‘MyFirstJavaProgram.java’

public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

Java identifiers

All Java components require names. Names used for classes, variables, and methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows −

  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  • After the first character, identifiers can have any combination of characters.
  • A key word cannot be used as an identifier.
  • Most importantly, identifiers are case sensitive.
  • Examples of legal identifiers: age, $salary, _value, __1_value.
  • Examples of illegal identifiers: 123abc, -salary.

Comments in Java

Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram {

/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Java Keywords

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while

Objects and Classes in Java

Object − Objects have states and behaviors. Example: A dog has states — color, name, breed as well as behaviors — wagging the tail, barking, eating. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.Following is a sample of a class.

Example

public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods.

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

  • Declaration − A variable declaration with a variable name with an object type.
  • Instantiation − The ‘new’ keyword is used to create the object.
  • Initialization − The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object.

Following is an example of creating an object −

Example

public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

Java variable types

Following are the types of variables in Java −

  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static Variables)
  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

Example

import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) {
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal;
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
  • Class/Static variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Example

import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

Constructors

When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Following is an example of a constructor −

Example

public class Puppy {
public Puppy() {
}
public Puppy(String name) {
// This constructor has one parameter, name.
}
}

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Syntax

Following is the syntax of a constructor −

class ClassName {
ClassName() {
}
}

Java allows two types of constructors namely −

  • No argument Constructors
  • Parameterized Constructors

No argument Constructors

As the name specifies the no argument constructors of Java does not accept any parameters instead, using these constructors the instance variables of a method will be initialized with fixed values for all objects.

Example

Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}

Parameterized Constructors

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor’s name.

Example

Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
int x;

// Following is the constructor
MyClass(int i ) {
x = i;
}
}

Import Statements

In Java if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.

For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io −

import java.io.*;

Data Types

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

There are two data types available in Java −

  • Primitive Data Types
  • Reference/Object Data Types

Primitive Data Types

There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a keyword.

byte

  • Byte data type is an 8-bit signed two’s complement integer
  • Minimum value is -128 (-2⁷)
  • Maximum value is 127 (inclusive)(2⁷ -1)
  • Default value is 0
  • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
  • Example: byte a = 100, byte b = -50

short

  • Short data type is a 16-bit signed two’s complement integer
  • Minimum value is -32,768 (-2¹⁵)
  • Maximum value is 32,767 (inclusive) (2¹⁵ -1)
  • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
  • Default value is 0.
  • Example: short s = 10000, short r = -20000

int

  • Int data type is a 32-bit signed two’s complement integer.
  • Minimum value is — 2,147,483,648 (-2³¹)
  • Maximum value is 2,147,483,647(inclusive) (2³¹ -1)
  • Integer is generally used as the default data type for integral values unless there is a concern about memory.
  • The default value is 0
  • Example: int a = 100000, int b = -200000

long

  • Long data type is a 64-bit signed two’s complement integer
  • Minimum value is -9,223,372,036,854,775,808(-2⁶³)
  • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2⁶³ -1)
  • This type is used when a wider range than int is needed
  • Default value is 0L
  • Example: long a = 100000L, long b = -200000L

float

  • Float data type is a single-precision 32-bit IEEE 754 floating point
  • Float is mainly used to save memory in large arrays of floating point numbers
  • Default value is 0.0f
  • Float data type is never used for precise values such as currency
  • Example: float f1 = 234.5f

double

  • double data type is a double-precision 64-bit IEEE 754 floating point
  • This data type is generally used as the default data type for decimal values, generally the default choice
  • Double data type should never be used for precise values such as currency
  • Default value is 0.0d
  • Example: double d1 = 123.4

boolean

  • boolean data type represents one bit of information
  • There are only two possible values: true and false
  • This data type is used for simple flags that track true/false conditions
  • Default value is false
  • Example: boolean one = true

char

  • char data type is a single 16-bit Unicode character
  • Minimum value is ‘\u0000’ (or 0)
  • Maximum value is ‘\uffff’ (or 65,535 inclusive)
  • Char data type is used to store any character
  • Example: char letterA = ‘A’

Reference Datatypes

  • Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.
  • Class objects and various type of array variables come under reference datatype.
  • Default value of any reference variable is null.
  • A reference variable can be used to refer any object of the declared type or any compatible type.
  • Example: Animal animal = new Animal(“giraffe”);

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −

  • Access Modifiers − default, public , protected, private
  • Visible to the package, the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).
  • Non-access Modifiers − final, abstract, strictfp
  • The static modifier for creating class methods and variables.
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.

Basic operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus), ++ (Increment), -- (Decrement)

The Relational Operators

There are following relational operators supported by Java language.

== (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation.

& (bitwise and), | (bitwise or), ^ (bitwise XOR), ~ (bitwise compliment), << (left shift), >> (right shift), >>> (zero fill right shift)

The Logical Operators

The following table lists the logical operators −

&& (logical and), || (logical or), ! (logical not)

The Assignment Operators

Following are the assignment operators supported by Java language −

=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=

Miscellaneous Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −

variable x = (expression) ? value if true : value if false

Following is an example −

Example

public class Test {   public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

Loop statement

while loop - Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.for loop - Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.do...while loop - Like a while statement, except that it tests the condition at the end of the loop body.

Loop control statements

break statement - Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.continue statement - Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Decision making

if statement - An if statement consists of a boolean expression followed by one or more statements.if...else statement - An if statement can be followed by an optional else statement, which executes when the boolean expression is false.nested if statement - You can use one if or else if statement inside another if or else if statement(s).switch statement - A switch statement allows a variable to be tested for equality against a list of values.

Numbers

Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.

Example

int i = 5000;
float gpa = 13.65f;
double mask = 125;

However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes. All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number. The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class.

And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package.

Following is an example of boxing and unboxing −

Example

public class Test {   public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}

Number Methods

Following is the list of the instance methods that all the subclasses of the Number class implements −

xxxValue()- Converts the value of this Number object to the xxx data type and returns it.compareTo()- Compares this Number object to the argument.equals()- Determines whether this number object is equal to the argument.

valueOf()- Returns an Integer object holding the value of the specified primitive.
toString()- Returns a String object representing the value of a specified int or Integer.

parseInt()- This method is used to get the primitive data type of a certain String.
abs()- Returns the absolute value of the argument.ceil()- Returns the smallest integer that is greater than or equal to the argument. Returned as a double.

floor()- Returns the largest integer that is less than or equal to the argument. Returned as a double.

rint()- Returns the integer that is closest in value to the argument. Returned as a double.

round()- Returns the closest long or int, as indicated by the method's return type to the argument.
min()- Returns the smaller of the two arguments.

max()- Returns the larger of the two arguments.

exp()- Returns the base of the natural logarithms, e, to the power of the argument.
log()- Returns the natural logarithm of the argument.

pow()- Returns the value of the first argument raised to the power of the second argument.

sqrt()- Returns the square root of the argument.

sin()- Returns the sine of the specified double value.
cos()- Returns the cosine of the specified double value.tan()- Returns the tangent of the specified double value.

asin()- Returns the arcsine of the specified double value.
acos()- Returns the arccosine of the specified double value.atan()- Returns the arctangent of the specified double value.

atan2()- Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.

toDegrees()- Converts the argument to degrees.
toRadians()- Converts the argument to radians.

random()- Returns a random number.

Characters

Normally, when we work with characters, we use primitive data types char.

Example

char ch = 'a';// Unicode for uppercase Greek omega character
char uniChar = '\u039A';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char.

The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor −

Character ch = new Character('a');

The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way.

Example

// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');

Character Methods

Following is the list of the important instance methods that all the subclasses of the Character class implement −

isLetter()- Determines whether the specified char value is a letter.

isDigit()- Determines whether the specified char value is a digit.
isWhitespace()- Determines whether the specified char value is white space.

isUpperCase()- Determines whether the specified char value is uppercase.

isLowerCase()- Determines whether the specified char value is lowercase.

toUpperCase()- Returns the uppercase form of the specified char value.
toLowerCase()- Returns the lowercase form of the specified char value.toString()- Returns a String object representing the specified character value that is, a one-character string.

Strings

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.

The Java platform provides the String class to create and manipulate strings. The most direct way to create a string is to write −

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!’.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

Example

public class StringDemo {   public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

The following program is an example of length(), method String class.

Example

public class StringDemo {   public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

Concatenating Strings

The String class includes a method for concatenating two strings −

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in −

"Hello," + " world" + "!"

which results in −

"Hello, world!"

Let us look at the following example −

Example

public class StringDemo {   public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

String Methods

Here is the list of methods supported by String class −

char charAt(int index)- Returns the character at the specified index.int compareTo(Object o)- Compares this String to another Object.int compareTo(String anotherString)- Compares two strings lexicographically.

int compareToIgnoreCase(String str)- Compares two strings lexicographically, ignoring case differences.
String concat(String str)- Concatenates the specified string to the end of this string.boolean contentEquals(StringBuffer sb)- Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.static String copyValueOf(char[] data)- Returns a String that represents the character sequence in the array specified.static String copyValueOf(char[] data, int offset, int count)- Returns a String that represents the character sequence in the array specified.boolean endsWith(String suffix)- Tests if this string ends with the specified suffix.boolean equals(Object anObject)- Compares this string to the specified object.boolean equalsIgnoreCase(String anotherString)- Compares this String to another String, ignoring case considerations.byte[] getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.byte[] getBytes(String charsetName)- Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)- Copies characters from this string into the destination character array.int hashCode()- Returns a hash code for this string.int indexOf(int ch)- Returns the index within this string of the first occurrence of the specified character.int indexOf(int ch, int fromIndex)- Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.int indexOf(String str)- Returns the index within this string of the first occurrence of the specified substring.int indexOf(String str, int fromIndex)- Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.String intern()- Returns a canonical representation for the string object.int lastIndexOf(int ch)- Returns the index within this string of the last occurrence of the specified character.int lastIndexOf(int ch, int fromIndex)- Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.int lastIndexOf(String str)- Returns the index within this string of the rightmost occurrence of the specified substring.int lastIndexOf(String str, int fromIndex)- Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.int length()- Returns the length of this string.boolean matches(String regex)- Tells whether or not this string matches the given regular expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)- Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)- Tests if two string regions are equal.String replace(char oldChar, char newChar)- Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.String replaceAll(String regex, String replacement)- Replaces each substring of this string that matches the given regular expression with the given replacement.String replaceFirst(String regex, String replacement)- Replaces the first substring of this string that matches the given regular expression with the given replacement.String[] split(String regex)- Splits this string around matches of the given regular expression.String[] split(String regex, int limit)- Splits this string around matches of the given regular expression.boolean startsWith(String prefix)- Tests if this string starts with the specified prefix.boolean startsWith(String prefix, int toffset)- Tests if this string starts with the specified prefix beginning a specified index.CharSequence subSequence(int beginIndex, int endIndex)- Returns a new character sequence that is a subsequence of this sequence.String substring(int beginIndex)- Returns a new string that is a substring of this string.String substring(int beginIndex, int endIndex)- Returns a new string that is a substring of this string.char[] toCharArray()- Converts this string to a new character array.String toLowerCase()- Converts all of the characters in this String to lower case using the rules of the default locale.String toLowerCase(Locale locale)- Converts all of the characters in this String to lower case using the rules of the given Locale.String toString()- This object (which is already a string!) is itself returned.String toUpperCase()- Converts all of the characters in this String to upper case using the rules of the default locale.String toUpperCase(Locale locale)- Converts all of the characters in this String to upper case using the rules of the given Locale.String trim()- Returns a copy of the string, with leading and trailing whitespace omitted.static String valueOf(primitive data type x)- Returns the string representation of the passed data type argument.

Array

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax

dataType[] arrayRefVar;   // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.

Example

The following code snippets are examples of this syntax −

double[] myList;   // preferred way.
or
double myList[]; // works but not preferred way.

Creating Arrays

You can create an array by using the new operator with the following syntax −

Syntax

arrayRefVar = new dataType[arraySize];

The above statement does two things −

  • It creates an array using new dataType[arraySize].
  • It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows −

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −

double[] myList = new double[10];

Example

Here is a complete example showing how to create, initialize, and process arrays −

public class TestArray {   public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

Python

Definition and Features

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

  • Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
  • Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
  • Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
  • Python is a Beginner’s Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Write “Hello world” using python

print("Hello World");

Let us write a simple Python program in a script. Python files have extension .py. Type the above source code in a test.py file −

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −python test.pyHello World

This will produce Hello World output as shown in the above block.

Basic Syntax

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers −

  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Lines and Indentation

Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −

if true
print("true");
else:
print(false");

Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three;

Quotation in Python

Python accepts single (‘), double (“) and triple (’’’ or ”””) quotes to denote string literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

word = 'word'
sentence = "This is a sentence"
paragraph = """ This is a paragraph. It is made up of
multiple lines and sentences."""

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

#First comment
print("Hello World"); #Second comment
''' This is a multi line
comment. '''

Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Python Data Types

Python Variables

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

The data stored in memory can be of many types. Python has five standard data types −

  1. Numbers

2. String

3. List

4. Tuple

5. Dictionary

#Numbersvar1 = 1
var2 = 10
#String
str = "Hello World";
#List
list = ['john', '765', '3.4'];
#Tuples
tuple = ( 'john', '765', '3.4');
#Dictionary
dictionary = { 'name':'john', 'code':'234', 'department':'sales'};

Numbers

Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example −

var1 = 1
var2 = 10

Python supports four different numerical types −

  • int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
  • long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
  • float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
  • complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.

Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

  • Type int(x) to convert x to a plain integer.
  • Type long(x) to convert x to a long integer.
  • Type float(x) to convert x to a floating-point number.
  • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
  • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions.

Mathematical functions

abs(x)- The absolute value of x: the (positive) distance between x and zero.ceil(x)- The ceiling of x: the smallest integer not less than x.cmp(x, y)- -1 if x < y, 0 if x == y, or 1 if x > yexp(x)- The exponential of x: e^x  

fabs(x)- The absolute value of x.
floor(x)- The floor of x: the largest integer not greater than xlog(x)- The natural logarithm of x, for x> 0log10(x)- The base-10 logarithm of x for x> 0.max(x1, x2,...)- The largest of its arguments: the value closest to positive infinitymin(x1, x2,...)- The smallest of its arguments: the value closest to negative infinitymodf(x)- The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.pow(x, y)- The value of x^**y.round(x [,n])- x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.sqrt(x)- The square root of x for x > 0

Random Number Functions

Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

choice(seq) - A random item from a list, tuple, or string.randrange ([start,] stop [,step]) - A randomly selected element from range(start, stop, step)random() - A random float r, such that 0 is less than or equal to r and r is less than 1seed([x]) - Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns Noneshuffle(lst) - Randomizes the items of a list in place. Returns None.uniform(x, y) - A random float r, such that x is less than or equal to r and r is less than y

Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. Creating strings is as simple as assigning a value to a variable.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example

str = 'Hello World!'

print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

Accessing Values in Strings

#!/usr/bin/python

var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

String Special Operators

+ - Concatenation - Adds values on either side of the operator* - Repetition - Creates new strings, concatenating multiple copies of the same string[] - Slice - Gives the character from the given index[:] - Range Slice - Gives the characters from the given rangein - Membership - Returns true if a character exists in the given stringnot in - Membership - Returns true if a character does not exist in the given stringr/R - Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.% - Format - Performs String formatting

String Methods

capitalize() - Capitalizes first letter of stringcenter(width, fillchar)- Returns a space-padded string with the original string centered to a total of width columns.count(str, beg= 0,end=len(string))- Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.decode(encoding='UTF-8',errors='strict')- Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')- Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))- Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.expandtabs(tabsize=8)- Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.find(str, beg=0 end=len(string))- Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

index(str, beg=0, end=len(string))- Same as find(), but raises an exception if str not found.

isalnum()- Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isalpha()- Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

isdigit()- Returns true if string contains only digits and false otherwise.

islower()- Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isnumeric()- Returns true if a unicode string contains only numeric characters and false otherwiseisspace()- Returns true if string contains only whitespace characters and false otherwise.

istitle()- Returns true if string is properly "titlecased" and false otherwise.

isupper()- Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

join(seq)- Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

len(string)- Returns the length of the string

ljust(width[, fillchar])- Returns a space-padded string with the original string left-justified to a total of width columns.

lower()- Converts all uppercase letters in string to lowercase.

lstrip()- Removes all leading whitespace in string.

maketrans()- Returns a translation table to be used in translate function.

max(str)- Returns the max alphabetical character from the string str.

min(str)- Returns the min alphabetical character from the string str.

replace(old, new [, max])- Replaces all occurrences of old in string with new or at most max occurrences if max given.
rfind(str, beg=0,end=len(string))- Same as find(), but search backwards in string.rindex( str, beg=0, end=len(string))- Same as index(), but search backwards in string.

rjust(width,[, fillchar])- Returns a space-padded string with the original string right-justified to a total of width columns.

rstrip()- Removes all trailing whitespace of string.

split(str="", num=string.count(str))- Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.

splitlines( num=string.count('\n'))- Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
startswith(str, beg=0,end=len(string))- Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.

strip([chars])- Performs both lstrip() and rstrip() on string.
swapcase()- Inverts case for all letters in string.

title()- Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

translate(table, deletechars="")- Translates string according to translation table str(256 chars), removing those in the del string.

upper()- Converts lowercase letters in string to uppercase.
zfill (width)- Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).isdecimal()- Returns true if a unicode string contains only decimal characters and false otherwise.

Lists

Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

Basic List Operations

len([1, 2, 3]) o/p 3 Length, 
[1, 2, 3] + [4, 5, 6] o/p [1, 2, 3, 4, 5, 6] Concatenation,
['Hi!'] * 4 o/p ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition,
3 in [1, 2, 3] o/p True Membership,
for x in [1, 2, 3]: print x, o/p 1 2 3 Iteration.

Built-in List Functions & Methods

Functions

cmp(list1, list2)- Compares elements of both lists.

len(list)- Gives the total length of the list.
max(list)- Returns item from the list with max value.

min(list)- Returns item from the list with min value.

list(seq)- Converts a tuple into list.

Methods

list.append(obj)- Appends object obj to listlist.count(obj)- Returns count of how many times obj occurs in listlist.extend(seq)- Appends the contents of seq to listlist.index(obj)- Returns the lowest index in list that obj appearslist.insert(index, obj)- Inserts object obj into list at offset indexlist.pop(obj=list[-1])- Removes and returns last object or obj from listlist.remove(obj)- Removes object obj from listlist.reverse()- Reverses objects of list in placelist.sort([func])- Sorts objects of list, use compare func if given

Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

Basic Tuple Operations

len([1, 2, 3]) o/p 3 Length, 
[1, 2, 3] + [4, 5, 6] o/p [1, 2, 3, 4, 5, 6] Concatenation,
['Hi!'] * 4 o/p ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition,
3 in [1, 2, 3] o/p True Membership,
for x in [1, 2, 3]: print x, o/p 1 2 3 Iteration.

Built-in Tuple Functions

cmp(tuple1, tuple2) - Compares elements of both tuples.len(tuple) - Gives the total length of the tuple.max(tuple) - Returns item from the tuple with max value.min(tuple) - Returns item from the tuple with min value.tuple(seq) - Converts a list into tuple.

Dictionary

Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Built-in Dictionary Functions & Methods

Functions

cmp(dict1, dict2) - Compares elements of both dict.len(dict) - Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.str(dict) - Produces a printable string representation of a dictionarytype(variable) - Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Methods

dict.clear() - Removes all elements of dictionary dictdict.copy() - Returns a shallow copy of dictionary dictdict.fromkeys() - Create a new dictionary with keys from seq and values set to value.dict.get(key, default=None) - For key key, returns value or default if key not in dictionarydict.has_key(key) - Returns true if key in dictionary dict, false otherwisedict.items() - Returns a list of dict's (key, value) tuple pairsdict.keys() - Returns list of dictionary dict's keys

dict.setdefault(key, default=None) - Similar to get(), but will set dict[key]=default if key is not already in dict
dict.update(dict2) - Adds dictionary dict2's key-values pairs to dict

dict.values() - Returns list of dictionary dict's values

Data type conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.

int(x [,base])Converts x to an integer. base specifies the base if x is a string.long(x [,base] )Converts x to a long integer. base specifies the base if x is a string.float(x)Converts x to a floating-point number.complex(real [,imag])Creates a complex number.str(x)Converts object x to a string representation.repr(x)Converts object x to an expression string.eval(str)Evaluates a string and returns an object.tuple(s)Converts s to a tuple.list(s)Converts s to a list.set(s)Converts s to a set.dict(d)Creates a dictionary. d must be a sequence of (key,value) tuples.frozenset(s)Converts s to a frozen set.chr(x)Converts an integer to a character.unichr(x)Converts an integer to a Unicode character.ord(x)Converts a single character to its integer value.hex(x)Converts an integer to a hexadecimal string.oct(x)Converts an integer to an octal string.

Basic Operators

Python language supports the following types of operators.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

see here for further details

Python Arithmetic Operators

+ Addition, - Subtraction, * Multiplication, / Division, % Modulus, ** Exponent, // Floor division

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.

==, !=,<>, >, <, >=, <=

Python Assignment Operators

=, += Add AND, -= Subtract AND, *= Multiply AND, /= Divide AND, %= Modulus AND, **= Exponent AND, //= Floor Division

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation.

& Binary AND, | Binary OR, ^ Binary XOR, ~ Binary Ones Complement, << Binary Left Shift, >> Binary Right Shift

Python Logical Operators

and Logical AND, or Logical OR, not Logical NOT

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.

in, not in

Python Identity Operators

Identity operators compare the memory locations of two objects.

is, not is

Decision Making

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

if statements - An if statement consists of a boolean expression followed by one or more statements.if...else statements - An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.nested if statements - You can use one if or else if statement inside another if or else if statement(s).

Loop statement

A loop statement allows us to execute a statement or group of statements multiple times.

while loop - Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.for loop - Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.nested loops - You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

break statement - Terminates the loop statement and transfers execution to the statement immediately following the loop.continue statement - Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.pass statement - The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

JavaScript

Definition and Features

JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform.

JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

JavaScript can be implemented using JavaScript statements that are placed within the <script>… </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

write “Hello World” using Javascript

<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

There is a flexibility given to include JavaScript code anywhere in an HTML document. However the most preferred ways to include JavaScript in an HTML file are as follows −

  • Script in <head>…</head> section.
  • Script in <body>…</body> section.
  • Script in <body>…</body> and <head>…</head> sections.
  • Script in an external file and then include in <head>…</head> section.

Client-Side JavaScript

Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.

The merits of using JavaScript are −

  • Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
  • Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
  • Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
  • Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations of using JavaScript are −

  • We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −
  • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
  • JavaScript cannot be used for networking applications because there is no such support available.
  • JavaScript doesn’t have any multi-threading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or disable this support manually.

Basic Syntax

Semicolons are Optional

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons.

<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, you must use semicolons −

<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>

Case Sensitivity

JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So the identifiers Time and TIME will convey different meanings in JavaScript.

NOTE − Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript

JavaScript supports both C-style and C++-style comments, Thus −

  • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
  • Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
  • JavaScript also recognizes the HTML comment opening sequence <! — . JavaScript treats this as a single-line comment, just as it does the // comment.
  • The HTML comment closing sequence → is not recognized by JavaScript so it should be written as // —

Example

The following example shows how to use comments in JavaScript.

<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++

/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

JavaScript Datatypes

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript allows you to work with three primitive data types −

  • Numbers, eg. 123, 120.50 etc.
  • Strings of text e.g. “This text string” etc.
  • Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object.

Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.

<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.

  • Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
  • Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.

<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

While naming your variables in JavaScript, keep the following rules in mind.

  • You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0–9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
  • JavaScript variable names are case-sensitive. For example, Name and name are two different variables.

JavaScript Reserved Words

A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract, else, instanceof, switch, boolean, enum, int, synchronized, break, export, interface, this, byte, extends, long, throw, case, false, native, throws, catch, final, new, transient, char, finally, null, true, class, float, package, try, const, for, private, typeof, continue, function, protected, var, debugger, goto, public, void, default, if, return, volatile, delete, implements, short, while, do, import, static, with, double, in, super

Basic Operators

JavaScript supports the following types of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Arithmetic Operators

JavaScript supports the following arithmetic operators −

+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus), ++ (Increment), -- (Decrement)

Comparison Operators

JavaScript supports the following comparison operators −

= = (Equal), != (Not Equal), > (Greater than), < (Less than), >= (Greater than or Equal to), <= (Less than or Equal to)

Logical Operators

JavaScript supports the following logical operators −

&& (Logical AND), || (Logical OR), ! (Logical NOT)

Bitwise Operators

JavaScript supports the following bitwise operators −

& (Bitwise AND), | (BitWise OR), ^ (Bitwise XOR), ~ (Bitwise Not), << (Left Shift), >> (Right Shift), >>> (Right shift with Zero)

Assignment Operators

JavaScript supports the following assignment operators −

= (Simple Assignment ), += (Add and Assignment), −= (Subtract and Assignment), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)

Miscellaneous Operator

We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator.

Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

? : (Conditional )If Condition is true? Then value X : Otherwise value Y

Decision statements

if statement

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax

The syntax for a basic if statement is as follows −

if (expression) {
Statement(s) to be executed if expression is true
}

Example

<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;

if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

if…else statement

The ‘if…else’ statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

Syntax

if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}

Example

<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

if…else if… statement

The if…else if… statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

Syntax

The syntax of an if-else-if statement is as follows −

if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}

Example

<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>

Switch

The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

switch (expression) {
case condition 1: statement(s)
break;

case condition 2: statement(s)
break;
...

case condition n: statement(s)
break;

default: statement(s)
}

The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

Example

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;

case 'B': document.write("Pretty good<br />");
break;

case 'C': document.write("Passed<br />");
break;

case 'D': document.write("Not so good<br />");
break;

case 'F': document.write("Failed<br />");
break;

default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.

Syntax

The syntax of while loop in JavaScript is as follows −

while (expression) {
Statement(s) to be executed if expression is true
}

Example

<html>
<body>

<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");

while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!");
//-->
</script>

<p>Set the variable to different value and then try...</p>
</body>
</html>

The do…while Loop

The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax

The syntax for do-while loop in JavaScript is as follows −

do {
Statement(s) to be executed;
} while (expression);

Example

Try the following example to learn how to implement a do-while loop in JavaScript.

<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);
document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Loop statements

For loop

The ‘for’ loop is the most compact form of looping. It includes the following three important parts −

  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
  • The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
  • The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

Syntax

The syntax of for loop is JavaScript is as follows −

for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}

Example

<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

For…in loop

The for…in loop is used to loop through an object’s properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.

Syntax

The syntax of ‘for..in’ loop is −

for (variablename in object) {
statement or block to execute
}

In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.

Example

<html>
<body>
<script type = "text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
//-->
</script>
<p>Set the variable to different object and then try...</p>
</body>
</html>

Loop control statements

The break Statement

The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

Example

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>
</body>
</html>

The continue Statement

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

Example

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {
x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Function

A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax

The basic syntax is shown here.

<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

Example

<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function

To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.

Example

<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

Function Parameters

Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.

Example

<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

The return Statement

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

For example, you can pass two numbers in a function and then you can expect the function to return their multiplication in your calling program.

Example

<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

What is an Event ?

JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

Example

<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

HTML 5 Standard Events

Offline, Onabort, onafterprint, onbeforeonload, onbeforeprint, onblur, oncanplay, oncanplaythrough, onchange, onclick, oncontextmenu, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, onformchange, onforminput, onhaschange, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, onmessage, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onoffline, onoine, ononline, onpagehide, onpageshow, onpause, onplay, onplaying, onpopstate, onprogress, onratechange, onreadystatechange, onredo, onresize, onscroll, onseeked, onseeking, onselect, onstalled, onstorage, onsubmit, onsuspend, ontimeupdate, onundo, onunload, onvolumechange, onwaiting

--

--