Monday, 26 December 2011

Structure of a Java Program

Structure of Java Program

A Java program with two classes


class Room
{
float length;
float breadth;
void getdata(float a, float b)
{
length=a;
breadth=b;
}
}

class RoomArea
{
public static void main(String args[])
{
float area;
Room room1 = new Room();//Create an object room1 from the class Room
room1.getdata(15,20);
area=room1.length * room1.breadth;
System.out.println("Area = "+area);
}
}

A Simple Java Program

class Sample
{
public static void main(String args[])
{
System.out.println("Java is pure OOP");
}
}


Now Understanding the program



The first line



class Sample



declare a class, which is an object oriented construct. Java is a pure object oriented language so everything in java must be placed inside a class. class is a keyword and used to declare a new class definition. Sample is a java identifier that specifies the name of the class to be defined.



The Braces { & }



In java every class definition begins with an open brace “{“ and end with a matching closing brace “}” just like in C++. But 1 thing to remember , in C++ class definition ends with a semicolon “;” but in java it’s not.



For example



In C++



class SampleCPPclass
{
//Body of the class
};//Semicolone required





In Java



class SampleCPPclass
{
//Body of the class
}//Semicolone not required


The main method



The line “public static void main(String args[])” defines a method named main. This is similar to the main() function in C/C++. Every Java program must include the main method because this is the entry point for the interpreter to begin the execution of the program. But the Java Applets will not use the main method.



Now the keywords public, static & void



public : The keyword public is an access specifier that declares the main method as unprotected so it can accessible to all other classes.



static: The keyword static declares main method as one that belongs to the entire class and not a part of any objects of the class. In Java the main method must always declared as static since  the Java interpreter uses this method before any objects are created.



void : The keyword void is a type modifier states that the main method does not return any value.



The Output Line



The line “System.out.println("Java is pure OOP");” is similar to the printf() statement of C or cout<< construct of C++. Since Java is a pure OOL, every method must be a part of an object. Here the println() method is a member of the out object, which is a static data member of System class.



This program will print the string “Java is pure OOP”

Tuesday, 15 November 2011

Life Cycle of a java program


The figure below explains the lifecycle of a Java Program. In words, the figure can be explained as:
  1. A Java program is written using either a Text Editor like Textpad or an IDE like Eclipse and is saved as a .java file. (Program.java)
  2. The .java file is then compiled using Java compiler and a .class file is obtained from it. (Program.class)
  3. The .class file is now portable and can be used to run this Java program in any platform.
  4. Class file (Program.class) is interpreted by the JVM installed on a particular platform. JVM is part of the JRE software.

Web Browsers

web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier (URI) and may be a web page, image, video, or other piece of content. Hyperlinks present in resources enable users easily to navigate their browsers to related resources. A web browser can also be defined as an application software or program designed to enable users to access, retrieve and view documents and other resources on the Internet.

Example of Web browsers :


  • HotJava
  • Netscape Navigator
  • Internet Explorer
HotJava :
        HotJava (later called HotJava Browser to distinguish it from HotJava Views) was a modular, extensible web browser from Sun Microsystems implemented in Java. It was the first browser to support Java applets, and was Sun's demonstration platform for the then new technology. It has since been discontinued and is now no longer supported.

Netscape Navigator:
        Netscape Navigator was a proprietary web browser that was popular in the 1990s. It was the flagship product of the Netscape Communications Corporation and the dominant web browser in terms of usage share. It can run Java Applets
        It has many useful features such as visual display about downloading process and indication of the number bytes downloaded. It also supports JavaScript, a scripting language used in HTML documents.

Internet Explorer:
        Windows Internet Explorer (formerly Microsoft Internet Explorer, commonly abbreviated IE or MSIE) is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It use a just-in-time (JIT) compiler which greatly increase the speed of execution.

Java as an Internet Language


