Labels

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, June 20, 2010

eclipse with java

Eclipse Java IDE

This article describes the usage of Eclipse as a Java IDE. It describes the installation of Eclipse, the creation of Java programs, the usage of external jars, quick fix and content assist and the usage of the Eclipse update manager.

This article is based on Eclipse 3.5 (Eclipse Galileo).


1. Eclipse Overview

Eclipse an open source community whose projects building tools and frameworks for creating general purpose application. The most popular usage of Eclipse is as a Java development environment which will be described in this article.

2. Getting started

2.1. Installation

Download "Eclipse IDE for Java Developers" from the website Eclipse Downloads and unpack it to a directory. This is sufficient for Eclipse to be used; no additional installation procedure is required.

Tip

Use a directory path which does not contain spaces in its name.

Tip

Eclipse requires an installed Java Runtime. I recommended to use Java 6 (also known as Java 1.6).

2.2. Start Eclipse

To start Eclipse double-click on the file eclipse.exe in your installation directory.

The system will prompt you for a workspace. The workspace is the place there you store your Java projects (more on workspaces later). Select a suitable (empty) directory and press Ok.

Eclipse will start and show the Welcome page.

Close the welcome page by press in little x besides the Welcome.

3. Eclipse UI Overview

Eclipse provides perspectives, views and editors. Views and editors are grouped into perspectives. All projects are located in a workspace.

3.1. Workspace

The workspace is the physical location (file path) you are working in. You can choose the workspace during startup of eclipse or via the menu (File-> Switch Workspace-> Others).

All your projects, sources files, images and other artifacts will be stored and saved in your workspace.

Tip

To predefine the workspace you can use the startup parameter -data path_to_workspace, e.g. c:\eclipse.exe -data "c:\temp" Please note that you have to put the path name into brackets.

Tip

To see the current workspace directory in the title of Eclipse use -showLocation as additional parameter.

3.2. Perspective

A perspective is a visual container for a set of views and editors.

You can change the layout within a perspective (close / open views, editors, change the size, change the position, etc.)

Tip

A common problem is that you closed a view and don't know how to re-open this view. You can reset a perpective it to it original state via the menu "Window" -> "Reset Perspective".

Eclipse allow you to switch to another perspective via the menu Window->Open Perspective -> Other.

For Java development you usually use the "Java Perspective".

3.3. Views and Editors

A view is typically used to navigate a hierarchy of information or to open an editor. Changes in a view are directly applied.

Editors are used to modify elements. Editors can have code completion, undo / redo, etc. To apply the changes in an editor to the underlying resources, e.g. Java source file, you usually have to save.

4. Create your first Java program

The following will describe how to create a minimal Java program using Eclipse. It will be the classical "Hello World" program. Our program will write "Hello Eclipse!" to the console.

4.1. Create project

Select from the menu File -> New-> Java project. Maintain "de.vogella.eclipse.ide.first" as the project name. Select "Create separate source and output folders".

Press finish to create the project. A new project is created and displayed as a folder. Open the folder "de.vogella.eclipse.ide.first"

4.2. Create package

Create now a package. A good convention is to use the same name for the top package as the project. Create therefore the package "de.vogella.eclipse.ide.first".

Select the folder src, right mouse click on it and select New -> Package.

4.3. Create Java class

Right click on your package and select New -> Class

Create MyFirstClass, select the flag "public static void main (String[] args)"

Maintain the following code.

				

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");
}

}

4.4. Run your project in Eclipse

Now run your code. Right click on your Java class and select Run-as-> Java application

Finished! You should see the output in the console.

4.5. Run your Java program outside Eclipse (create jar file)

To run your Java program outside of Eclipse you need to export it as a jar file. Select your project, right click on it and select "Export".

Select JAR file, select next. Select your project and maintain the export destination and a name for the jar file. I named it "myprogram.jar".

Press finish. This will create a jar file in your select output directory.

4.6. Run your program outside Eclipse

Open a command shell, e.g. under Microsoft Windows select Start -> Run and type in cmd. This should open a consle.

Switch to your output directory, e.g. by typing cd path, e.g. if you jar is located in "c:\temp" type "cd c:\temp".

