Java - Basic Syntax

JAVA - BASIC SYNTAX



Copyright ? tutorials

When we consider a Java program it can be defined as a collect ion of object s t hat communicat e via invoking each ot her's met hods. Let us now briefly look int o what do class, object , met hods and inst ance variables mean.

Object - Object s have st at es and behaviors. Example: A dog has st at es - color, name, breed as well as behaviors -wagging, barking, eat ing. An object is an inst ance of a class. Class - A class can be defined as a t emplat e/ blue print t hat describes t he behaviors/st at es t hat object of it s t ype support . Metho ds - A met hod is basically a behavior. A class can cont ain many met hods. It is in met hods where t he logics are writ t en, dat a is manipulat ed and all t he act ions are execut ed. Instance Variables - Each object has it s unique set of inst ance variables. An object 's st at e is creat ed by t he values assigned t o t hese inst ance variables.

First Java Program:

Let us look at a simple code t hat would print t he words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program. * This will print 'Hello World' as the output */

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

} }

Let 's look at how t o save t he file, compile and run t he program. Please follow t he st eps given below: Open not epad and add t he code as above. Save t he file as: MyFirst JavaProgram.java. Open a command prompt window and go o t he direct ory where you saved t he class. Assume it 's C:\. Type ' javac MyFirst JavaProgram.java ' and press ent er t o compile your code. If t here are no errors in your code, t he command prompt will t ake you t o t he next line (Assumpt ion : The pat h variable is set ). Now, t ype ' java MyFirst JavaProgram ' t o run your program. You will be able t o see ' Hello World ' print ed on t he window.

C : > javac MyFirstJavaProgram.java C : > java MyFirstJavaProgram Hello World

Basic Synt ax:

About Java programs, it is very import ant t o keep in mind t he following point s. Case Sensitivity - Java is case sensit ive, which means ident ifier Hello and hello would have different meaning in Java. Class Names - For all class names t he first let t er should be in Upper Case.

If several words are used t o form a name of t he class, each inner word's first let t er should be in

Upper Case. Example class MyFirstJavaClass Metho d Names - All met hod names should st art wit h a Lower Case let t er. If several words are used t o form t he name of t he met hod, t hen each inner word's first let t er should be in Upper Case. Example public void myMethodName() Pro gram File Name - Name of t he program file should exact ly mat ch t he class name. When saving t he file, you should save it using t he class name (Remember Java is case sensit ive) and append '.java' t o t he end of t he name (if t he file name and t he class name do not mat ch your program will not compile). Example : Assume 'MyFirst JavaProgram' is t he class name. Then t he file should be saved as 'MyFirstJavaProgram.java' public static vo id main(String args[]) - Java program processing st art s from t he main() met hod which is a mandat ory part of every Java program..

Java Ident ifiers:

All Java component s require names. Names used for classes, variables and met hods are called ident ifiers. In Java, t here are several point s t o remember about ident ifiers. They are as follows:

All ident ifiers should begin wit h a let t er (A t o Z or a t o z), currency charact er ($) or an underscore (_). Aft er t he first charact er ident ifiers can have any combinat ion of charact ers. A key word cannot be used as an ident ifier. Most import ant ly ident ifiers are case sensit ive. Examples of legal ident ifiers: age, $salary, _value, __1_value Examples of illegal ident ifiers: 123abc, -salary

Java Modifiers:

Like ot her languages, it is possible t o modify classes, met hods, et c., by using modifiers. There are t wo cat egories of modifiers:

Access Mo difiers: default , public , prot ect ed, privat e No n-access Mo difiers: final, abst ract , st rict fp We will be looking int o more det ails about modifiers in t he next sect ion.

Java Variables:

We would see following t ype of variables in Java: Local Variables Class Variables (St at ic Variables) Inst ance Variables (Non-st at ic variables)

Java Arrays:

Arrays are object s t hat st ore mult iple variables of t he same t ype. However, an array it self is an

object on t he heap. We will look int o how t o declare, const ruct and init ialize in t he upcoming chapt ers.

Java Enums:

Enums were int roduced in java 5.0. Enums rest rict a variable t o have one of only a few predefined values. The values in t his enumerat ed list are called enums.

Wit h t he use of enums it is possible t o reduce t he number of bugs in your code.

For example, if we consider an applicat ion for a fresh juice shop, it would be possible t o rest rict t he glass size t o small, medium and large. This would make sure t hat it would not allow anyone t o order any size ot her t han t he small, medium or large.

Example:

class FreshJuice {

enum FreshJuiceSize{ SMALL, MEDIUM, LARGE } FreshJuiceSize size; }

public class FreshJuiceTest {

public static void main(String args[]){ FreshJuice juice = new FreshJuice(); juice.size = FreshJuice. FreshJuiceSize.MEDIUM ; System.out.println("Size: " + juice.size);

} }

Above example will produce t he following result :

Size: MEDIUM

No te: enums can be declared as t heir own or inside a class. Met hods, variables, const ruct ors can be defined inside enums as well.

Java Keywords:

The following list shows t he reserved words in Java. These reserved words may not be used as const ant or variable or any ot her ident ifier names.

abst ract assert

boolean break

byt e

case

cat ch

char

class

const

cont inue default

do

double

else

enum

ext ends final

f inally

f loat

for

got o

if

implement s

import inst anceof

int

int erface

long

nat ive

new

package

privat e prot ect ed

public

ret urn

short

st at ic

st rict fp super

swit ch synchronized t his

t hrow

t hrows t ransient

t ry

void

volat ile while

Comment s in Java

Java support s single-line and mult i-line comment s very similar t o c and c++. All charact ers 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");

} }

Using Blank Lines:

A line cont aining only whit espace, possibly wit h a comment , is known as a blank line, and Java t ot ally ignores it .

Inherit ance:

In Java, classes can be derived from classes. Basically if you need t o creat e a new class and here is already a class t hat has some of t he code you require, t hen it is possible t o derive your new class from t he already exist ing code.

This concept allows you t o reuse t he fields and met hods of t he exist ing class wit hout having t o rewrit e t he code in a new class. In t his scenario t he exist ing class is called t he superclass and t he derived class is called t he subclass.

Int erfaces:

In Java language, an int erface can be defined as a cont ract bet ween object s on how t o communicat e wit h each ot her. Int erfaces play a vit al role when it comes t o t he concept of inherit ance.

An int erface defines t he met hods, a deriving class(subclass) should use. But t he implement at ion of t he met hods is t ot ally up t o t he subclass.

What is Next ?

The next sect ion explains about Object s and classes in Java programming. At t he end of t he session you will be able t o get a clear pict ure as t o what are object s and what are classes in Java.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download