google Ads

Monday, July 20, 2009

Overview of JAVA

Java is a two things:


One is Programming language

and another one is platform


Java Programming language



Java is a high-level programming language that is all of the following:


Simple

Object-oriented

Distributed

Interpreted

Robust

Secure

Architecture-neutral

Portable

High-performance

Multithreaded

Dynamic


Java is also unusual in that each Java program is both compiled and interpreted. With a compiler, you translate a Java program into an intermediate language called java bytecodes – the platform-independent codes interpreted by the Java interpreter. With an interpreter, each java bytecode instruction is parsed and run on the computer.


Compilation happens just once; interpretation occurs each time the program is executed.


The following figure illustrates how this works


How a Java Program works





You can think of Java bytecodes as the machine code instructions for the java Virtual Machine (JVM). Every Java interpreter, whether it’s a Java development tool or a Web browser that can run java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware.


Java bytecodes help make “write once, run anywhere” possible. You can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM. For example, the same Java program can run on Windows NT, Solaris, and Macintosh.


Java Platform

The Java Platform


A platform is the hardware or software environment in which a program runs. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other, hardware-based platforms. Most other platforms are described as a combination of hardware and operating system.

The Java platform has two components:

The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

The JVM. It’s the base for the Java platform and is ported onto various hardware-based platforms.

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. The Java API is grouped into libraries (PACKAGES) of related components.

As a platform-independent environment, Java can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring Java’s performance close to that of native code without threatening portability.

Sunday, July 19, 2009

Structure of a Java program

Structure of a Java program


The structure of a java program is very different from traditional programming languages like C or C++. In java we have to declare a class however simple the objective of our program be. This is because java is pure object oriented language. Through difficult to start with, it is clearly one of the best programming paradigms.


Syntax of Java program

public class

{

public static void main (String [] arguments)

{


statemenst;


}

}





Example


Public class myprogClass ------------- Step1

{

Public static void main (String[] arguments) ------------- Step2

{

System.out.println(“Good Morning”); ------------- Step 3

}

}


The above program is inside a file called myprogClass.java

The above program prints Good Morning in the standard output screen

The above code has to be stored in a file, which has same name as the public class. So the source file should have a name myprogClass.java

Let us analyze this code step by step

In Step1 we declare a class called myprogClass (We have to declare this)

In Step 2 we make declare a method called main, which takes in an array of String objects. This is starting point of any program. We are not allowed to change the signature of this method.

In Step 3 we call System.out.println() method which is inside an object called out, which is in turn inside an object called System. We will learn more about these Objects and classes later, as of now remember this statement, as we will be using this quite often.

How to compile and run a code

How to compile and run a code

Once the file myprogClass.java has been saved, we have to compile it and convert it into byte code.


The Java compilation does not create direct executable format. (.exe in MsDOS or MS Windows). Instead byte code for the source is generated which is run by Java Virtual Machine or JVM.


To compile a .java file we have to type

Syntax:


Prompt > javac

Example:

C:\javac myprogClass.java


To generates a file called myprogClass.class


To run a byte code (for a class), it must contain a static main() method as described above. In our case we have to type

C:\ java myprogClass


This runs the main method in that class. If no main method is found an error message saying ‘No main method found’ is displayed.

Note: Its better if you set the path to the directory in which the jdk is installed. Doing so will allow you to execute the above commands from any directory.


To do this add following line to your autoexec.bat file which is in the C:


Set path=”C:\jdk1.5\bin”


Here c:\jdk1.5\bin is the directory where java and javac are stored


Before we go ahead with programming in java it is good to know the directory structure of the JDK. It may not make much sense when looking for the first time, but it is very important from viewpoint of platform independence implementation in java.

Development Files and Directories

Development Files and Directories

This section describes the files and directories that are required to develop apps for the Java platform. ( The directories that are not required include demos, source code, and C header files. They are discussed in the following section, Additional Files and Directories ). The following diagram shows the most important directories.

C:\jdk1.5

