Vous êtes sur la page 1sur 10

JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.A variable can have a
short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive

Example
A variable's value can change during the execution of a script. You can refer to a variable by its name
to display or change its value.

This example will show you how

Declaring (Creating) JavaScript Variables


Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var keyword:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and carname will
hold the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.
Variables
Variables are places in memory to store values. There are different kinds of variables, and every language
offers slightly different characteristics.

Name.

Data Type specifies the kinds of data a variable an store. Java has two general kinds of data types.

 8 basic or primitive types (byte, short, int, long, float, double, char, boolean).

 An unlimited number of object types (String, Color, JButton, ...). Java object variables hold a
reference (pointer) to the the object, not the object, which is always stored on the heap.

Scope of a variable is who can see it. The scope of a variable is related program structure: eg, block,
method, class, package, child class.

Lifetime is the interval between the creation and destruction of a variable. The following is basically how
things work in Java. Local variables and parameters are created when a method is entered and destroyed
when the method returns. Instance variables are created by new and destroyed when there are no more
references to them. Class (static) variables are created when the class is loaded and destroyed when the
program terminates.

Initial Value. What value does a variable have when it is created? There are several possibilites.

1. No initial value. Java local variables have no initial value, however Java compilers perform a simple
flow analysis to ensure that every local variable is assigned a value before it is used. These error
messages are usually correct, but the analysis is simple-minded, so sometimes you will have to
assign an initial value even tho you know that it isn't necessary.

2. User specified initial value. Java allows an assignment of intitial values in the declaration of a
variable.
3. Instance and static variables are given default initial values: zero for numbers, null for objects,
and false for booleans.

Declarations are required. Java, like many languages, requires you to declare variables -- tell the
compiler the data type, etc. Declarations are good because they help the programmer build more reliable
and efficient programs.

 Declarations allow the compiler to find places where variables are misused, eg, parameters of the
wrong type. What is especially good is that these errors are detected at compile time. Bugs that
make it past the compiler are harder to find, and may not be discovered until the program has been
released to customers. This fits the fail early, fail often philosophy.

 A declaration is also the perfect place to write comments describing the variable and how it is used.

 Because declarations give the compiler more information, it can generate better code.
Java Variable Types

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here:

type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one
variable of the specified type, use a comma-separated list.

Here are several examples of variable declarations of various types. Note that some include an initialization.

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

This chapter will explain varioys variable types available in Java Language. There are three kinds of
variables in Java:

1. Local variables

2. Instance variables

3. Class/static variables

Local variables :

 Local variables are declared in methods, constructors, or blocks.

 Local variables are created when the method, constructor or block is entered and the variable will
be destroyed once it exits the method, constructor or block.

 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method, constructor or block.

 Local variables are implemented at stack level internally.

 There is no default value for local variables so local variables should be declared and an initial value
should be assigned before the first use.

Example:

Here age is a local variable. This is defined inside pupAge() method and its scope is limited to this method
only.
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();
}
}

This would produce following result:

Puppy age is: 7

Example:

Following example uses age without initializing it, so it would give an error at the time of compilation.

public class Test{


public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy age is : " + age)
}

public static void main(String args[]){


Test test = new Test();
Test.pupAge();
}
}

This would produce following error while compiling it:

Test.java:4:variable number might not have been initialized


age = age + 7;
^
1 error

Instance variables :

 Instance variables are declared in a class, but outside a method, constructor or any block.

 When a space is allocated for an object in the heap a slot for each instance variable value is
created.

 Instance variables are created when an object is created with the use of the key word 'new' and
destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object.s state that must be present through out the class.

 Instance variables can be declared in class level before or after use.

 Access modifiers can be given for instance variables.

 The instance variables are visible for all methods, constructors and block in the class. Normally it is
recommended to make these variables private (access level).However visibility for subclasses can
be given for these variables with the use of access modifiers.

 Instance variables have default values. For numbers the default value is 0, for Booleans it is false
and for object references it is null. Values can be assigned during the declaration or within the
constructor.

 Instance variables can be accessed directly by calling the variable name inside the class. However
within static methods and different class ( when instance variables are given accessibility) the
should be called using the fully qualified name . ObjectReference.VariableName.

Example:

import java.io.*;

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();
}
}

This would produce following result:


name : Ransika
salary :1000.0

Class/static variables :

 Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.

 There would only be one copy of each class variable per class, regardless of how many objects are
created from it.

 Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final and static. Constant variables never change from their initial
