Sunday, 21 December 2014

Java tokens, variables, constants

Java tokens are the atomic elements of Java. Java program are a collection of Java tokens separated by white spaces and comments.

Java is a free form language so it is not must to follow any special indentation rule. The only rule, which needs to be considered, is that the java tokens must be separated by an operator or by a separator or  by at least one white space character. In java, white space is a space, tab, or new line.

More than one white space characters may also appear wherever one white space character is allowed.

Java tokens can be classified into following categories:

  • Keywords
  • Identifiers
  • Literals
  • Operators
  • Separators
Keywords


There are appox. 50 reserved keywords in java. These keywords can not be used as identifiers. All keywords are in lowercase like C/C++.

The keywords const and goto are reserved but are not being used as of now. They  are reserved for the future use.

A new keyword assert was added by jdk 1.4.

In addition to the keywords, Java reserves the following:

true, false and null

These are the literal/constant values defined by Java, you may not use these keywords as identifiers.


Identifiers

An identifier is a word used in a program to name a local variable, method, class, interface, data members, package name etc. Java identifiers are case sensitive.

Name of the identifiers must follow certain rules:


  • A Java identifier must begin with a letter, dollar sign or underscore.
  • The subsequent characters may be digits also.
  • There is no length restriction on the identifiers i.e. they can be of any length.
  • Java allows Unicode characters in identifiers.
It is suggested that following naming convention may be followed while naming java identifiers:


  • Name of all the classes and interfaces start with a leading uppercase letter and each subsequent word also starts with a leading uppercase letter. Rest of the letters must be in lower case. Example: Student, Hello, HelloWorld, EmployeeInfo etc.
  • Names of all the public data members and methods start with a leading lowercase character. When more than one words are used in a name, the second and subsequent words start with a leading uppercase letter. Example: annualSalary, grossSalary, calculateSalary etc.
  • Names of variables that represent constant values use all uppercase letters and underscores between words.


Literals/Constants

A java literal represents a constant value in java. A literal or constant is a value specified in the source as opposed to one determined at run time. Literals may appear on the right side  in an assignment, or may be passed as arguments in method calls. Literals represent constant values so you can not assign a value to any literal i.e. they can not appear on the left side in an assignment.

Literals represent integer (byte, short, int, long) constants, floating point (float, double), constants, Character (char) constants and Boolean (boolean) constants in Java. Java also supports a literal null, which represents a null reference.

Examples:

Integer Literals: 200, -600, 0x1A, 015, 564L

Floating point Literals: 6.89, -3.15, 2.45f, 3.45d, 1.34E-01, 4.56E11

Character Literals: 'x', 'X', '\101', '\n'

Boolean Literals: true, false

String: "Hello", "abc", "xyz"

Java source file structure

All java source files must end with the extension ".java". A source file may contain at the most one top level public class. If a public class is present, the un-extended file name should be same as the class name i.e. if the class name is Hello then the source file name should be Hello.java. If a source file does not contain any public class then name of the source file can be anything.

A source file may contain an unlimited number of non-public class definitions.

There are four top level elements that may appear in a file. None of these elements is must. If they are present, then they must appear in the following order:

  1. Package definitions
  2. import statements
  3. class and/or interface definitions
A source file may have at the most one package statement. If a package statement is present it must be the first statement in the java program. Only comments may appear before the package statements.

A source file may have zero or more import statements. As of now you can think of import statements to be like #include statements in the Java Program. If present, all the import statements must come after the package statement and before the class/interface definitions.

A source file may have any number of class and/or interface definitions but there can be at the most one public class or interface.

main() method

A source file may or may not contain a class having main() method but a standalone java program always starts its execution from main() just like a C/C++ program. So the class from which we want to start the execution  must have the main() defined in it.

The main() method must always have the following signature:

public static void main(String args[])

Note: Method prototype is referred to as signature in Java.

The void keyword preceding main() method indicates that it does not return any value. The keyword public indicates that the main method can be accessed from anywhere. The main() method must be declared public as it is called by the code, which is part of the JVM and is outside the class containing the main() method.

The main() method takes one argument, which is the array of strings. Each element of the array represents one command line argument.

The main() method can also be invoked like any other static method form anywhere in the java program. It can also be overloaded like any other Java method.

It is very common to get an exception indicating that the main() method is not present while running a java program event when the main() method is present. This happens when the signature of the main() method differs from the above mentioned signature.

Comments

A program can be documented by inserting comments wherever required. The comments are simply ignored by the compiler.

Java provides three types of comments for documentation:
  1. Single line comment
  2. Multi line comment
  3. Documentation comment
Single line Comment






A single line comment spans only one line. It can be given on any line followed by the character "//". The syntax is similar to C++.

Example

// This line is a comment and will be ignored by the compiler
x = 4*y // This is also a comment but appears after assignment statement

Multi line Comment

The syntax of multi line comment is same as C/C++. A multi line comment  is enclosed between "/*" and "*/".



Features of Java

Simple and Familiar
  1. Java does not support operator overloading.
  2. Java does not support multiple inheritence
  3. Java does not use pointers.
  4. Java code does not support global variables.
Secure

Java programs run within the JVM and they are inaccessible to other java parts. This greatly improves the security. A java program rarely hangs due to this feature. It is quite unlike C/C++ program, which hangs frequently. Java's security model has three primary compenents:
  • Class loader
  • Bytecode verifier
  • Security manager
Java uses different class loaders to load class files (executable files) from local machine and remote machines. The class loaded from remote machines like Applet classes are not allowed to read or write files on the local machine. This prevents a malicious program from damaging the local file system.

Bytecode verifier verifies the bytecode as soon as class loader completes its work. It ensures that bytecode is valid java code. It almost eliminates the possibility of java program doing some malicious activity like accessing the memory outside the JVM.