The root directory of the SDK software installation. Contains copyright, license, and README files. Also contains src.jar, the archive of source code for the Java 2 platform.

C:\jdk1.5\bin


The executable files for the development tools contained in the Java Development Kit. The PATH environment variables should contain an entry for this directory. For more information on the tools, see the SDK Tools.




Variables

Variables


A variable is an entity that can change values during the program execution. Variables are the nouns of any programming language. They are the entities (values and data ) that act or are acted upon.



All variables in Java must be clearly declared and initialized before using it. This may sound a little uncomfortable at first, at it is one way to ensure safe programming.

Data Types

Data Types



Java defines eight simple types of data:

byte
short
int
long
char
float
double
boolean

These can be put in four groups:

Integers This group includes byte, short, int, and long, which are for whole valued
signed numbers.

Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.

Characters This group includes char, which represents symbols in a character
set, like letters and numbers.

Boolean This group includes boolean, which is a special type for representing
true/false values.


JAVA LANGUAGE

The simple types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the simple types are not. They are analogous to
the simple types found in most other non–object-oriented languages. The reason for
this is efficiency. Making the simple types into objects would have degraded performance too much.

The simple types are defined to have an explicit range and mathematical behavior.
Languages such as C and C++ allow the size of an integer to vary based upon the
dictates of the execution environment. However, Java is different. Because of Java’s
portability requirement, all data types have a strictly defined range. For example, an
int is always 32 bits, regardless of the particular platform. This allows programs to be
written that are guaranteed to run without porting on any machine architecture. While
strictly specifying the size of an integer may cause a small loss of performance in some environments, it is necessary in order to achieve portability.

Integers

Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Many other computer languages, including C/C++, support both signed and unsigned integers. However, Java’s designers felt that unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used mostly to specify the behavior of the high-order bit, which defined the sign of an int when expressed as a number. Java manages the meaning of the high-order bit differently, by adding

a special “unsigned right shift” operator. Thus, the need for an unsigned integer type

was eliminated.

The width of an integer type should not be thought of as the amount of storage it

consumes, but rather as the behavior it defines for variables and expressions of that

type. The Java run-time environment is free to use whatever size it wants, as long as

the types behave as you declared them. In fact, at least one implementation stores bytes and shorts as 32-bit (rather than 8- and 16-bit) values to improve performance, because that is the word size of most computers currently in use.


The width and ranges of these integer types vary widely, as shown in this table:


Name Width Range

long 64 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

int 32 2,147,483,648 to 2,147,483,647

short 16 32,768 to 32,767

byte 8 128 to 127

THE

JAVA

LANGUAGE

long


long is a signed 64-bit type and is useful for those occasions where an int type is not

large enough to hold the desired value. The range of a long is quite large. This makes

it useful when big, whole numbers are needed. For example, here is a program that

computes the number of miles that light will travel in a specified number of days.

// Compute distance light travels using long variables.

class Light

{

public static void main(String args[])

{

int lightspeed;

long days;

long seconds;

long distance;

// approximate speed of light in miles per second

lightspeed = 186000;

days = 1000; // specify number of days here

seconds = days * 24 * 60 * 60; // convert to seconds

distance = lightspeed * seconds; // compute distance

System.out.print("In " + days);

System.out.print(" days light will travel about ");

System.out.println(distance + " miles.");

}

}

This program generates the following output:

In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.

Int

The most commonly used integer type is int. It is a signed 32-bit type that has a range

from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Any time you have an integer expression involving bytes, shorts, ints, and literal numbers, the entire expression is promoted to int before the calculation is done.

The int type is the most versatile and efficient type, and it should be used most of

the time when you want to create a number for counting or indexing arrays or doing

integer math. It may seem that using short or byte will save space, but there is no

guarantee that Java won’t promote those types to int internally anyway. Remember,

type determines behavior, not size. (The only exception is arrays, where byte is

guaranteed to use only one byte per array element, short will use two bytes, and int

will use four.)

short

short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the