To run this program you need to include the jar file into your classpath. See Classpath and Java JAR Files for details.

				

java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass

Congratulations! You created your first Java project, a package a tiny Java program and you ran this program inside Eclipse and outside

5. Content Assists and Quick Fix

Tip

For a list of the most important Eclipse shortcuts please see Eclipse Shortcuts

5.1. Content assist

The content assistant allows you to get input help in an editor. It can be invoked by CTRL + Space.

For example type syso and then press [Ctrl + Space] and it will be replaced by System.out.println(""). Or if you have an object, e.g. Person P and need to see the methods of this object you can type p. (or press CTRL + Space) which activates also the content assist.

5.2. Quick Fix

Whenever there is a problem Eclipse will underline the problematic place in the coding. Select this and press (Ctrl+1)

For example type "myBoolean = true;" If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press "Ctrn+1", then Eclipse will suggest to create a field or local variable.

Quick Fix is extremely powerful, it allows you to create new local / field variables, new methods, classes, put try and catch around your exceptions, assign a statement to a variable etc.

6. Using jars (libraries)

6.1. Adding external library (.jar ) to the Java classpath

The following describes how to add external jars to your project.

The following assumes you have a jar available.

Tip

If you need an example for working with jars you can use JFreeChart Tutorial

Create a new Java project "de.vogella.eclipse.ide.jars". Create a new folder called "lib" (or use your existing folder) by right click on your project and selecting New -> Folder

From the menu select File -> Import -> File system. Select your jar and select the folder lib as target.

Select your project, right mouse click and select properties. Under libraries select "Add JARs".

The following example shows how the result would look like if junit-4.4.jar would be added to a project.

6.2. Show source code for jar

To browse the source of a type contained in library you can attach a source archive or source folder to this library. The editor will then show the source instead of a the decompiled code. Setting the source attachment also allows source level stepping with the debugger.

The Source Attachment dialog can be reached via:

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Source attachment attribute and press Edit

Maintain the location to the source attachement.

In the Location path field, enter the path of an archive or a folder containing the source.

6.3. Add the Javadoc for a jar

Download the javadoc of the jar and put it somewhere in your filesystem.

Open the Java Build Path page of a project (Projects > Properties > Java Build Path). On the Libraries page expand the library's node and select the Javadoc location attribute and press Edit

Maintain the location to the api.

7. Updates and Installation of Plugins

7.1. Eclipse Update Manager

Eclipse provides functionality via so-called features (which contain plugins). Eclipse 3.5 contains a Software Update Manager which allows you to update existing plugins and to install new plugins.

To update your existing installation select the menu Help -> Check for Updates. The system will verify if for the installed plugins updates are available or not.

To install new functionality, select Help-> Install New Software.

Select from the list a update site from which you would like to install new software. For example if you want to install new plugins from Galileo select the Galileo Update Site.

Tip

Sometimes you have to uncheck "Group items by category" – not all available Plugins are categorized. If they are not categorized they will not be displayed. See Eclipse bug .

To add a new update site select, press the button "Add" and input the URL. This will then make this update site available and will allow you to install software from this site.

7.2. Manual installation of plugins (dropins folder)

If you’re using Plugins where no Software Site is available, then you can use the Dropins folder in your Eclipse installation directory.

To do this put the plugin into Eclipse "dropins" folder and restart Eclipse. Eclipse should detect the new plugin and install it for you.

8. More Tips

8.1. Problems view

The problems view displays problems in your projects. You can open it via Windows -> Show View -> Problems

You can configure the problems view, e.g. if you only want to display the problems from the current selected project, select "Configure Contents".

8.2. Important Preference Settings

Eclipse allows to set semicolons (and other elements) automatically.

Eclipse allows to format the source code and to organize the imports at save.

Tip

You can export your Preferences settings from one workspace via File -> Export -> General -> Preferences. Similar you can import them again into your workspace.

8.3. Task Management

If you use // TODO in the coding this indicates a task for eclipse and you find it in the task view of Eclipse.

For more advanced tasks you can use Eclipse Mylyn Tutorial .

8.4. Working Sets

A common problem in Eclipse is that your data in your workspace grows and therefore your workspace is not well structured anymore. You can use working sets to organize your displayed projects / data. To setup your working set select in the Package Explorer -> Show -> Working Sets.