value.

 Static variables are stored in static memory. It is rare to use static variables other than declared
final and used as either public or private constants.

 Static variables are created when the program starts and destroyed when the program stops.

 Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.

 Default values are same as instance variables. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or within the
constructor. Additionally values can be assigned in special static initializer blocks.

 Static variables can be accessed by calling with the class name . ClassName.VariableName.

 When declaring class variables as public static final, then variables names (constants) are all in
upper case. If the static variables are not public and final the naming syntax is the same as instance
and local variables.

Example:

import java.io.*;

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);
}
}

This would produce following result:

Development average salary:1000


Note: If the variables are access from an outside class the constant should be accessed as
Employee.DEPARTMENT

In this section, you will learn about Java variables. A variable refers to the memory location
that holds values like: numbers, texts etc. in the computer memory. A variable is a name of
location where the data is stored when a program executes.
The Java contains the following types of variables:

1. Instance Variables (Non-static fields): In object oriented programming, objects store


their individual states in the "non-static fields" that is declared without the static
keyword. Each object of the class has its own set of values for these non-static variables
so we can say that these are related to objects (instances of the class).Hence these
variables are also known as instance variables. These variables take default values if not
initialized.    
2. Class Variables (Static fields): These are collectively related to a class and none of the
object can claim them  its sole-proprietor . The variables defined with static keyword are
shared by all objects. Here Objects do not store an individual value but they are forced to
share it among themselves. These variables are declared as "static fields" using the
static keyword. Always the same set of values is shared among different objects of the
same class. So these variables are like global variables which are same for all objects of
the class. These variables take default values if not initialized.          
3. Local Variables: The variables defined in a method or block of code is called local
variables. These variables can be accessed within a method or block of code only. These
variables don't take default values if not initialized. These values are required to be
initialized before using them.
4. Parameters: Parameters or arguments are variables used in method declarations. 

Declaring and defining variables


Before using variables you must declare the variables  name and type. See the following
example for variables declaration:
int num;            //represents that num is a variable that can store value of int
type.
String name;     //represents that name is a variable that can store string value.
boolean bol;    //represents that bol is a variable that can take boolean value
(true/false);
You can assign a value to a variable at the declaration time by using an assignment operator (
= ).
int num = 1000;       // This line declares num as an int variable which holds
value "1000".
boolean bol = true;      // This line declares bol as boolean variable which is set
to the value "true".
Literals
By literal we mean any number, text, or other information that represents a
value. This means what you type is what you get. We will use literals in
addition to variables in Java statement. While writing a source code as a
character sequence, we can specify any value as a literal such as an integer.
This character sequence will specify the syntax based on the value's type. This
will give a literal as a result. For instance
int month  = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10
because it directly represents the integer value.
In Java programming language there are some special type of literals that
represent numbers, characters, strings and boolean values. Lets have a closer
look on each of the following.
Number Literals
Number literals is a sequence of digits and a suffix as L. To represent the type
as long integer we use L as a suffix. We can specify the integers either in
decimal, hexadecimal or octal format. To indicate a decimal format put the left
most digit as nonzero. Similarly put the characters as ox to the left of at least
one hexadecimal digit to indicate hexadecimal format. Also we can indicate
the octal format by a zero digit followed by the digits 0 to 7. Lets tweak the
table below.
CONTENTS
PAGE NO:
HTML
INTRODUCTION TO HTML 1-10
HOW TO CREATE AN HTML DOCUMENT 11
PROGRAMME TO CREATE MARQUEE 12-13
PROGRAMME TO CREATE MARQUEE 14-17
PROGRAMME TO CREATE A DIFFERENT TYPE OF HEADING 18
PROGRAMME TO CREATE A ELEMENT OF IMAGE 19
PROGRAMME TO CREATE A IMAGE OF HYPERLINK 20
PROGRAMME TO CREATE ORDERED, UNORDERED LISTS 21-25
PROGRAMME TO CREATE A TABLE 26-49
ADVANTAGE OR LIMITATION OF HTML 50

JAVASCRIPT
INTRODUCTION TO JAVASCRIPT 51-57
PROGRAMME TO CREATE A SERIES 1-10 58
PROGRAMME TO CREATE A TABLE OF 7 59
PROGRAMME TO CREATE A BUTTON 60-62
PROGRAMME TO CREATE A STAR 63

MY WEBSITE 64-78
QUIZ PROGRAMME 79-83

Vous aimerez peut-être aussi