Search This Blog

Saturday, 31 December 2011

Class Libraries in Java


println( ) and print( ). As mentioned, these methods are members of the System class,
which is a class predefined by Java that is automatically included in your programs. In the
larger view, the Java environment relies on several built-in class libraries that contain many
built-in methods that provide support for such things as I/O, string handling, networking,
and graphics. The standard classes also provide support for windowed output. Thus, Java
as a totality is a combination of the Java language itself, plus its standard classes. As you
will see, the class libraries provide much of the functionality that comes with Java. Indeed,
part of becoming a Java programmer is learning to use the standard Java classes.


Friday, 30 December 2011

Lexical Issues ( atomic elements of Java )


Now that you have seen several short Java programs, it is time to more formally describe
the atomic elements of Java. Java programs are a collection of 

  • whitespace 
  • identifiers
  • comments
  • literals
  • operators
  • separators
  • keywords
Whitespace 


Java is a free-form language. This means that you do not need to follow any special
indentation rules. For example, the Example program could have been written all on one
line or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator
or separator. In Java, whitespace is a space, tab, or newline.

Identifiers

Identifiers are used for class names, method names, and variable names. An identifier
may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. They must not begin with a number, lest they be
confused with a numeric literal. Again, Java is case-sensitive, so VALUE is a different
identifier than Value.
Some examples of valid identifiers are:

HighTemp     temp    h8      $low         this_is_ok


Invalid variable names include:


2temp      low-temp    Yes/ok

Comments

As mentioned, there are three types of comments defined by Java. You have already
seen two: 
1) single-line( // ) 
2) multiline.  //
                  //

The third type is called a documentation comment.
This type of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a 
/* and ends with a */.

literals


A constant value in Java is created by using a literal representation of it. For example,
here are some literals:

100                             literal specifies an integer
98.6                            literal specifies a floating-point value
'X'                               literal specifies is a character constant
"This is a test"              literal specifies  is a string

 A literal can be used anywhere a value of
its type is allowed.


Separators

In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon. As you have seen, it is used to terminate
statements. The separators are shown in the following table:
Symbol                       Name                             Purpose
( )                             Parentheses        Used to contain lists of parameters in method
                                                          definition and invocation. Also used for defining
                                                          precedence in expressions, containing expressions in
                                                          control statements, and surrounding cast types.

{ }                             Braces              Used to contain the values of automatically initialized
                                                           arrays. Also used to define a block of code, for
                                                           classes, methods, and local scopes.

[ ]                              Brackets            Used to declare array types. Also used when
                                                           dereferencing array values.

;                                Semicolon           Terminates statements.

,                                Comma               Separates consecutive identifiers in a variable
                                                           declaration. Also used to chain statements together
                                                            inside a for statement.

.                                 Period               Used to separate package names from subpackages
                                                           and classes. Also used to separate a variable or
                                                           method from a reference variable.


Keywords in Java

There are 48 reserved keywords currently defined in the Java language.
These keywords, combined with the syntax of the operators and separators, form the
definition of the Java language. These keywords cannot be used as names for a variable,
class, or method

abstract   const   Finally   int   Public   this   boolean   continue   Float   interface   Return   throw
break   default    For      long   Short    throws    byte      do         Goto    native      Static   transient
case     double     If        new   Strictfp   try      catch     else     Implements       package     Super
void      char     extends    Import   private    Switch    volatile   class     final    Instanceof   protected
Synchronized    while

The keywords const and goto are reserved but not used.
In addition to the keywords, Java reserves the following: true, false, and null. These are
values defined by Java. You may not use these words for the names of variables, classes,
and so on.

Using Blocks of Code ( Code blocks )

Java allows two or more statements to be grouped into blocks of code also called code blocks.This is done by enclosing the statement between opening and closing curly braces.A block of statement should be a logical statement. It works a particular task. For example, a block can be a target for Java's if and for statement


if ( x < y ) {  // Block begins


     x = y;
     y = 0;
}                //Blocks end


Here, if value of x is less than y then we enters the code block for execution. What ever we given in the code block it will execute
Lets look at another example. The following program uses a block of code as the target of a for loop

class BlockTest {
public static void main ( String args [ ] )  {

int x, y;
y = 20;

for ( x = 0; x < 10; x++) {
   System.out.println ( " This is X= " +x);
   System.out.println ( " This is Y= " +y);
   y = y - 2;
   }
 }
}

Thursday, 29 December 2011

The for Loop with Example