Press new on the following dialog to create a working set.

On the following dialog select java, select the source folder you would like to see and give it a name. You can now easily display only the files you want to see.

8.5. Synchronize package explorer with code display

The package explorer allows to display the associated file from the current selected editor. Example: if you working on foo.java and you change in the editor to bar.java then the display in the package explorer will change.

To activate this press "Link with Editor".

8.6. Code Templates

If you have to type frequently the same code / part of the document you can maintain templates which can be activate via autocomplete (Ctrl + Space).

For example lets assume you are frequently creating "public void name(){}" methods. You could define a template which creates the method body for you.

To create a template for this select the menu Window->Preferences and Open Java -> Editor -> Templates

Press New. Create the following template. ${cursor} indicates that the cursor should be placed at this position after applying the template.

This this example the name "npm" is your keyword.

Now every time you type the keyword in the Java editor and press Ctrl+Space the system will replace your text with your template.

9. Next steps

To learn how to debug Eclipse Java programs you can use Eclipse Debugging

To learn Java Web development you can use with Servlet and JSP development with Eclipse Web Tool Platform (WTP) - Tutorial . If you want to develop rich stand-alone Java clients you can use Eclipse RCP - Tutorial

. Check out Eclipse Plugin Development - Tutorial to learn how to develop your own plugins.

Good luck in your journey of learning Java!

10. Thank you

Thank you for practicing with this tutorial.

If you like the information of this article, please help me by donating.

11. Questions and Discussion

For questions and discussion around this article please use the www.vogella.de Google Group . Also if you note an error in this article please post the error and if possible the correction to the Group.

Tip

The following tries to help you in asking good questions: 10 golden rules of asking questions in the OpenSource community .

12. Links and Literature

12.1. Source Code

Source Code of Examples

12.2. Eclipse Resources

Eclipse.org Homepage

Saturday, June 12, 2010

java@begin_5

1:Methods (Includes Recursive Methods)

A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Each calculation part of a program is called a method. Methods are logically the same as C's functions, Pascal's procedures and functions, and Fortran's functions and subroutines.

When I wrote System.out.println("Hello World!"); in the first program we were using the System.out.println() method. The System.out.println() method actually requires quite a lot of code, but it is all stored for us in the System libraries. Thus rather than including that code every time we need to print, we just call the System.out.println() method.

You can write and call your own methods too. Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. A private method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by default. access specifier. We then decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By default methods are not static. We finally specify the return type.

Next is the name of the method.

Source Code

class FactorialTest {    //calculates the factorial of that number.

public static void main(String args[]) {

int n;
int i;
long result;

for (i=1; i <=10; i++) {
result = factorial(i);
System.out.println(result);
}

} // main ends here


static long factorial (int n) {

int i;
long result=1;

for (i=1; i <= n; i++) {
result *= i;
}

return result;

} // factorial ends here


}

Recursive Methods

Recursion is used when a problem can be reduced into one or several problems of the same nature, but a smaller size. This process is usually repeated until a boundary situation is reached, where the problem can be directly solved. Java supports recursive methods, i.e. even if you're already inside methodA() you can call methodA().

Example (A Recursive Counterpart of the Above Factorial Method)

n! is defined as n times n-1 times n-2 times n-3 ... times 2 times 1 where n is a positive integer. 0! is defined as 1. As you see n! = n time (n-1)!. This lends itself to recursive calculation, as in the following method:

public static long factorial (int n) {

if (n < 0) {
return -1;
}
else if (n == 0) {
return 1;
}
else {
return n*factorial(n-1);
}

}

Arrays

Arrays are generally effective means of storing groups of variables. An array is a group of variables that share the same name and are ordered sequentially from zero to one less than the number of variables in the array. The number of variables that can be stored in an array is called the array's dimension. Each variable in the array is called an element of the array.

Creating Arrays

There are three steps to creating an array, declaring it, allocating it and initializing it.

Declaring Arrays

Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:

int[] k;
float[] yt;
String[] names;

In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.

Allocating Arrays

Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above: new

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings.