The Security Manager controls many critical operations like file deletion, creation of threads etc. These operations are allowed only if the java program have sufficient permissions otherwise security manager does not allow the operations and generates Security Exception.

Platform Independent and Portable

Java programs are platform independent. They follow the paradigm write-once-run-anywhere.
A java program written for Windows platform can be run on any other platform (Unix, Linux, Solaris etc.) simply by copying the bytecode (".class" files). You do not have to copy the source code and compile it again as in case of a C/C++ program. This feature has made the java a powerful language. You can run bytecode on any machine provided that the Java Virtual Machine. Java Virtual Machine itself is platform dependent. It is actually the jvm, which converts the bytecode into the machine code and execute them.

So we can say that Java is a portable language. one more feature which makes Java highly portable, is that Primitive data types are of fixed length irrespective of the Platform. for example an int will be always of 4 bytes in Java. This is unlike C/C++ where size of int can be 2 bytes on some machines and 4 bytes on other machines.

 Object Oriented

Java is almost pure object oriented language but it supports primitive data types like byte, short, int, long, float, double, char, boolean for the performance reasons.

Memory Management and Garbage Collection 

Memory allocation for the Java objects is completely dynamic but Java does not have support for pointer arithmetic like C/C++, which simplifies the things. Moreover you do not have to worry about freeing the memory while writing java programs.  Whenever you run a java program, JVM also run another java program (thread to be more precise) called Garbage Collector in the background. Garbage collector keeps check on the java objects. Whenever a java object is not being used it is garbage collected by the Garbage Collector i.e. the memory allocated for the object is added to the pool/heap of free memory  and can be reused. This simplifies the task of the programmer to a large extent. This also eliminates lots of bugs caused due to improper use of pointer and memory management features like freeing memory explicitly.



Multi-threaded

Java was designed to meet the real world requirement of creating interactive, networked programs. Java provides support for writing multi threaded programs to achieve this. This allows the programmer to write programs that can do many thins concurrently. For example a GUI based application might be listening to user events and taking appropriate action, a separate thread might be doing printing and a separate thread might be downloading a file from some machine across the network, all of this being concurrently. This results in better performance and better CPU utilization.

It is possible to write multi-threaded programs in other language also but it is achieved only by making use of System calls while in case of java it can be achieved by using features of the language itself.

Rich API (Application Programmer's interface) / Class Library

Java API is very rich as compared to other languages specially when it comes to Network Programming.



Robust

Most programs fail for one of the two reasons:
  1. Memory Management
  2. Exceptional conditions at run time
While designing the language one of the aim was to ensure that java programs are as robust as possible i.e. they should rarely fail. So due importance was given to the above two factors in the Java.

In Java memory allocation and de-allocation is handled in language itself, which eliminates many problems caused due to dynamic memory management features in C/C++. Java also supports object oriented exceptional handling features to handle exceptional conditions, which occur at run time. This allows a java program to recover and continue execution event after an exceptional condition occurs.

Distributed

Java is designed for the distributed environment of the Internet. Java has built in support for various TCP/IP based protocols for this purpose. In fact, accessing a resource using a URL is similar to accessing a file on the local machine. Java also has features for Remote Method Invocation, which is somewhat similar to Remote Procedure Calls (RPC), This allows objects on different computers to execute procedures remotely. Java has built in API's for this purpose called RMI, Which stands for Remote Method Invocation.

Dynamic

Every java class is a separate unit of execution. A class is loaded at the run time only when it is needed. This is normally allows us to update a class without modifying the code using it. Default mechanism for binding methods in Java is also dynamic (run time binding).



Set Jdk path

If you install the JDK in folder c:\jdk\bin Type the command below:

SET PATH=%PATH%;C:\JDK\BIN;

Saturday, 20 December 2014

Running a Java Application

When a program is compiled (C or C++ program), it is directly translated into machine code that is specific to a platform/processor. But running a java program is a two-step process. In java translation from source code to the executable code is achieved using two translators:

Java Compiler: A java program is first compiled by the java compiler to generate bytecode. Bytecode resemble machine code but it is not specific to any platform i.e. it can not be executed on a computer without further translation.


Java Interpreter: Java interpreter executes the byte code after interpreting and converting into machine code.

Example: the following java program just displays the message "Hello World" on the monitor/console.

Step1: Write the following code into file "Hello.java" using any text editor:

public class Hello{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

Note: Java is a case sensitive language


Step 2: Compile the above written java program using the command:
javac Hello.java

Step 3: Run the java program
java Hello


Output: Hello World



Java: Type of applications

  1. Standalone applications
  2. Applets
  3. Web Applications
  4. Distributed Applications

1. Standalone applications: A standalone application is a program that runs on your computer. It is more or less like a C or C++ program.

2.  Applets: An applet is a application designed to travel over the internet and to be executed on the client machine by Java compatible web browser like Firefox or google chrome. Applets are also java programs but they reside on the servers. An applet can not be executed like standalone application. Applet can be executed only by embedding it into an HTML page like an image or sound file. To run an applet you need to access an HTML page which has applet embedded into it. When the web browser downloads such an HTML page, It subsequently loads the executable file, which contains Applet and then executes it on the local machine.

3. Web Applications: Web applications run on the web server. Web applications are accessed through web clients i.e. web browsers like firefox and google chrome. Whenever you access some web site by specifying the url, you are accessing some web application written in java.

Java servlets
Java server pages
HTML

Introduction to Java

Java is an object-oriented programming language developed by Sun Microsystems Inc in 1991.

Java has become the widely used programming language for the internet. Although while designing the language, the primary objective was to develop a programming language that is platform independent.