Java is an object oriented language and a very simple language. Because it has no space for complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling set up boxes and devices. But later new features were added to it and it was renamed as Java. Java became a general purpose language that had many features to support it as the internet language. Few of the features that favors it to be an internet language are:
Cross Platform Compatibility:  The java source files (java files with .java extension) after compilation generates the bytecode (the files with .class extension) which is further converted into the machine code by the interpreter. The byte code once generated can execute on any machine having a JVM. Every operating system has it's unique Java Virtual Machine (JVM) and the Java Runtime Environment (JRE).
Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc .
Support to HTML: Most of the programming languages that are used for web application uses the html pages as a view to interact with the user. Java programming language provide it's support to html. For example. Recently the extension package jipxhtml is developed in java to parse and create the html 4.0 documents.
Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides the mechanism to retrieve the values from respective fields and accordingly creates the java objects. These objects enables to invoke methods to achieve the desired functionality.
Support to  XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different applications  over the internet.
Support to  Web Services : Java has a rich variety of APIs to use xml technology in diverse applications that supports  N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It  makes java a most suited internet language.
Support to java enabled Mobile devices: Java programming language is made in such a way so that it is compatible with mobile devices also. Java language also works with any java enabled mobile devices that support MIDP 1.0/2.0 including the symbian OS mobile devices. 
Support to Personal Digital Assistants: Java language is compatible with Personal Java 1.1 such as chaiVM, Jeode, CrEME, and JV-Lite2 or with all the later version and it also support PDAs like HP/Compaq, iPAQ, Fujitsu-Siemens Pocket Loox and SimPad, HHP, NEC, Samsung, Sharp Electronics, Toshiba, psion m5, and any other device with Windows CE/Pocket PC 2002/2003/2005)

Features of Java


Simple:
        The syntax for Java is like a cleanup version of the syntax of C++. Their is no need for header file pointer arithmetic structures, union , operator overloading and virtual base class and so on...
        Another aspect for being simple is being small. Java enable the construction of software that can run stand alone in a small machine. The size of the basic interpreter and class support is only 40 KB (approx).

Object oriented:
        Java is a object oriented language. Almost everything in java is an object. All program code and data reside within class and objects. The objects model in java is simple and easy to extend.
Distributed :
        Java is designed as a distributed ;language for creating application of networks. It has the ability to share bot data and programs. Java application can open and access a remote object on internet as easy as they can do in a local system. This enables multiple programs at multiple remote locations to collaborate and work together in a single project.

Robust:
        Java is a robust language. It provides many save guards to ensure many reliable code. It has strict compile time and run time checking for data types. This feature is also very useful. The java compiler detects many problems that in other language would show up only at run time.

Secure:
        Security becomes an important issue for a language that is used for programming on internet. Threat of viruses and abuse of resource are everywhere. Java system not only verify all memory access but also ensure that no viruses are communicated with an applet . The absence of pointer in Java ensure that programs can not gain access to memory location without proper authorization.

Architecture Neutral:
        The compiler generate an architecture-neutral file format.  The compiled code is executable in many processors, if given the presence of the java run time system. The Java compiler does this by generating bytecode instruction, which have nothing to do a particular computer architecture rather they are designed to both easy to interpret and easily translated to native machine code in the fly.

Portable:
        Unlike C and C++ there are no "implementation dependents" - aspect of the specification. The size of the preemptive data types are specified as is the behavior of arithmetic on them. For example an int in Java is always a 32 bit Integer. In C/C++ int can mean a 16 bit Integer, a 32 bit Integer or any other size that the compiler vendor likes.

Compiled & Interpreted :
        Usually a Computer language is either compiled or Interpreted. Java combines both of these approaches. Thus making Java a two state system. First Java Compiler translate secure code into bytecode instruction. Bytecode are not machine instruction and therefore in the second stage Java interpreter generates machine code that can be directly executed by the machine, that is running the Java program.

High performance:
        Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode. Java architecture is also deigned to reduce overhead during run-time, further the incorporation of multireading enhances the overall execution speed of Java programs.

Multithreaded :
        Multithreaded means handling multiple tasks simultaneously. java supports multithreaded programs, this means that we need not wait for the application to finish one task before beginning another. For example we can listen to any audio clip while scrolling a page and at the same time download an applet from a distant computer. The benefits of multithreding are better interactive responsiveness and real time behavior. Threads in Java also can take advantages of multiprocessor system, if the base operating system does so.

Dynamic :
        Java is a dynamic language. Java is capable of dynamic linking in new class libraries, methods, objects. Java can also determine the type of class through a query, making it possible to either dynamically link of abort the program, depending on the response.

Difference between Java & C++

Java is a true object oriented language while C++ is basically C with object-oriented extension. That is what exactly the increment operator ++ indicates. C++ has maintained backward compatibility with C. It is therefore possible to write and old style C program and run it successfully in C++. Java appears to be simile to C++ when we consider only the "extension" part of C++. However, some object-oriented features of C++ make the C++ code extremely difficult to follow and maintain. 

Difference between Java & C


