Java Syntax

The syntax of the Java programming language is the set of rules defining how a Java program is written and interpreted. The syntax is mostly derived from C and C++. Unlike C++, Java is almost exclusively an object-oriented language. There are no global functions or variables, all code belongs to classes and all values are objects. The only exception is the primitive types, which are not represented by a class instance due to performance reasons (though can be automatically converted to objects and vice-versa via auto boxing). Some features like operator overloading or unsigned integer types are omitted to simplify the language and to avoid possible programming mistakes. Java syntax is constantly improved in major JDK releases. The latest improvements to the language happened in Java SE 7, which introduced such language features as try-with-resources statements and binary literals.
public void processData()

{
    do 

    { 

        int data = getData(); 

        if(data < 0) 

            performoperation1(data); 

        else 

            performoperation2(data); 

    } 

    while(hasMoreData()); 

}
A snippet of Java code with keywords highlighted in bold font.

Object > Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. 

Class > A class in the context of Java are templates that are used to create objects and to define object data types and methods. Core properties include the data types and methods that may be used by the object. All class objects should have the basic class properties. Classes are groups and objects are items within each group. 

Methods > A method in Java is a block of statements that has a name and can be executed by calling (also called invoking) it from some other place in your program. Along with fields, methods are one of the two elements that are considered members of a class. 

Instance Variables > In object oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable is similar to and contrasts with a class variable. An instance variable is not a Class variable. It is a type of class attribute (class property, field, or data member). The same dichotomy between instance and class members applies to methods ("member functions") as well; a class may have both instance methods and class methods. Each class variable and instance variable you invoke with the object lives in memory for the life of that object. Instance variables are properties an object knows about itself. All instances of an object have their own copies of instance variables, even if the value is the same from one object to another. One object instance can change values of its instance variables without affecting all other instances. Instance variables can be used by all methods of a class unless the method is declared as static.

First Coding with Java Programming Language

 

 Start your coding with Java Programming Language:
public class MyFirstJavaProgram {
    public static void main(String []args) {
       System.out.println("Welcome to my world! This is my first java program. It is just beginning my friend’s, picture is still remaining.");
    }
} 
Now we are going to see how to save Java file and compile and run it using notepad. Just try yourself:

Step – 01 > Open notepad and write the code as above.

Step – 02 > Save the file as: MyFirstJavaProgram.java.

Step – 03 > Open a command prompt window and go o the directory where you saved the class. May be it is in C:\.

Step – 04 > Now type javac then press spacebar once and then type MyFirstJavaProgram.java (javac MyFirstJavaProgram.java) then press enter to compile your written code. If there are no error found in the code then command prompt will reach you to the next line.

Step – 05 > Now type javac then press spacebar once and then type MyFirstJavaProgram (javac MyFirstJavaProgram) then press enter  to run your program.

Step – 06 > Now you will get output on your screen: Welcome to my world! This is my first java program. It is just beginning my friend’s, picture is still remaining.

Just run your command window and type following:

C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
Welcome to my world! This is my first java program. It is just beginning my friend’s, picture is still remaining.

Now we are going to see how to save Java file, compile and run the program using Eclipse IDE. Just try yourself:

When you develop Java applications in Eclipse, it stores all the created files in a directory called "workspace". When Eclipse is run for the first time, it will ask you where you want the workspace to be placed:

You can just use the default location or specify your preferred location. To avoid getting asked this question every time you start Eclipse, check "Use this as the default and do not ask again" option and press "OK" button. Once Eclipse finishes its startup process, you will see the welcome window.

Click the "Workbench" icon on the right, which will lead you to the main Eclipse window.

Now that you've got Eclipse up and running, it's time to create your first Java project. To do this, you'll want to go File -> New -> Java Project. After doing so, you'll see a window.

Type your project name (hellowordl) in the "Project name" field and click Finish. Then the name of your newly created project will appear on the left side of the Eclipse window (this part of the window is called "Package explorer pane").

As you create more projects in Eclipse, other project names will appear in the Package explorer pane and you will be able to switch between your projects by clicking the name of a project.

Now that you have created your first project, now you want to create a new Java file with .java extension and add it into your project. To create a new Java file, right click on the name of your project (helloworld) in the Package explorer pane and select New -> Class and click. This command will show you a window.

In the "Name: " field provides the name of the file (or the class) you want to create, MyFirstJavaProgram then click "Finish" button.

Congratulations! Now you have created your first Java code with Eclipse IDE. As you can see from the Package explore pane, your project now includes MyFirstJavaProgram.java file. The "Editor pane" to the right of the Package explorer pane shows the actual content of the MyFirstJavaProgram.java file, which simply declares MyFirstJavaProgram as a public class. You can edit the content of the Java code inside the Editor pane.

Save and compile and run Java code in Eclipse IDE

Now let us learn how to compile and run (java code) a Java program in Eclipse. Now write the Java code inside the Editor pane.
public class MyFirstJavaProgram {
    public static void main(String []args) {
       System.out.println("Welcome to my world! This is my first java program. It is just beginning my friend’s, picture is still remaining.");
    }
} 
Now save the file by selecting File->Save, or pressing Ctrl-S (Option-S on Mac). When you save a Java file, Eclipse will automatically compile the file also, so, that you do not need to compile it later when you want to run it.

Now that your code has been saved and compiled, you can run your program by selecting Run -> Run, or by pressing Ctrl-F11 (Option-F11 on Mac) or by clicking on the "Run" button near the top of the window. Once your program finishes running, you will be able to see the output of your program by selecting the "Console tab" at the bottom of the window.

