if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
All programming languages have some form of an if statement that allows you to test conditions. All arrays have lengths and we can access that length by referencing the variable arrayname.length. We test the length of the args array as follows:
Source Code
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
/* Now let's say hello */
System.out.print("Hello ");
if (args.length > 0) {
System.out.println(args[0]);
}
}
}
Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.
What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively.
Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality. Lets look at an example when there are more then 1 statement in a branch and how braces are used indefinitely.
Source Code
import java.io.*;
class NumberTest
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );
String inS;
int num;
System.out.println("Enter an integer number");
inS = stdin.readLine();
num = Integer.parseInt( inS ); // convert inS to int using wrapper classes
if ( num < 0 ) // true-branch
{
System.out.println("The number " + num + " is negative");
System.out.println("negative number are less than zero");
}
else // false-branch
{
System.out.println("The number " + num + " is positive");
System.out.print ("positive numbers are greater ");
System.out.println("or equal to zero ");
}
System.out.println("End of program"); // always executed
}
}
All conditional statements in Java require boolean values, and that's what the ==, <, >, <=, and >= operators all return. A boolean is a value that is either true or false. Unlike in C booleans are not the same as ints, and ints and booleans cannot be cast back and forth. If you need to set a boolean variable in a Java program, you have to use the constants true and false. false is not 0 and true is not non-zero as in C. Boolean values are no more integers than are strings.
Else
Lets look at some examples of if-else:
//Example 1
if(a == b) {
c++;
}
if(a != b) {
c--;
}
//Example 2
if(a == b) {
c++;
}
else {
c--;
}
We could add an else statement like so:
Source Code
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
/* Now let's say hello */
System.out.print("Hello ");
if (args.length > 0) {
System.out.println(args[0]);
}
else {
System.out.println("whoever you are");
}
}
}
Source Code
public class divisor
{
public static void main(String[] args)
int a = 10;
int b = 2;
if ( a % b == 0 )
{
System.out.println(a + " is divisible by "+ b);
}
else
{
System.out.println(a + " is not divisible by " + b);
}
}
Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Rusty works, but if we type java Hello Elliotte Rusty Harold, Java still only prints Hello Elliotte. Let's fix that.
We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities.
Lets look at some examples of if-else-if:
//Example 1
if(color == BLUE)) {
System.out.println("The color is blue.");
}
else if(color == GREEN) {
System.out.println("The color is green.");
}
//Example 2
if(employee.isManager()) {
System.out.println("Is a Manager");
}
else if(employee.isVicePresident()) {
System.out.println("Is a Vice-President");
}
else {
System.out.println("Is a Worker");
}
Source Code
// This is the Hello program in Java
class Hello {
public static void main (String args[]) {
/* Now let's say hello */
System.out.print("Hello ");
if (args.length == 0) {
System.out.print("whoever you are");
}
else if (args.length == 1) {
System.out.println(args[0]);
}
else if (args.length == 2) {
System.out.print(args[0]);
System.out.print(" ");
System.out.print(args[1]);
}
else if (args.length == 3) {
System.out.print(args[0]);
System.out.print(" ");
System.out.print(args[1]);
System.out.print(" ");
System.out.print(args[2]);
}
System.out.println();
}
}
Boolean-expression ? expression-1 : expression-2
The JVM tests the value of Boolean-expression. If the value is true, it evaluates expression-1; otherwise, it evaluates expression-2. For
Example
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
These operators act on Boolean operands according to this table
A B A|B A&B A^B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false
| the OR operator
& the AND operator
^ the XOR operator
! the NOT operator
|| the short-circuit OR operator
&& the short-circuit AND operator
== the EQUAL TO operator
!= the NOT EQUAL TO operator
Example
class Bool1{
public static void main(String args[]){
// these are boolean variables
boolean A = true;
boolean B = false;
System.out.println("A|B = "+(A|B));
System.out.println("A&B = "+(A&B));
System.out.println("!A = "+(!A));
System.out.println("A^B = "+(A^B));
System.out.println("(A|B)&A = "+((A|B)&A));
}
}
Use Returns true if
op1 > op2 op1 is greater than op2
op1 >= op2 op1 is greater than or equal to op2
op1 < op2 op1 is less than to op2
op1 <= op2 op1 is less than or equal to op2
op1 == op2 op1 and op2 are equal
op1 != op2 op1 and op2 are not equal
Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of
The main use for the above relational operators are in CONDITIONAL phrases The following java program is an example, RelationalProg, that defines three integer numbers and uses the relational operators to compare them.
public class RelationalProg {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
int k = 42;
//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false
//(they are equal)
//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true
//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true
//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}
Example
x = 1;
y = ++x;
System.out.println(y);
prints 2, but
x = 1;
y = x++;
System.out.println(y);
prints 1
Source Code
//Count to ten
class UptoTen {
public static void main (String args[]) {
int i;
for (i=1; i <=10; i++) {
System.out.println(i);
}
}
}
When we write i++ we're using shorthand for i = i + 1. When we say i-- we're using shorthand for i = i - 1. Adding and subtracting one from a number are such common operations that these special increment and decrement operators have been added to the language. T
There's another short hand for the general add and assign operation, +=. We would normally write this as i += 15. Thus if we wanted to count from 0 to 20 by two's we'd write:
Source Code
class CountToTwenty {
public static void main (String args[]) {
int i;
for (i=0; i <=20; i += 2) { //Note Increment Operator by 2
System.out.println(i);
}
} //main ends here
}
As you might guess there is a corresponding -= operator. If we wanted to count down from twenty to zero by twos we could write: -=
class CountToZero {
public static void main (String args[]) {
int i;
for (i=20; i >= 0; i -= 2) { //Note Decrement Operator by 2
System.out.println(i);
}
}
}
i = i + 2;
Here we say that we are assigning i's value to the new value which is i+2.
A shortcut way to write assignments like this is to use the += operator. It's one operator symbol so don't put blanks between the + and =.
i += 2; // Same as "i = i + 2"
The shortcut assignment operator can be used for all Arithmetic Operators i.e. You can use this style with all arithmetic operators (+, -, *, /, and even %).
Here are some examples of assignments:
//assign 1 to
//variable a
int a = 1;
//assign the result
//of 2 + 2 to b
int b = 2 + 2;
//assign the literal
//"Hello" to str
String str = new String("Hello");
//assign b to a, then assign a
//to d; results in d, a, and b being equal
int d = a = b;
The relation operators in Java are: ==, !=, <, >, <=, and >=. The meanings of these operators are:
Use Returns true if
op1 + op2 op1 added to op2
op1 - op2 op2 subtracted from op1
op1 * op2 op1 multiplied with op2
op1 / op2 op1 divided by op2
op1 % op2 Computes the remainder of dividing op1 by op2
The following java program, ArithmeticProg , defines two integers and two double-precision floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface.
public class ArithmeticProg {
public static void main(String[] args) {
//a few numbers
int i = 10;
int j = 20;
double x = 10.5;
double y = 20.5;
//adding numbers
System.out.println("Adding");
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));
//subtracting numbers
System.out.println("Subtracting");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));
//multiplying numbers
System.out.println("Multiplying");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));
//computing the remainder resulting
//from dividing numbers
System.out.println("Modulus");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));
}
}
This class demonstrates how command line arguments are passed in Java. Arguments are passed as a String array to the main method of a class. The first element (element 0) is the first argument passed not the name of the class.
Source Code
An example that prints in the command line arguments passed into the class when executed.
public class ReadArgs
{
public static final void main(String args[])
{
for (int i=0;i
System.out.println( args[i] );
}
}
}
Sample Run
java ReadArgs zero one two three
Output:
The following command line arguments were passed:
arg[0]: zero
arg[1]: one
arg[2]: two
arg[3]: three
There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the eight primitive data types are:
| byte | short | int | long | float | double | char | boolean |
There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers.
| Integer Primitive Data Types | ||
|---|---|---|
| Type | Size | Range |
| byte | 8 bits | -128 to +127 |
| short | 16 bits | -32,768 to +32,767 |
| int | 32 bits | (about)-2 billion to +2 billion |
| long | 64 bits | (about)-10E18 to +10E18 |
| Floating Point Primitive Data Types | ||
|---|---|---|
| Type | Size | Range |
| float | 32 bits | -3.4E+38 to +3.4E+38 |
| double | 64 bits | -1.7E+308 to 1.7E+308 |
Examples
int yr = 2006;
double rats = 8912 ;
For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes:
| primitive type | Wrapper type |
| byte | Byte |
| short | Short |
| int | Int |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of as a little box made up of one or more bytes that can hold a value of a particular data type:
Syntax: variabletype variablename = data;
Source Code ( demonstrating declaration of a variable )
class example
{
public static void main ( String[] args )
{
long x = 123; //a declaration of a variable named x with a datatype of long
System.out.println("The variable x has: " + x );
}
}
Source Code
public class MaxDemo {
public static void main(String args[]) {
//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
//other primitive types
char aChar = 'S';
boolean aBoolean = true;
//Display them all.
System.out.println("largest byte value is " + largestByte + ".");
System.out.println("largest short value is " + largestShort + ".");
System.out.println("largest integer value is " + largestInteger + ".");
System.out.println("largest long value is " + largestLong + ".");
System.out.println("largest float value is " + largestFloat + ".");
System.out.println("largest double value is " + largestDouble + ".");
}
}
Sample Run
The largest short value is 32767.
The largest integer value is 2147483647.
The largest long value is 9223372036854775807.
The largest float value is 3.4028235E38.
The largest double value is 1.7976931348623157E308.
The Java programming language supports three kinds of comments:
/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.
// text
The compiler ignores everything from // to the end of the line.
Example
Java denotes comments in three ways:
1. Double slashes in front of a single line comment:
int i=5; // Set the integer to 5
2. Matching slash-asterisk (/*) and asterisk-slash (*/) to bracket multi-line comments:
/*
Set the integer to 5
*/
int i=5;
3. Matching slash-double asterisk (/**) & asterisk-slash(*/) for Javadoc automatic hypertext documentation, as in
/**
This applet tests graphics.
*/
public class testApplet extends applet{...
or
/**
* Asterisks inside the comment are ignored by javadoc so they
* can be used to make nice line markers.
**/
The SDK tool javadoc uses the latter /** ..*/ comment style when it produces hypertext pages to describe a class.
Our first application will be extremely simple - the obligatory "Hello World". The following is the Hello World Application as written in Java. Type it into a text file or copy it out of your web browser, and save it as a file named HelloWorld.java. This program demonstrates the text output function of the Java programming language by displaying the message "Hello world!". Java compilers expect the filename to match the class name.
A java program is defined by a public class that takes the form:
public class program-name {
optional variable declarations and methods
public static void main(String[] args) {
statements
}
optional variable declarations and methods
}Source Code
In your favorite editor, create a file called HelloWorld.java with the following contents:
/** Comment
* Displays "Hello World!" to the standard output.
*/
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!"); //Displays the enclosed String on the Screen Console
}
}
To compile Java code, we need to use the 'javac' tool. From a command line, the command to compile this program is:
javac HelloWorld.java
For this to work, the javac must be in your shell's path or you must explicitly specify the path to the program (such as c:\j2se\bin\javac HelloWork.java). If the compilation is successful, javac will quietly end and return you to a command prompt. If you look in the directory, there will now be a HelloWorld.class file. This file is the compiled version of your program. Once your program is in this form, its ready to run. Check to see that a class file has been created. If not, or you receive an error message, check for typographical errors in your source code.
You're ready to run your first Java application. To run the program, you just run it with the java command:
java HelloWorld
Sample Run
Hello world!
The source file above should be saved as myfirstjavaprog.java, using any standard text editor capable of saving as ASCII (eg - Notepad, Vi). As an alternative, you can download the source for this tutorial.
HelloWorld.java
Note: It is important to note that you use the full name with extension when compiling (javac HelloWorld.java) but only the class name when running (java HelloWorld).
You've just written your first Java program! Congratulations!!
In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the Java garbage collector automatically deletes the unreachable object, freeing memory and preventing a memory leak. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed—in other words, they can still occur but at higher conceptual levels.
The use of garbage collection in a language can also affect programming paradigms. If, for example, the developer assumes that the cost of memory allocation/recollection is low, they may choose to more freely construct objects instead of pre-initializing, holding and reusing them. With the small cost of potential performance penalties (inner-loop construction of large/complex objects), this facilitates thread-isolation (no need to synchronize as different threads work on different object instances) and data-hiding. The use of transient immutable value-objects minimizes side-effect programming.
Comparing Java and C++, it is possible in C++ to implement similar functionality (for example, a memory management model for specific classes can be designed in C++ to improve speed and lower memory fragmentation considerably), with the possible cost of extra development time and some application complexity. In Java, garbage collection is built-in and virtually invisible to the developer. That is, developers may have no notion of when garbage collection will take place as it may not necessarily correlate with any actions being explicitly performed by the code they write. Depending on intended application, this can be beneficial or disadvantageous: the programmer is freed from performing low-level tasks, but at the same time loses the option of writing lower level code.
The Java language compiler and run-time system implement several layers of defense against potentially incorrect code. The environment starts with the assumption that nothing is to be trusted, and proceeds accordingly. The next few sections discuss the Java security models in greater detail.
Memory Allocation and Layout
One of the Java compiler's primary lines of defense is its memory allocation and reference model. First of all, memory layout decisions are not made by the Java language compiler, as they are in C and C++. Rather, memory layout is deferred to run time, and will potentially differ depending on the characteristics of the hardware and software platforms on which the Java system executes.Secondly, Java does not have "pointers" in the traditional C and C++ sense of memory cells that contain the addresses of other memory cells.The Java compiled code references memory via symbolic "handles" that are resolved to real memory addresses at run time by the Java interpreter. Java programmers can't forge pointers to memory, because the memory allocation and referencing model is completely opaque to the programmer and controlled entirely by the underlying run-time system.
Very late binding of structures to memory means that programmers can't infer the physical memory layout of a class by looking at its declaration. By removing the C and C++ memory layout and pointer models, the Java language has eliminated the programmer's ability to get behind the scenes and manufacture pointers to memory. These features must be viewed as positive benefits rather than a restriction on the programmer, because they ultimately lead to more reliable and secure applications.
The Byte Code Verification Process
What about the concept of a "hostile compiler"? Although the Java compiler ensures that Java source code doesn't violate the safety rules, when an application such as the HotJava Browser imports a code fragment from anywhere, it doesn't actually know if code fragments follow Java language rules for safety: the code may not have been produced by a known-to-be trustworthy Java compiler. In such a case, how is the Java run-time system on your machine to trust the incoming bytecode stream? The answer is simple: the Java run-time system doesn't trust the incoming code, but subjects it to bytecode verification.The tests range from simple verification that the format of a code fragment is correct, to passing each code fragment through a simple theorem prover to establish that it plays by the rules:
- it doesn't forge pointers,
- it doesn't violate access restrictions,
- it accesses objects as what they are (for example,
InputStreamobjects are always used asInputStreams and never as anything else).
The Byte Code Verifier
The bytecode verifier traverses the bytecodes, constructs the type state information, and verifies the types of the parameters to all the bytecode instructions.
The illustration shows the flow of data and control from Java language source code through the Java compiler, to the bytecode verifier and hence on to the Java interpreter. The important issue is that the Java bytecode loader and the bytecode verifier make no assumptions about the primary source of the bytecode stream--the code may have come from the local system, or it may have travelled halfway around the planet. The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to the Java interpreter is in a fit state to be executed and can run without fear of breaking the Java interpreter. Imported code is not allowed to execute by any means until after it has passed the verifier's tests. Once the verifier is done, a number of important properties are known:
- There are no operand stack overflows or underflows
- The types of the parameters of all bytecode instructions are known to always be correct
- Object field accesses are known to be legal--private, public, or protected
Security Checks in the Bytecode Loader
While a Java program is executing, it may in its turn request that a particular class or set of classes be loaded, possibly from across the network. After incoming code has been vetted and determined clean by the bytecode verifier, the next line of defense is the Java bytecode loader. The environment seen by a thread of execution running Java bytecodes can be visualized as a set of classes partitioned into separate name spaces. There is one name space for classes that come from the local file system, and a separate name space for each network source.When a class is imported from across the network it is placed into the private name space associated with its origin. When a class references another class, it is first looked for in the name space for the local system (built-in classes), then in the name space of the referencing class. There is no way that an imported class can "spoof" a built-in class. Built-in classes can never accidentally reference classes in imported name spaces--they can only reference such classes explicitly. Similarly, classes imported from different places are separated from each other.
Security in the Java Networking Package
Java's networking package provides the interfaces to handle the various network protocols (FTP, HTTP, Telnet, and so on). This is your front line of defense at the network interface level. The networking package can be set up with configurable levels of paranoia. You can
- Disallow all network accesses
- Allow network accesses to only the hosts from which the code was imported
- Allow network accesses only outside the firewall if the code came from outside
- Allow all network accesses
With the phenomenal growth of networks, today's developers must "think distributed". Applications--even parts of applications--must be able to migrate easily to a wide variety of computer systems, a wide variety of hardware architectures, and a wide variety of operating system architectures. They must operate with a plethora of graphical user interfaces.
Clearly, applications must be able to execute anywhere on the network without prior knowledge of the target hardware and software platform. If application developers are forced to develop for specific target platforms, the binary distribution problem quickly becomes unmanageable. Various and sundry methods have been employed to overcome the problem, such as creating "fat" binaries that adapt to the specific hardware architecture, but such methods are not only clumsy but are still geared to a specific operating system. To solve the binary-distribution problem, software applications and fragments of applications must be architecture neutral and portable.
Reliability is also at a high premium in the distributed world. Code from anywhere on the network should work robustly with low probabilities of creating "crashes" in applications that import fragments of code.
Architecture Neutral
The solution that the Java system adopts to solve the binary-distribution problem is a "binary code format" that's independent of hardware architectures, operating system interfaces, and window systems. The format of this system-independent binary code is architecture neutral. If the Java run-time system is made available on a given hardware and software platform, an application written in Java can then execute on that platform without the need to perform any special porting work for that application.Byte Codes
The Java compiler doesn't generate "machine code" in the sense of native hardware instructions--rather, it generates bytecodes: a high-level, machine-independent code for a hypothetical machine that is implemented by the Java interpreter and run-time system.One of the early examples of the bytecode approach was the UCSD P-System, which was ported to a variety of eight-bit architectures in the middle 1970s and early 1980s and enjoyed widespread popularity during the heyday of eight-bit machines. Coming up to the present day, current architectures have the power to support the bytecode approach for distributed software. Java bytecodes are designed to be easy to interpret on any machine, or to dynamically translate into native machine code if required by performance demands.
The architecture neutral approach is useful not only for network-based applications, but also for single-system software distribution. In today's software market, application developers have to produce versions of their applications that are compatible with the IBM PC, Apple Macintosh, and fifty-seven flavors of workstation and operating system architectures in the fragmented UNIX marketplace.
With the PC market (through Windows 95 and Windows NT) diversifying onto many CPU architectures, and Apple moving full steam from the 68000 to the PowerPC, production of software to run on all platforms becomes almost impossible until now. Using Java, coupled with the Abstract Window Toolkit, the same version of your application can run on all platforms.
Portable
The primary benefit of the interpreted byte code approach is that compiled Java language programs are portable to any system on which the Java interpreter and run-time system have been implemented.The architecture-neutral aspect discussed above is one major step towards being portable, but there's more to it than that. C and C++ both suffer from the defect of designating many fundamental data types as "implementation dependent". Programmers labor to ensure that programs are portable across architectures by programming to a lowest common denominator.
Java eliminates this issue by defining standard behavior that will apply to the data types across all platforms. Java specifies the sizes of all its primitive data types and the behavior of arithmetic on them. Here are the data types:
byte 8-bit two's complementshort 16-bit two's complementint 32-bit two's complementlong 64-bit two's complement
float 32-bit IEEE 754 floating pointdouble 64-bit IEEE 754 floating point
char 16-bit Unicode character
The data types and sizes described above are standard across all implementations of Java. These choices are reasonable given current microprocessor architectures because essentially all central processor architectures in use today share these characteristics. That is, most modern processors can support two's-complement arithmetic in 8-bit to 64-bit integer formats, and most modern processors support single- and double-precision floating point.
The Java environment itself is readily portable to new architectures and operating systems. The Java compiler is written in Java. The Java run-time system is written in ANSI C with a clean portability boundary which is essentially POSIX-compliant. There are no "implementation-dependent" notes in the Java language specification.
Robust
Java is intended for developing software that must be robust, highly reliable, and secure, in a variety of ways. There's strong emphasis on early checking for possible problems, as well as later dynamic (run-time) checking, to eliminate error-prone situations.
4.3.1 Strict Compile-Time and Run-Time Checking
The Java compiler employs extensive and stringent compile-time checking so that syntax-related errors can be detected early, before a program is deployed.One of the advantages of a strongly typed language (like C++) is that it allows extensive compile-time checking, so bugs can be found early. Unfortunately, C++ inherits a number of loopholes in its compile-time checking from C. Unfortunately, C++ and C are relatively lax, most notably in the area of method or function declarations. Java imposes much more stringent requirements on the developer: Java requires explicit declarations and does not support C-style implicit declarations.
Many of the stringent compile-time checks at the Java compiler level are carried over to the run time, both to check consistency at run time, and to provide greater flexibility. The linker understands the type system and repeats many of the type checks done by the compiler, to guard against version mismatch problems.
The single biggest difference between Java and C or C++ is that Java's memory model eliminates the possibility of overwriting memory and corrupting data. Instead of pointer arithmetic, Java has true arrays and strings, which means that the interpreter can check array and string indexes. In addition, a programmer can't write code that turns an arbitrary integer into an object reference by casting.
While Java doesn't pretend to completely remove the software quality assurance problem, removal of entire classes of programming errors considerably eases the job of testing and quality assurance.
What are objects? They're software programming models. In your everyday life, you're surrounded by objects: cars, coffee machines, ducks, trees, and so on. Software applications contain objects: buttons on user interfaces, spreadsheets and spreadsheet cells, property lists, menus, and so on. These objects have state and behavior. You can represent all these things with software constructs called objects, which can also be defined by their state and their behavior.
In your everyday transportation needs, a car can be modelled by an object. A car has state (how fast it's going, in which direction, its fuel consumption, and so on) and behavior (starts, stops, turns, slides, and runs into trees).
You drive your car to your office, where you track your stock portfolio. In your daily interactions with the stock markets, a stock can be modelled by an object. A stock has state (daily high, daily low, open price, close price, earnings per share, relative strength), and behavior (changes value, performs splits, has dividends).
After watching your stock decline in price, you repair to the cafe to console yourself with a cup of good hot coffee. The espresso machine can be modelled as an object. It has state (water temperature, amount of coffee in the hopper) and it has behavior (emits steam, makes noise, and brews a perfect cup of java).
- Encapsulation--implements information hiding and modularity (abstraction)
- Polymorphism--the same message sent to different objects results in behavior that's dependent on the nature of the object receiving the message
- Inheritance--you define new classes and behavior based on existing classes to obtain code re-use and code organization
- Dynamic binding--objects could come from anywhere, possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. Dynamic binding provides maximum flexibility while a program is executing
To stay abreast of modern software development practices, Java is object oriented from the ground up. The point of designing an object-oriented language is not simply to jump on the latest programming fad. The object-oriented paradigm meshes well with the needs of client-server and distributed software. Benefits of object technology are rapidly becoming realized as more organizations move their applications to the distributed client-server model.
Unfortunately, "object oriented" remains misunderstood, over-marketed as the silver bullet that will solve all our software ills, or takes on the trappings of a religion. The cynic's view of object-oriented programming is that it's just a new way to organize your source code. While there may be some merit to this view, it doesn't tell the whole story, because you can achieve results with object-oriented programming techniques that you can't with procedural techniques.
An important characteristic that distinguishes objects from ordinary procedures or functions is that an object can have a lifetime greater than that of the object that created it. This aspect of objects is subtle and mostly overlooked.In the distributed client-server world, this creates the potential for objects to be created in one place, passed around networks, and stored elsewhere, possibly in databases, to be retrieved for future work.
As an object-oriented language, Java draws on the best concepts and features of previous object-oriented languages, primarily Eiffel, SmallTalk, Objective C, and C++. Java goes beyond C++ in both extending the object model and removing the major complexities of C++. With the exception of its primitive data types, everything in Java is an object, and even the primitive types can be encapsulated within objects if the need arises.
SUBSCRIBE VIA eMAIL
Recent Posts
Archives
- December 2008 (5)
- November 2008 (15)
- October 2008 (17)
- September 2008 (9)
- August 2008 (12)
- July 2008 (19)
- June 2008 (22)
- May 2008 (17)
- April 2008 (2)
Categories
- java.sql (19)
- Examples (18)
- INTRODUCTION (9)
- JAVA APPLET (9)
- java.awt (8)
- java.net (8)
- java.beans (7)
- JAVA String Utility (6)
- Arrays (4)
- java.math (3)
- java.util.regex (3)
- Sort (2)
- Swing (2)
- java.security (2)
- java.util.zip (2)
- Catching Exceptions (1)
- Classes and Objects (1)
- Core Java Programs-part 1 (1)
- Core Java Programs-part 2 (1)
- Core Java Programs-part3 (1)
- Criticism of Java programming language (1)
- Falling Letters (1)
- File I/O and Streams (1)
- Fun With Letters and Words (1)
- Get current working directory (1)
- How do I convert String to Date object? (1)
- How do I convert string into InputStream? (1)
- How do i calculate directory size? (1)
- How to make executable jar files in JDK1.3.1? (1)
- Interfaces (1)
- JAVA Date Utility (1)
- Java Arithmetic Operators (1)
- Java Assignment Operators (1)
- Java Boolean Operators (1)
- Java Command Line Arguments (1)
- Java Comments (1)
- Java Conditional Operators (1)
- Java Data and Variables (1)
- Java Hello World Program (1)
- Java If-Else Statement (1)
- Java Increment and Decrement Operators (1)
- Java Loops (while (1)
- Java Relational Operators (1)
- Java Variables and Arithmetic Expressions (1)
- Java Virtual Machine (1)
- Know the current position of cursor (1)
- Letters (1)
- Methods (Includes Recursive Methods) (1)
- Rotating Lines (1)
- Send an email with attachment (1)
- Use for..each in Java (1)
- What is Autoboxing? (1)
- Write text file (1)
- connection to database (1)
- do-while and for loops) (1)