Initializing Arrays

Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException. subscripts indexes k k[0] k[1] k[2] k[3] ArrayIndexOutOfBoundsException

You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.

Here's how we'd store values in the arrays we've been working with:

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";

This step is called initializing the array or, more precisely, initializing the elements of the array. Sometimes the phrase "initializing the array" would be reserved for when we initialize all the elements of the array.

For even medium sized arrays, it's unwieldy to specify each element individually. It is often helpful to use for loops to initialize the array. For instance here is a loop that fills an array with the squares of the numbers from 0 to 100.

float[] squares = new float[101];

for (int i=0; i <= 500; i++) {
squares[i] = i*2;
}

Shortcuts

We can declare and allocate an array at the same time like this:

int[] k = new int[3];
float[] yt = new float[7];
String[] names = new String[50];

We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:

int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};

Two Dimensional Arrays

Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However we have to specify two dimensions rather than one, and we typically use two nested for loops to fill the array. for

The array examples above are filled with the sum of their row and column indices. Here's some code that would create and fill such an array:

class FillArray {

public static void main (String args[]) {

int[][] M;
M = new int[4][5];

for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
M[row][col] = row+col;
}
}

}

}

In two-dimensional arrays ArrayIndexOutOfBounds errors occur whenever you exceed the maximum column index or row index. Unlike two-dimensional C arrays, two-dimensional Java arrays are not just one-dimensional arrays indexed in a funny way.

Multidimensional Arrays

You don't have to stop with two dimensional arrays. Java lets you have arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Here's a program that declares, allocates and initializes a three-dimensional array:

class Fill3DArray {

public static void main (String args[]) {

int[][][] M;
M = new int[4][5][3];

for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
for (int ver=0; ver < 3; ver++) {
M[row][col][ver] = row+col+ver;
}
}
}

}

}

Example 1 : declaring and initializing 1-dimensional arrays

An array groups elements of the same type. It makes it easy to manipulate the information contained in them.

class Arrays1{

public static void main(String args[]){

// this declares an array named x with the type "array of int" and of
// size 10, meaning 10 elements, x[0], x[1] , ... , x[9] ; the first term
// is x[0] and the last term x[9] NOT x[10].
int x[] = new int[10];

// print out the values of x[i] and they are all equal to 0.
for(int i=0; i<=9; i++)
System.out.println("x["+i+"] = "+x[i]);

// assign values to x[i]
for(int i=0; i<=9; i++)
x[i] = i; // for example

// print the assigned values of x[i] : 1,2,......,9
for(int i=0; i<=9; i++)
System.out.println("x["+i+"] = "+x[i]);

// this declares an array named st the type "array of String"
// and initializes it
String st[]={"first","second","third"};

// print out st[i]
for(int i=0; i<=2; i++)
System.out.println("st["+i+"] = "+st[i]);

}
}


Example 2 : Find the sum of the numbers 2.5, 4.5, 8.9, 5.0 and 8.9

class Arrays2{

public static void main(String args[]){

// this declares an array named fl with the type "array of int" and
// initialize its elements

float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f};

// find the sum by adding all elements of the array fl
float sum = 0.0f;
for(int i=0; i<= 4; i++)
sum = sum + fl[i];

// displays the sum
System.out.println("sum = "+sum);
}
}


Check that the sum displayed is 29.8.

Example 3 : declaring and initializing 2-dimensional arrays

class Arrays3{

public static void main(String args[]){

// this declares a 2-dimensional array named x[i][j] of size 4 (4 elements)
// its elements are x[0][0], x[0][1], x[1][0] and x[1][1].
// the first index i indicates the row and the second index indicates the
// column if you think of this array as a matrix.


int x[][] = new int[2][2];

// print out the values of x[i][j] and they are all equal to 0.0.
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("x["+i+","+j+"] = "+x[i][j]);

// assign values to x[i]
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
x[i][j] = i+j; // for example

// print the assigned values to x[i][j]
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("x["+i+","+j+"] = "+x[i][j]);

// this declares a 2-dimensional array of type String
// and initializes it
String st[][]={{"row 0 column 0","row 0 column 1"}, // first row
{"row 1 column 0","row 1 column 1"}}; // second row

// print out st[i]
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println("st["+i+","+j+"] = "+st[i][j]);

}
}