Java i s lot like C but the major difference between Java and C is that Java is an object-oriented langugae and has mechanism to define classes and objects. To build a simple and safe language, the Java team did not include some of the C features in Java.


  • Java does not include the C unique statement keywords sizeof, and typedef.
  • Java does not contain the data types struct and union.
  • Java does not define the type modifiers keywords auto,extern,register,signed, and unsigned
  • Java does not support an explicit pointer type.
  • Java does not have a preprocessor and therefore we can not use #define, #include, and #ifdef statements.
  • Java requires that the function with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.
  • Java adds new operators such as instanceof and >>>.
  • Java adds labelled break and continue statements.
  • Java adds many features required for object oriented programming.

Saturday, 12 November 2011

Basic Concept of Object Oriented Programming

Objects & Classes:

Objects are the basic runtime entities in an Object-Orients System. They may represent a person, a bank, a car etc… Each object has its own properties and behavior.  For example if we chose a CAR as an object then its properties will be number of wheels, height, width, length, body material etc, and its behavior will be run, turn left, turn right, turn backward etc..

j1                                                                                                                                                     

But in a programming domain objects interacts with each other by sending massages. Like a User account interact with a Bank Account…

 

In programming view an object is a combination of some data and code.  These data and code of an object can be made a user defined data type using the concept of a Class.  So what is class?

 

1.       If we taught class as a Data type then objects will be the variable of this Data type.

2.       If we taught class as a blueprint of a building then the building is an object.

3.       If we taught class as a recipe then the cocked food is an object.

Basic Concept of Object Oriented Programming


Objects & Classes:


Objects are the basic runtime entities in an Object-Orients System. They may represent a person, a bank, a car etc… Each object has its own properties and behavior.  For example if we chose a CAR as an object then its properties will be number of wheels, height, width, length, body material etc, and its behavior will be run, turn left, turn right, turn backward etc..





                                                                                                                                                                                                     
But in a programming domain objects interacts with each other by sending massages. Like a User account interact with a Bank Account…

In programming view an object is a combination of some data and code.  These data and code of an object can be made a user defined data type using the concept of a Class.  So what is class?

1.       If we taught class as a Data type then objects will be the variable of this Data type.
2.       If we taught class as a blueprint of a building then the building is an object.
3.       If we taught class as a recipe then the cocked food is an object.

Friday, 11 February 2011

Expressions in PHP

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an
expression. The simplest yet most accurate way to define an expression is "anything that has a value".The most basic forms of expressions are constants and variables. When you type "$a = 5", you’re assigning ’5’ into $a. ’5’, obviously, has the value 5, or in other words ’5’ is an expression with the value of 5 (in this case, ’5’ is an integer constant). After this assignment, you’d expect $a’s value to be 5 as well, so if you wrote $b = $a, you’d expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following

   1: function foo () {
   2: return 5;
   3: }


Assuming you’re familiar with the concept of functions (if you’re not, take a look at the chapter about
functions), you’d assume that typing $c = foo() is essentially just like writing$c = 5, and you’re
right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression ’foo()’ is 5. Usually functions don’t just return a static value but compute something.



Of course, values in PHP don’t have to be integers, and very often they aren’t. PHP supports three scalar value types: integer values, floating point values and string values (scalar values are values that you can’t ’break’ into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.



So far, users of PHP/FI 2 shouldn’t feel any change. However, PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we’ve already dealt with, ’$a = 5’. It’s easy to see that there are two values involved here, the value of the integer constant ’5’, and the value of $a which is being updated to 5 as well. But the truth is that there’s one additional value involved here, and that’s the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that ’$a = 5’, regardless of what it does, is an expression with the value 5. Thus, writing something like ’$b = ($a = 5)’ is like writing ’$a = 5; $b = 5;’ (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write ’$b = $a = 5’.


Another good example of expression orientation is pre- and post-increment and decrement. Users of
PHP/FI 2 and many other languages may be familiar with the notation of variable++ and variable–.
These are increment and decrement operators. In PHP/FI 2, the statement ’$a++’ has no value (is not an expression), and thus you can’t assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. The difference is with the value of the increment expression. Pre-increment, which is written ’++$variable’, evaluates to the incremented value (PHP increments the variable before reading its value, thus the name ’pre-increment’). Post-increment, which is written ’$variable++’ evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name ’post-increment’). A very common type of expressions are comparison expressions. These expressions evaluate to either 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), < (smaller than) and <= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as IF statements. The last example of expressions we’ll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write ’$a++’ or ’++$a’. But what if you want to add more than one to it, for instance 3? You could write ’$a++’ multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write ’$a = $a + 3’. ’$a + 3’ evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written ’$a += 3’. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of ’$a += 3’, like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that’s assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example ’$a -= 5’ (subtract 5 from the value of $a), ’$b *= 7’ (multiply the value of $b by 7), etc.