least-used Java type, since it is defined as having its high byte first (called big-endian

format). This type is mostly applicable to 16-bit computers, which are becoming

increasingly scarce.

Here are some examples of short variable declarations:

short s;

short t;

byte

The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly compatible with Java’s other built-in types.

Byte variables are declared by use of the byte keyword. For example, the following

declares two byte variables called b and c: byte b, c;

Floating-Point

Floating-Point Types


Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root, or transcendentals such as sine and cosine, result in a value whose precision
requires a floating-point type. Java implements the standard set of



floating-point types and operators. There are two kinds of floating-point types,

float
double
which represent single- and double-precision numbers, respectively. Their
width and ranges are shown here:
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e045 to 3.4e+038
Each of these floating-point types is examined next.


Float

The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision. For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;


double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area

{

public static void main( String args[] )

{

double pi, r, a;

r = 10.8; // radius of circle

pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);

}
}

Friday, July 17, 2009

Characters

Characters


In Java, the data type used to store characters is char. However, C/C++ programmers

beware: char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability.

Here is a program that demonstrates char variables:

// Demonstrate char data type.

class CharDemo {

public static void main(String args[]) {

char ch1, ch2;

ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

}

}

This program displays the following output:

ch1 and ch2: X Y

Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that

corresponds to the letter X. As mentioned, the ASCII character set occupies the first

127 values in the Unicode character set. For this reason, all the “old tricks” that you

have used with characters in the past will work in Java, too. Even though chars are not integers, in many cases you can operate on them as if they were integers. This allows you to add two characters together, or to increment the value of a character variable.

For example, consider the following program:

// char variables behave like integers.

class CharDemo2

{

public static void main(String args[])

{

char ch1;

ch1 = 'X';

System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1

System.out.println("ch1 is now " + ch1);

}

}

The output generated by this program is shown here:

ch1 contains X

ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

if(b == true) ...

Third, the outcome of a relational operator, such as <, is a boolean value. This is why

the expression 10 > 9 displays the value “true.” Further, the extra set of parentheses

around 10 > 9 is necessary because the + operator has a higher precedence than the >.

Booleans

Booleans


Java has a simple type, called boolean, for logical values. It can have only one of two

possible values, true or false. This is the type returned by all relational operators, such

as a < >. boolean is also the type required by the conditional expressions that govern the

control statements such as if and for.

Here is a example program for the boolean type:

THEJAVA

LANGUAGE

// Demonstrate boolean values.

class BoolTest

{

public static void main(String args[])

{

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

}

}

The Output will be:

b is false

b is true

This is executed.

10 > 9 is true

There are three interesting things to notice about this program. First, as you can see,

when a boolean value is output by println( ), “true” or “false” is displayed. Second,

the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this:

Variable names

Variable names


A program refers to a variable’s value by its name. For example, when the countChars methos wants to refer to the value of the count variable, it simply uses the name count. In Java, the following must hold true for a variable name.

1. It must be a legal java identifier comprised of a series of Unicode characters. Unicode is a character-coding system designed to support text written in diverse human languages. It allows for the codification of up to 65,356 characters, currently 34,168 have been assigned. This allows you to use characters in your Java programs from various alphabets, such as Japanese, Greek, Cyrillic, and Hebrew. This is important as it enables programmers can write code that is meaningful in their native languages.

2. It must not be a keyword or a boolean literal ( true or false).

3. It must not have the same name as another variable whose declaration appears in the same scope.


Rules:

1. A variable cannot starts with a numeral (Example: 1d, 88hak, 66emp, 888sal, etc).

2. It has start with a alphabet or _ (Underscore) or $ (Dollar).
Example : _myEmployee, $salary

3. A variable names should be starts with a lowercase and class name starts with a UPPERCASE.

4. If a variable name consists of more than one word, such as isVisible, the words are joined together and each word after the first begins with an uppercase letter.

Scope

Scope in JAVA


A variable’s scope is the block of code within which the variable is accessible and determines when the variable is created and destroyed. The location of the variable declaration within your program establishes its scope and places it into one of these four categories:

Member variable
Local variable
Method parameter

Exception-handler parameter


A member variable is a member of a class or an object. It can be declared anywhere in a class but not in a method. The member is available to all code in the class.





Variable Initialization

Variable Initialization in JAVA

Local variables and member variables can be initialized with an assignment statement when they are declared. The data type of both sides of the assignment statement must match. The countChars method provides and initial value of zero for count when declaring it:

int sum=0;
int a=10;
float salary= 5000;
double sal = 6000;

The value assigned to the variable must match the variable’s type. Method parameters and exception-handler parameters cannot be initialized in the way. The value for a parameter is set by the caller.

Final Variables

Final Variables in JAVA



You can declare a variable in any scope to be final, including parameters to methods and constructors. The value of a final variable cannot change after it has been initialized. To declare a final variable, use the final keyword in the variable declaration before the type

Final in aFinalVar=0;

The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialization of a final variable. Simply declare the variable and initialize it later, like this:

Final int blankfinal;

….

Blankfinal =0;

A final variable that has been declared but not yet initialized is called a blank final. Again, once a final variable has been initialized it cannot be set and any later attempts to assign a value to blankfinal result in a compile-time error.

Arrays

Arrays in JAVA


An array is a collection of identical data object which are stored in consecutive memory location under common name. In other words, arrays are sets of values of the same type, which have the single name followed by an index.


Single Dimensional Array

Array declaration

In the array declaration, one must define the type of the array, name of the array, number of subscripts in the array and total number of memory locations to be allocated.

Syntax:

Data_type array_name[size]

Note : The size of the array must be an integer constant.

Example:

int empno[24];

float salary[24];


Initializing an array

The variables are initialized when they are declared, in the same way the arrays can also be initialized.

Syntax:

Data_type array_name[size] = { element1, element2, …..};

Example:

Int empno[6]={30,35,40,45,50,55 };

Float salary[6] = { 1000.50, 2500.25, 5500.45,35000.35, 4000.50, 5550.60 };


Assessing array elements

The array elements are accessed using the position of the element in the array. The position of the array start with 0 and ends with ( number_of_elements-1).

For example consider the following declaration

int empno[6];

30 35 40 45 50 55

empno[0] empno[1] empno [2] empno[3] empno[4] empno[5]



float salary[6];


1000.50 2500.25 5500.45 35000.35 4000.50 5550.60

salary[0] salary[1] salary[2] salary[3] salary[4] salary[5]


User can access these elements in any order he likes and use them in the same way as simple variable.

Example 1