Classes and Objects

Following the principles of Object Oriented Programming (OOP), everything in Java is either a class, a part of a class, or describes how a class behaves. Objects are the physical instantiations of classes. They are living entities within a program that have independent lifecycles and that are created according to the class that describes them. Just as many buildings can be built from one blueprint, many objects can be instantiated from one class. Many objects of different classes can be created, used, and destroyed in the course of executing a program. Programming languages provide a number of simple data types like int, float and String. However very often the data you want to work with may not be simple ints, floats or Strings. Classes let programmers define their own more complicated data types.

All the action in Java programs takes place inside class blocks, in this case the HelloWorld class. In Java almost everything of interest is either a class itself or belongs to a class. Methods are defined inside the classes they belong to. Even basic data primitives like integers often need to be incorporated into classes before you can do many useful things with them. The class is the fundamental unit of Java programs. For instance consider the following Java program:

class HelloWorld {

public static void main (String args[]) {

System.out.println("Hello World");

}

}

class GoodbyeWorld {

public static void main (String args[]) {

System.out.println("Goodbye Cruel World!");

}

}


Save this code in a single file called hellogoodbye.java in your javahtml directory, and compile it with the command javac hellogoodbye.java. Then list the contents of the directory. You will see that the compiler has produced two separate class files, HelloWorld.class and GoodbyeWorld.class. javac hellogoodbye.java

The second class is a completely independent program. Type java GoodbyeWorld and then type java HelloWorld. These programs run and execute independently of each other although they exist in the same source code file.

Class Syntax

Use the following syntax to declare a class in Java:

//Contents of SomeClassName.java
[ public ] [ ( abstract | final ) ] class SomeClassName [ extends SomeParentClass ] [ implements SomeInterfaces ]
{
// variables and methods are declared within the curly braces
}

* A class can have public or default (no modifier) visibility.
* It can be either abstract, final or concrete (no modifier).
* It must have the class keyword, and class must be followed by a legal identifier.
* It may optionally extend one parent class. By default, it will extend java.lang.Object.
* It may optionally implement any number of comma-separated interfaces.
* The class's variables and methods are declared within a set of curly braces '{}'.
* Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
* Finally, the source file name must match the public class name and it must have a .java suffix.

Here is an example of a Horse class. Horse is a subclass of Mammal, and it implements the Hoofed interface.

public class Horse extends Mammal implements Hoofed
{
//Horse's variables and methods go here
}

Lets take one more example of Why use Classes and Objects. For instance let's suppose your program needs to keep a database of web sites. For each site you have a name, a URL, and a description.

class website {

String name;
String url;
String description;

}
These variables (name, url and description) are called the members of the class. They tell you what a class is and what its properties are. They are the nouns of the class. members. A class defines what an object is, but it is not itself an object. An object is a specific instance of a class. Thus when we create a new object we say we are instantiating the object. Each class exists only once in a program, but there can be many thousands of objects that are instances of that class.

To instantiate an object in Java we use the new operator. Here's how we'd create a new web site:

    website x = new website();
Once we've got a website we want to know something about it. To get at the member variables of the website we can use the . operator. Website has three member variables, name, url and description, so x has three member variables as well, x.name, x.url and x.description. We can use these just like we'd use any other String variables. For instance:

website x = new website();
x.name = "freehavaguide.com";
x.url = "http://www.freejavaguide.com";
x.description = "A Java Programming Website";

System.out.println(x.name + " at " + x.url + " is " + x.description);

JAVA Tutorial - Class Declaration

A simple Java class declaration with constructor declaration:

class simple {
// Constructor
simple(){
p = 1;
q = 2;
r = 3;
}
int p,q,r;
}

In class declaration, you can declare methods of the class:

class simple {
// Constructor
simple(){
p = 1;
q = 2;
r = 3;
}
int p,q,r;
public int addNumbers(int var1, int var2, int var3)
{
return var1 + var2 + var3;
}
public void displayMessage()
{
System.out.println("Display Message");
}
}

To invoke the class, you can create the new instance of the class:

// To create a new instance class

Simple sim = new Simple();

// To access the methods of the class

sim.addNumbers(5,1,2)