The for loop is the type of  looping construct. It also works as while loop construct but it provide the initialization, condition and the increment  is same written in the for construct. All the statements which has to be executed written in the for block

The Syntax for the For Loop:  
  for( initialization; termination; increment)
  {
  statements;
  }

Example

public class  ForLoop {
  public static void main(String[] args) {
  for(int i = 1;i <= 5;i++) {
  System.out.print(i);
  }
  }
}

if Control Statements with example

The if Statement


The if statement encloses some code which is executed only if a condition is true. The general syntax of the if statement is:



if (condition) {
    body-code
}
The if statement has two parts. The condition is a boolean expression which resolves to either true or false. Thebody-code is code that will be executed only if the condition is true. Here is an example of the if statement.
Example
// Returns 0 if s is null
public int getLength(String s) {
    if (s == null) {
        // This line of code is execute only if s is null
        return 0;
    }
    return s.length();
}

The if statement also has an optional else part which encloses some code that is executed only if the condition is false. Here is the general syntax of the if statement with the optional else part:

The if Statement with else

if (condition) {
    body-code
} else {
    else-code
}
The else-code is executed only if condition resolves to false. Here is an example of the if statement with the optionalelse part
Example
// Generates a random number and prints whether it is even or odd
if ((int)(Math.random()*100)%2 == 0) {
    System.out.println("The number is even");
} else {
    System.out.println("The number is odd");
}
The else-code part can also be another if statement. An if statement written this way sets up a sequence ofcondition's, each tested one after the other in top-down order. If one of the conditions is found to be true, the body-code for that if statement is executed. Once executed, no other conditions are tested and execution continues after the sequence. Here is an example of a sequence of if/else/if statements

Wednesday, 28 December 2011

Compiling The Java Program With environment variables

In WINDOWS 2000 you do not use AUTOEXEC.BAT file. Instead you create environment variables. On your computer desktop right click the My Computer icon and select Properties.

On the System Properties window select Advance tab.


On Windows 7 select Start, right click Computer. Click Advance System setting on System properties window select Advance tab, Click Environment Variables button
On Windows XP, to get to the same System Properties window, select Start, Select Control panel,
In the opened Control panel select Performance and Maintenance (it is ar the bottom),



Select System, Advance tab.



Click the Environmental Variables button. Environment Variables window displays.


Click New button in System variables frame at the bottom of the Environment Variables Window. For Java SDK enter Path environment variable and.


enter path to JAVA bin folder on your PC. On mine it is C:\j2sdk1.4.0\bin. Type semicolon at the end. If you installed tomcat after java type path to tomcat bin folder on your PC. On mine it is C:\j2sdk1.4.0\bin;C:\jakarta-tomcat-4.1.29\bin;. Do not forget to type semicolon. Click OK button. Click OK button on Environment Variables window. Click OK button on Properties window.
To execute Java program create CLASSPATH environment variable.




For Tomcat enter CATALINA_HOME environment variable name and path to the folder where your tomcat installed. On mine it is C:\jakarta-tomcat-4.1.29


To run Tomcat you need to create JAVA_HOME environment variable. To check your configuration for Tomcat go to C:\jakarta-tomcat-4.1.29\bin directory, type startup and press enter.


Tomcat starts in separate command prompt window.












If Tomcat does not start, probably you have not enough memory set in command prompt. Go to command prompt menu on your desktop and right click it

From drop down menu select properties. Select memory tab. Increase convention memory and click OK to save changes.


Close command prompt if you had it open. Open again and try to start Tomcat.
Now it should be started. To make sure that Tomcat is running properly, open Internet Explored and type URL address:
http://localhost:8080
Tomcat home page displays.



Java Objects with Example


Objects

Object-oriented programming focuses on constructs called “objects.” An object consists of data and functions known as methods which use or change the data. (Methods are similar to procedures or functions in other languages.)

 Objects of the same kind are said to have the same type or be in the same class. A class defines what data can be in an object, and what operations are performed by the methods. One or more objects can be created or “instantiated” from a class.

 The structure of a Java program consists of various objects exchanging messages. The keyword class defines a blueprint for objects with similar properties.

 In our first example we define the class Particle

public class Particle
{
   double x, y, vx, vy, mass;
}

This class does not do anything (because it has no methods), but it can be used to describe a particle by its position, velocity, and mass. For simplicity, we will consider only two dimensions.

What is Java?



  • A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web.


  • Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT).

  • Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java-compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.