There is one more expression that may seem odd if you haven’t seen it in other languages, the ternary conditional operator:




   1: $first ? $second : $third



If the value of the first subexpression is true (non-zero), then it the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.


The following example should help you understand pre- and post-increment and expressions in general a bit better:


   1: function double($i) {
   2: return $i*2;
   3: }
   4: $b = $a = 5; /* assign the value five into the variable $a and $b */
   5: $c = $a++; /* post-increment, assign original value of $a
   6: (5) to $c */
   7: $e = $d = ++$b; /* pre-increment, assign the incremented value of
   8: $b (6) to $d and $e */
   9: /* at this point, both $d and $e are equal to 6 */
  10: $f = double($d++); /* assign twice the value of $d before
  11: the increment, 2*6 = 12 to $f */
  12: $g = double(++$e); /* assign twice the value of $e after
  13: the increment, 2*7 = 14 to $g */
  14: $h = $g += 10; /* first, $g is incremented by 10 and ends with the
  15: value of 24. the value of the assignment (24) is
  16: then assigned into $h, and $h ends with the value
  17: of 24 as well. */




In the beginning of the chapter we said that we’ll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of ’expr’ ’;’ that is, an expression followed by a semicolon. In ’$b=$a=5;’, $a=5 is a valid expression, but it’s not a statement by itself. ’$b=$a=5;’ however is a valid statement.


One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you’re not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE (PHP doesn’t have a dedicated boolean type). The truth value of expressions in PHP is calculated in a similar way to perl. Any numeric non-zero numeric value is TRUE, zero is FALSE. Be sure to note that negative values are non-zero and are thus considered TRUE! The empty string and the string "0" are FALSE; all other strings are TRUE. With non-scalar values (arrays and objects) - if the value contains no elements it’s considered FALSE, otherwise it’s considered TRUE.


PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we’ll write expr to indicate any valid PHP expression.

GET and POST in PHP

HTML Forms (GET and POST)
When a form is submitted to a PHP script, any variables from that form will be automatically made
available to the script by PHP. For instance, consider the following form:
Example : Simple form variable

   1: <form action="foo.php3" method="post">
   2: Name: <input type="text" name="name"><br>
   3: <input type="submit">
   4: </form>


When submitted, PHP will create the variable $name, which will will contain whatever what entered into the Name: field on the form. PHP also understands arrays in the context of form variables, but only in one dimension. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input:
Example : More complex form variables


   1: <form action="array.html" method="post">
   2: Name: <input type="text" name="personal[name]"><br>
   3: Email: <input type="text" name="personal[email]"><br>
   4: Beer: <br>
   5: <select multiple name="beer[]">
   6: <option value="warthog">Warthog
   7: <option value="guinness">Guinness
   8: </select>
   9: <input type="submit">
  10: </form>

If PHP’s track_vars feature is turned on, either by the track_vars configuration setting or the
<?php_track_vars?> directive, then variables submitted via the POST or GET methods will also be
found in the global associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS as appropriate.

Variable scope in PHP

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

   1: $a = 1; /* global scope */
   2: Function Test () {
   3: echo $a; /* reference to local scope variable */
   4: }
   5: Test ();



This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.


An example:


   1: $a = 1;
   2: $b = 2;
   3: Function Sum () {
   4: global $a, $b;
   5: $b = $a + $b;
   6: }
   7: Sum ();
   8: echo $b;
The above script will output "3". By declaring $a and $b global within the function, all references to
either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.


 


A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:


   1: $a = 1;
   2: $b = 2;
   3: Function Sum () {
   4: $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
   5: }
   6: Sum ();
   7: echo $b;

The $GLOBALS array is an associative array with the name of the global variable being the key and the
contents of that variable being the value of the array element.
Another important feature of variable scoping is the static variable. A static variable exists only in a local
function scope, but it does not lose its value when program execution leaves this scope. Consider the
following example:


   1: Function Test () {
   2: $a = 0;
   3: echo $a;
   4: $a++;
   5: }

This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:


   1: Function Test () {
   2: static $a = 0;
   3: echo $a;
   4: $a++;
   5: }

Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables are also essential when functions are called recursively. A recursive function is one
which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10:


   1: Function Test () {
   2: static $count = 0;
   3: $count++;
   4: echo $count;
   5: if ($count < 10) {
   6: Test ();
   7: }
   8: $count-;
   9: }