// To show the result of the addNumbers

System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));

Interfaces

There is one thing in Java source code that is neither a class nor a member of a class. That's an interface. An interface defines methods that a class implements. In other words it declares what certain classes do. However an interface itself does nothing. All the action at least, happens inside classes. A class may implement one or more interfaces. This means that the class subscribes to the promises made by those interfaces. Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface. The methods of an interface are abstract -- they have no bodies. Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies -- implementations -- for its methods.

For example, a ScoreCounter class might meet the contract specified by the Counting interface:

interface Counting
{
abstract void increment();
abstract int getValue();
}

So might a Stopwatch, although it might have a totally different internal representation. Both would have increment() and getValue() methods, but the bodies of these methods might look quite different. For example, a ScoreCounter for a basketball game might implement increment() so that it counts by 2 points each time, while a Stopwatch might call its own increment() method even if no one else does.

A class that implements a particular interface must declare this explicitly:

class ScoreCounter implements Counting {
....
}

If a class implements an interface, an instance of that class can also be treated as though its type were that interface. For example, it can be labeled with a name whose declared type is that interface. For example, an instance of class ScoreCounter can be labeled with a name of type Counting. It will also answer true when asked whether it's an instanceof that interface type: if myScoreCounter is a ScoreCounter, then myScoreCounter instanceof Counting is true. Similarly, you can pass or return a ScoreCounter whenever a Counting is required by a method signature.

The generality of interfaces and the inclusion of multiple implementations within a single (interface) type is an extremely powerful feature. For example, you can use a name of type Counting to label either an instance of ScoreCOunter or an instance of Stopwatch (and use its increment() and getValue() methods) without even knowing which one you've got.


java@begin_4

1:Java If-Else Statement

The if-else class of statements should have the following form:

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 <>= 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();
}

Java Loops (while, do-while and for loops)

A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may look like:


while there's more data {
Read a Line of Data
Do Something with the Data
}

There are many different kinds of loops in Java including while, for, and do while loops. They differ primarily in the stopping conditions used.

For loops typically iterate a fixed number of times and then exit. While loops iterate continuously until a particular condition is met. You usually do not know in advance how many times a while loop will loop.

In this case we want to write a loop that will print each of the command line arguments in succession, starting with the first one. We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using the args.length. Therefore we will write this with a for loop. Here's the code:

Source Code

// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

int i;

/* Now let's say hello */
System.out.print("Hello ");
for (i=0; i < args.length; i = i++)
{ System.out.print(args[i]); System.out.print(" "); }
System.out.println(); } }

We begin the code by declaring our variables. In this case we have exactly one variable, the integer i. i Then we begin the program by saying "Hello" just like before. Next comes the for loop. The loop begins by initializing the counter variable i to be zero. This happens exactly once at the beginning of the loop. Programming tradition that dates back to Fortran insists that loop indices be named i, j, k, l, m and n in that order. Next is the test condition. In this case we test that i is less than the number of arguments. When i becomes equal to the number of arguments, (args.length) we exit the loop and go to the first statement after the loop's closing brace. You might think that we should test for i being less than or equal to the number of arguments; but remember that we began counting at zero, not one. Finally we have the increment step, i++ (i=i+1). This is executed at the end of each iteration of the loop. Without this we'd continue to loop forever since i would always be less than args.length. Java Variables and Arithmetic Expressions Java Variables are used to store data. Variables have type, name, and value. Variable names begin with a character, such as x, D, Y, z. Other examples are xy1, abc2, Count, N, sum, Sum, product etc. These are all variable names. Different variable types are int, char, double. A variable type tells you what kind of data can be stored in that variable. The syntax of assignment statements is easy. Assignment statements look like this: variableName = expression ; For example: int x; // This means variable x can store numbers such as 2, 10, -5. char y; // This means variable y can store single characters 'a', 'A'. double z; // This means variable z can store real numbers such as 10.45, 3.13411. The above are declarations for variables x, y and z. Important points: 1. Note that a variable has to be declared before being used. 2. The values assigned to a variable correspond to its type. Statements below represent assignment of values to a variable. x = 100; // x is an integer variable. y = 'A'; // y is a character variable. abc = 10.45; // abc is of type double (real numbers). 3. Both variable declaration and assignment of values can be done in same statement. For example, int x; x = 100; is same as int x = 100; 4. A variable is declared only once. int x; // Declaration for x. x = 100; // Initialization. x = x + 12; // Using x in an assignment statement. Often in a program you want to give a variable, a constant value. This can be done: class ConstDemo { public static void main ( String[] arg ) { final double PI = 3.14; final double CONSTANT2 = 100; . . . . . . } } The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.) 2. Arithmetic Expressions -------------------------- An assignment statement or expression changes the value that is held in a variable. Here is a program that uses an assignment statement: class example { public static void main ( String[] args ) { long x ; //a declaration without an initial value x = 123; //an assignment statement System.out.println("The variable x contains: " + x ); } } Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %. The % operator is the remainder or modulo operator. Arithmetic expressions are used to assign arithmetic values to variables. An expression is a combination of literals, operators, variables, and parentheses used to calculate a value. The following code describes the use of different arithmetic expressions. int x, y, z; // Three integer variables declared at the same time. x = 10; y = 12; z = y / x; // z is assigned the value of y divided by x. // Here z will have value 1. z = x + y; // z is assigned the value of x+y // Here z will have value 22. z = y % x // z is assigned the value of remainder when y // is divided by x. Here z will have value 2. Java Boolean expressions are expressions which are either true or false. The different boolean operators are < (less than), > (greater than),