import java.io.*;
public static void main(String args[])
{
int empno[6];
int i;
for(i=0;i<6;i++)>

{

System.out.println(empno[i]);

} for(i=0;i<6;i++)

{ System.out.println(“Employee No: “ + i+1 + empno[i]);

}

Output will be

Employee No: 30
Employee No: 35
Employee No: 40
Employee No: 45
Employee No: 50
Employee No: 55

Example 2

import java.io.*;
public static void main(String args[])
{
float salary[6];
int i;
for(i=0;i<6;i++)
{
System.out.println(salary[i]);
}
for(i=0;i<6;i++)
{
System.out.println(“Salary : “ + salary[i] );
}

Output will be

Salary : 1000.50
Salary : 2500.25
Salary : 5500.45
Salary : 35000.35
Salary : 4000.50
Salary : 5550.60

Double Dimensional Array in JAVA

Double Dimensional Array


Double dimensional arrays are defined in the same manner as one dimensional arrays, except that a separate pair of square brackets are required for each subscript.

Example:
int n[6][6];

The above declaration defined the coordinate as a integer of 6 rows and 6 columns

Initializing an array

Consider the following two dimensional array declaration,
int n[4][2] = { { 2,6 } { 8,4 } { 7,5} {10,15} }

Where

n[0][1] = 6
n[3][0] = 10
n[2][1] = 5
n[1][0] = 8

Operators in JAVA

Operators


Operators perform some function on either one or two operands or three operands. Operators that require one operand are called unary operators. For example, ++ is a unary operator that increments the value of its operand by 1. Operators that require two operands are binary operators. For example, = is a binary operator that assigns the value from its right-hand operand to its left-hand operand. And finally ternary operators are those that require three operands. The Java language has one tertiary operator,?:, which is a short-hand if-else statement.
Java’s unary operators can use either prefix or postfix notation. Prefix notation means that the operator appears before its operand:

operator op

Postfix notation means that the operator appears after its operand:

op operator

All of Java’s binary operators use infix notation, which means that the operator appears between its operands:

op1 operator op2

Java’s only ternary operator is also infix; each component of the operator appears between operands:

expr? op1 : op2

In addition to performing the operation, an operator also returns a value. The value and its type depends on the operator and the type of its operands. For example, the arithmetic operators, which perform basic arithmetic operations such as addition and subtraction, return numbers-the result of the arithmetic operation. The data type returned by the arithmetic operators depends on the type of its operands: If you add two integers, you get an integer back. An operation is said to evaluate to its result.
It is useful to divide Java’s operators into these categories: arithmetic, relational and conditional, bitwise and logical, and assignment.

These are discussed in the following sections.

Arithmetic Operators
Relational Operators
Logical operators
Assignment Operators
Increment and decrement Operators
Conditional Operators
Bitwise Operators

Arithmetic operators

Arithmetic operators

The five arithmetical operations supported by the Java language are:

+ addition
- subtraction
* multiplication
/ division
% modulo


Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators.
The only one that you might not be so used to see may be modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write:

a = 10 % 3;

the variable a will contain the value 2, since 1 is the remainder from dividing 10 between 3.


compound assignment
When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:


expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);

and the same for all other operators.

For example:

import java.io.*;
public class arithmeticOperator

public static void main (String args[])
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
System.out.println( a);
}

Increase and decrease

Increase and decrease


Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:

c++;
c+=1;
c=c+1;

are all equivalent in its functionality: the three of them increase by one the value of c.

In the early C compilers, the three previous expressions probably produced different executable code depending on which one was used. Nowadays, this type of code optimization is generally done automatically by the compiler, thus the three expressions should produce exactly the same executable code.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression. Notice the difference:

Example 1

B=5;
A=++B; // A contains 6, B contains 7 B=5;

Example 2

A=B++; // A contains 5, B contains 6

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.

Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in Java language:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Here there are some examples:

(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true. Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

Logical operators

Logical operators

The Operator ! is the Java operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:

!(6 == 6) // evaluates to false because the expression at its right (6 == 6) is true.
!(8 <= 4) // evaluates to true because (8 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.

The logical operators && and are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise.
The following panel shows the result of operator && evaluating the expression a && b:
&& OPERATOR

a b a&b
true true true
true false false
false true false
false false false


The operator corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves.
Here are the possible results of a b:
a b a b
true true true
true false true
false true true
false false false
For example:
( (6 == 6) && (3 > 8) ) // evaluates to false ( true && false ).
( (6 == 6) (3 > 8) ) // evaluates to true ( true false ).

Control Structures

Control Structures


In a program all the instructions are executed sequentially by default, when no repetition of some calculations are necessary. When in some situation we may have to change the execution order of statements based on condition or to repeat a set of statements until certain condition are met. In such situation conditional and control statements are very useful

A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, Java language provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all Java statements, but grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }

Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between braces ({}), forming a block.

Control Statement

if Statements
switch Statements

Looping Statements

while loop Statements
for loop Statements
do-while loop Statemnts

Monday, July 13, 2009

If statements

If statements

The if statements is having three types of statements
simple if statements
if-else statements
nested if-else statements

simple if staments
It is used to control the flow of execution of the statements and also used to test logically to find whether the condition is true false.

Syntax:
if (condition)
{
statements 1;
}
statements 2;

If the conditions is true, then the statements 1 will be executed. The true statements may be a single statements or group of statements. If the condition is false then the statements 1 are not executed but statements 2 will be executed.