You can exit eclipse by using any of the following alternatives: 

Hit the X in the upper right corner
or,
Select File -> Exit 

Now you have learned the very basic functionality of Eclipse. Eclipse supports many more functionality than what you just learned, including integrated debugging and automatic code completion and method lookup, etc.

Basic Syntax of Java Programming Language:

 

In Java Programming Language it is very essential to remember these for better coding:

 

Java is case sensitive: Java is case sensitive that means identifier Welcome and welcome is not same, both has different meaning in Java OOP.

Class names in Java OOP: In Java Programming Language all class names the first letter should be in UPPER CASE.

If you use more than one word to form a name of the class then every inner word is start with CAPITAL LETTER. Its mean all separate word's first letter should be write in UPPER CASE.

For example:
class MyFirstJavaClass

Methods names in Java OOP: All methods names should start with lower case letter (small letter).

If you use more than one word to form a name of the method then every inner word is start with CAPITAL LETTER. Its mean all separate word's first letter should be write in UPPER CASE.

For example: public void startMethodName()

In Java program file name: Name of program file should be same as class name otherwise program will not compile.

When saving the file, you should save it using the class name and end of the name add .java extension. If you do not write same name as class name in file saving time, your program will unable to compile, when you will want to compile it.

For example: MyFirstJavaProgram is a class name, so, file should be saved as MyFirstJavaProgram.java

In Java OOP public static void main(String args[]): Java program processing start with the main() method which is mandatory part of all Java Program.

Identifiers of Java Programming Language:

 

An identifier is a sequence of one or more characters. An identifier is a name given to a package, class, interface, method, or variable. It allows a programmer to refer to the item from other places in the program. To make the most out of the identifiers you choose make them meaningful. Every Java components require a name. Name used for classes, variables and methods are called identifiers.

In Java Programming Language it is very essential to remember about identifiers for better coding:

 

Few things to remember when choosing an identifier:


Reserved words cannot be used.

They cannot start with a digit but digits can be used after the first character (e.g., name5, name2name are valid identifier).

The only symbols you can use are the underscore (i.e., "_") and dollar sign (i.e., "$").

Remember that identifiers are case sensitive.

An identifier cannot be the same as a query language keyword. 

Here is a list of query language keywords:
ABS 
ALL 
AND 
ANY 
AS 
ASC 
AVG 
BETWEEN 
BIT_LENGTH 
BOTH 
BY 
CASE 
CHAR_LENGTH 
CHARACTER_LENGTH 
CLASS 
COALESCE 
CONCAT 
COUNT 
CURRENT_DATE 
CURRENT_TIMESTAMP 
DELETE 
DESC 
DISTINCT 
ELSE 
EMPTY 
END 
ENTRY 
ESCAPE 
EXISTS 
FALSE 
FETCH 
FROM 
GROUP 
HAVING 
IN 
INDEX 
INNER 
IS 
JOIN 
KEY 
LEADING 
LEFT 
LENGTH 
LIKE 
LOCATE 
LOWER 
MAX 
MEMBER 
MIN 
MOD 
NEW 
NOT 
NULL 
NULLIF 
OBJECT 
OF 
OR 
ORDER 
OUTER 
POSITION 
SELECT 
SET 
SIZE 
SOME 
SQRT 
SUBSTRING 
SUM 
THEN 
TRAILING 
TRIM 
TRUE 
TYPE 
UNKNOWN 
UPDATE 
UPPER 
VALUE 
WHEN 
WHERE 
It is not recommended that you use an SQL keyword as an identifier.

Examples of Valid Identifiers

Here are some valid identifiers:

xyz
sales_tax
_circleArea
box25width
$directory
xyz1234$$ 

Examples of Invalid Identifiers

It's easy to make a mistake and use a illegal identifier.

1xyz (ERROR: first character starts with a digit)
num-oranges (ERROR: dash is not permitted in identifiers)
num oranges (ERROR: space is not permitted in identifiers) 
 

Modifiers in Java Programming Language:

Modifiers are keywords that are added to change meaning of a definition. In Java Programming Language, modifiers are categorized into two types. The modifiers are:

Access control modifier: default, public , protected, private

Non Access Modifier: final, abstract, strictfp, static, transient, synchronized, volatile

Click here to know details about modifiers.

Variables in Java Programming Language

There are three types of variable in Java:
>> Local variable


Arrays in Java Programming Language:

In the Java programming language, arrays are objects are dynamically created, and may be assigned to variables of type Object, that use to store multiple variables of the same type.

Enums in Java Programming Language: 

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they are constants, the names of an enum type's fields are in UPPERCASE LETTERS. In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days of the week enum type as: 
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time. For example, the choices on a menu, command line flags, and so on. Here is some code that shows you how to use the Day enum defined above:
public class EnumTest {
    Day day;
    
    public EnumTest(Day day) {
        this.day = day;
    }
    
    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
                    
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
                         
            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;
                        
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }
    
    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}
The output is:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.
for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}
[Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.]

In the following example, Planet is an enum type that represents the planets in the solar system. They are defined with constant mass and radius properties.

Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.

[Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.]

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet ");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}
If you run Planet.class from the command line with an argument of 175, you get this output:
$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413 
Reference: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 
Regularly visit this site to get new information about Java Programming Language. Today, it is a robust and most powerful programming language in the Universe.