== (equal to), >= (greater or equal to), <= (less or equal), != (not equal to). Example:
int x = 10; int y = 4; int z = 5; (x <> 1) // This expression checks if y is greater than 1.


((x - y) == (z + 1)); // This expression checks
// if (x - y) equals (z + 1).

A boolean expression can also be a combination of other boolean expressions. Two or more boolean expressions can be connected using &&
(logical AND) and || (logical OR) operators.

The && operator represents logical AND. The expression is true only if both boolean expressions are true. The || operator represents logical
OR. This expression would be true if any one of the associated expressions is true.

Example:

int x = 10; int y = 4; int z = 5;

(x <= 10) && (y > 1) // This expression checks if x is less
// than 10 AND y is greater than 1.
// This expression is TRUE.

(x*y == 41) || (z == 5) // This expression checks if x*y is equal
// to 40 OR if z is equal to 5.
// This expression is FALSE

java@begin_3_operators

1:Java Arithmetic Operators

The Java programming language has includes five simple arithmetic operators like are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). The following table summarizes the binary arithmetic operators in the Java programming language.

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));

}
}


2:Java Assignment Operators

It's very common to see statement like the following, where you're adding something to a variable. Java Variables are assigned, or given, values using one of the assignment operators. The variable are always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment operator. The assignment operator is evaluated from right to left, so a = b = c = 0; would assign 0 to c, then c to b then b to a.

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;


3:Java Increment and Decrement Operators

There are 2 Increment or decrement operators -> ++ and --. These two operators are unique in that they can be written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix increment/decrement. The meaning is different in each case.

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);
}
}

}

4:Java Relational Operators

A relational operator compares two values and determines the relationship between them. For example, != returns true if its two operands are unequal. Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth. The relation operators in Java are: ==, !=, <, >, <=, and >=. The meanings of these operators are:
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(" i = " + (j < i)); //false System.out.println(" j = " + (k < j)); //false //less than or equal to System.out.println(" j = " + (i <= j)); //true System.out.println(" i = " + (j <= i)); //false System.out.println(" j = " + (k <= j)); //true //equal to System.out.println(" i ="="" j = " + (i == j)); //false System.out.println(" k ="="" j = " + (k == j)); //true //not equal to System.out.println(" j = " + (i != j)); //true System.out.println(" j =" ">

5: Java Boolean Operators
The Boolean logical operators are : | , & , ^ , ! , || , && , == , != . Java supplies a primitive data type called Boolean, instances of which can take the value true or false only, and have the default value false. The major use of Boolean facilities is to implement the expressions which control if decisions and while loops. 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)); } }


6:Java Conditional Operators Java has the conditional operator. It's a ternary operator -- that is, it has three operands -- and it comes in two pieces, ? and :, that have to be used together. It takes the form 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;