Example:

if (a>=10)
{
System.out.println(“A is greater than or equal to 10”);
}
System.out.println(“A value is less than 10”);


The above example : the condition is true output will be proved “A is greater than or equal to 10” . If the condition is false output will be proved ”A value is less than 10”.

void main()
{
If(a<=10;
{
System.out.println(“A value is less than or equal to 10 “;
}
System.out.println(“A value is greater then 10”;
}

If a value is 6

The output will be:

Enter the Value A:
6
A value is less than or equal to 10

If a value is 15

The output will be:

Enter the Value A:
15
A value is greater then 10

if-else statements

The if-else statements

It is used to control the flow of execution and also used carry out the logical test and ten pickup one of the two possible actions depending on the logical test.
It is used to execute some statements when the condition is true and execute some other statements. When the conditions is false.

Syntax:
if (condition)
{
statements 1;
}
else
{
statements 2;
}
statements 3;

If the conditions is true, then the statements 1 and statements 3 will be executed. The true statements may be a single statements or group of statements. If the condition is false then the statements 1 are not executed but statements 2 and statements 3 will be executed.

Example:
if (a>=10)
{
System.out.println(“A is greater than or equal to 10”);
}
else
{
System.out.println(“A value is less than 10”);

}
System.out.println(“A value is :” +a);

The above example : If a =15 the condition is true output will be proved “A is greater than or equal to 10” .and A Value is : 15

If a = 6the condition is false output will be proved ”A value is less than 10”. A value is : 6

Example:

import java.io.*;
public class biggest
{
public static void main(String args[])
{
int a,b;
a=15; b=24;


if(a>b)
{
System.out.println(“A is biggest number”);
}
else
{
System.out.println(“B is biggest Number”);
}
System.out.println(“A = “ +a +”B = “+ b);
}
}

Output will be

B is biggest Number
A=15 B= 24

Nested if-else

Nested if-else statements

When a series of if –else statements are occurred in a program, we can write an entire if-else statement in another if-else statement called nesting. And the statement is called nested if.

Syntax:

if(condition 1)
{
statements 1;
}
else if(condition 2)
{
statements 2;
}

else if(condition 3)
{
statements 3;
}
else
{
statements 4;
}

statements 5;

If Condition 1 is true Statements 1 and Statements 5 will be executed. If condition 1 is false Condition 2 (Statements 2) and Statements 5 will be executed. If Condition 1 and Condition 2 is false, then Condition 3 (Statement 3) and Statements 5 will be executed. If Condition 1, Condition 2 and Condition 3 is false, then process goes to else part and Statements 4 and Statements 5 will be executed.

Note: Statements 5 will be executed

Note that the third if-else statements is nested in the second else statement and second if-else statements is nested in the first else statements. If the condition in the first “if” statement is false, then the condition in the second if statement will be executed, if the second “if” statement is false, then the condition in the third “if” statement will be executed. If it is false then the final else statement is executed.


Example:

if (a>10)
{
System.out.println(“A Value is greater than 10”);
}
else if(a<10)
{
System.out.println(“A value is less than 10”);

}
else if(a==10)
{
System.out.println(“A value is :” + a);
}
System.out.println(“A= “ +a);


Similarly, we can construct any number of if-else statements in nested fashion, that is called if-else ladder.
If you want to test more than one condition in if statement the logical operator are used as specified below. These are used to combine the results of two or more conditions.
Operator Meaning
&& Logical And
Logical Or
! Logical Not



Example: 1

import java.io.*;
Public class biggest
{
Public static void main(String args[])
{
int a,b,c;
a=15; b=42; c=24;
}
if(a>b)&&(a>c)
{
System.out.println(“A is biggest number”);
}
else if(b>c)
{
System.out.println(“B is biggest Number”);
}
else
{
System.out.println(“C is Biggest Number");
}
System.out.println(“A = “ +a +”B = “+ b + "C= " + c);
}

Output will be

B is Biggest Number

A= 15 B= 42 C= 24