Java - Basic Language Elelemnts

(Identifiers, keywords, literals, white spaces and comments)
This part of the java tutorial teaches you the basic language elements and syntax for the java programming language. Once you get these basic language concepts you can continue with the other object oriented programming language concepts.

KEYWORDS

There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.
    abstract    default    if            private      this
 boolean     do         implements    protected    throw
 break       double     import        public       throws
 byte        else       instanceof    return       transient
 case        extends    int           short        try
 catch       final      interface     static       void
 char        finally    long          strictfp     volatile
 class       float      native        super        while
 const       for        new           switch
 continue    goto       package       synchronized
Keywords are marked in yellow as shown in the sample code below
/** This class is a Hello World Program used to introduce the Java Language*/
    public class HelloWorld {
       public static void main(String[] args) {
       System.out.println(“Hello World”); //Prints output to console
For more information on different Keywords –    Java Keywords
Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to
the C programming language. const and goto are Java keywords. The word finalize is the name of a method
of the Object class and hence not a keyword. enum and label are not keywords.

COMMENTS

Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.
Java supports three comment styles.
     Block style comments begin with /* and terminate with */ that spans multiple lines.
     Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
    Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.

VARIABLE, IDENTIFIERS AND DATA TYPES

Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.
public class localVariableEx {
  public static int a;
  public static void main(String[] args) {
    int b;
    System.out.println("a : "+a);
    System.out.println("b : "+b);  //Compilation error
}}
Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.
data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
  • Integer: byte, short, int, and long.
  • Floating Point: float and double
  • Character: char
  • Boolean: variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.
Data TypeDefault Value (for fields)Range
byte0-127 to +128
short0-32768 to +32767
int0 
long0L 
float0.0f 
double0.0d 
char‘\u0000′0 to 65535
String (object)null 
booleanfalse 
When we declare a variable we assign it an identifier and a data type.
For Example
String message = “hello world”
In the above statement, String is the data type for the identifier message. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules
  • Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
  • Must begin with a letter, dollar sign, or an underscore
  • Are case sensitive
  • Keywords cannot be used as identifiers
  • Within a given section of your program or scope, each user defined item must have a unique identifier
  • Can be of any length.

CLASSES

A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.

OBJECTS

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

INTERFACE

An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

INSTANCE MEMBERS

Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot ‘.’ notation with a object reference is used to access Instance Members.

STATIC MEMBERS

Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above.
/** Comment
 * Displays "Hello World!" to the standard output. 

 */
public class HelloWorld {
      String output = "";
      static HelloWorld helloObj;  //Line 1 

      public HelloWorld(){
            output = "Hello World";
      } 

      public String printMessage(){
            return output;
      } 

      public static void main (String args[]) {
            helloObj = new HelloWorld();  //Line 2
            System.out.println(helloObj.printMessage());
  }

}
Class Name: HelloWorld
Object Reference: helloObj (in Line 1)
Object Created: helloObj (In Line 2)
Member Function: printMessage
Field: output (String)
Static Member: helloObj
Instance Member : output (String)

No comments:

Post a Comment