Java


 class Test{

}

Now we need to add our main function. The main function is of the type public static void so it can be accessed by the system. It has a String[] parameter for arguments passed from the command prompt. The program now looks like this:

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

Although this will compile, it will not be very impressive, it will literally do nothing.

Output :-
There is no cout or cin in Java. Although input is very difficult, output is fairly simple. The easiest way to do input is via passed parameters. To output, you use the functions print() and pringln(). Both take a String parameter. (I’ll tell you about String later.) print() just prints the string, println() prints the string and ends the line.
Here is an example Hello World program.

class Test{
public static void main( String[] arg ){
System.out.println(“Hello World”);
}
}

The System.out tells the compiler where to find println().

–> Classes
Classes are declared the same way they are as in C++ but the declaration is always with the definition. (Like if you did the definition in a C++ header file.) A difference is how variables are declared. In Java there are two variable types, value and referance. Both are declared the same way. The only differance is whether you are declaring a class variable or a simple variabe (like int). Class variables are referances, simple variables are values. Both are declared like a C++ value variable. To declare an empty class variable this means you must use the new operator.(vartype varname = new vartype();) Class variables can also be initiated using another class variable of a related type, but keep in mind that since they are referances, whatever happens to one, happens to the other. A differance with C++ referances is that Java referances aren’t const, so class variables can be assined to one another using equals at any time, but keep in mind that they are referances. Simple variables are declared just like in C++. A good thing about Java is that you don’t have to worry about delete, Java takes care of it Garbage Collect. (a method of automatically recovering memory) A differance between these and C++ referance
See the end of the next section for an example.
—> String
String is the Java string handling class. Strings can be concatenating using +.

Here is an example program using concatenation:

 
class Test{
public static void main( String[] arg ){
System.out.println(“Hello” + ” ” + “World”);
}
}

Classes cannot have true automatic type conversions like they can in C++ using operator, but they can be automatically converted to a String using a toString() function.
Here is a two class Hello World program that uses toString().

class Test{
public static void main( String[] arg ){
HelloClass hello = new HelloClass();
System.out.println(hello);
}
}

class HelloClass{
public String toString(){
return “Hello World”;
}
}
Section 6: Inheritance
Normal inheritance is done using extends where public or private is used in C++ inheritance. Multiple inheritance is not allowed.
Abstract classes are implemented using interface in the place of class. Interfaces are inherited using implements. Multiple interfaces can be implemented by separating the names for the interfaces with commas.
A single class can both extend and implement. Here is an example:

class Cube extends Square implements ThreeDShape{
}
Section 7: Advanced Topics
In Java, instead of using #include you use import. For example if you wanted to use Windows classes you would:
import java.awt.*;
Another different reserved word is final. It is kind-of like const, but more powerful. It can be used with a variable where it functions exactly like const. It can also be used on a class making it so the class cannot be extended.
Things not mentioned here, like if else while for etc. function exactly like in C++.

Last updated: June 27, 2001
PART-1
• Java Hello World Program
• Java Comments
• Java Data and Variables
• Java Command Line Arguments

Java Hello World Program
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!!
Next: Java Comments

Java Comments
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.

Next: Java Data and Variables
Java Data and Variables
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 byte value is 127.
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.
Java Command Line Arguments
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<args.length;++i)
{
System.out.println( args[i] );
}
}
}

Sample Run
With the following command line, the output shown is produced.

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

PART-2
• Java Arithmetic Operators
• Java Assignment Operators
• Java Increment and Decrement Operators
• Java Relational Operators
• Java Boolean Operators
• Java Conditional Operators

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

}
}

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;

PART-2
• Java Arithmetic Operators
• Java Assignment Operators
• Java Increment and Decrement Operators
• Java Relational Operators
• Java Boolean Operators
• Java Conditional Operators

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

}

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(” 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
}
}

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

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;

PART-3
• Java If-else Statement
• Java Loops (while, do-while and for loops)
• Java Variables and Arithmetic Expressions

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 < 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();
}
}
PART-3
• Java If-else Statement
• Java Loops (while, do-while and for loops)
• Java Variables and Arithmetic Expressions

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.

PART-3
• Java If-else Statement
• Java Loops (while, do-while and for loops)
• Java Variables and Arithmetic Expressions

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 < 10) // This expression checks if x is less than 10.

(y > 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

PART-4
• Methods (Includes Recursive Methods)
• Arrays
• Classes and Objects
• Interfaces
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]);

}
}

PART-4
• Methods (Includes Recursive Methods)
• Arrays
• Classes and Objects
• Interfaces

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&#8221;;
x.description = “A Java Programming Website”;

System.out.println(x.name + ” at ” + x.url + ” is ” + x.description);
1
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)));
The complete listing of class declaration:
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”);
}
}

class example1{
public static void main(String args[])
{
// To create a new instance class
Simple sim = new Simple();
// To show the result of the addNumbers
System.out.println(“The result is ” + Integer.toString(addNumbers(5,1,2)));
// To display message
sim.displayMessage();
}
}
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.

Part5
• Catching Exceptions
• File I/O and Streams
• How to make executable jar files in JDK1.3.1?

Catching Exceptions
An exception is a point in the code where something out of the ordinary has happened and the regular flow of the program needs to be interrupted; an exception is not necessarily an error. A method which has run into such a case will throw an exception using the throw(ExceptionClass) method. When an exception is thrown it must be caught by a catch statement that should sit right after a try statement.
// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

/* Now let’s say hello */
System.out.print(“Hello “);
System.out.println(args[0]);
}

}
If you run the program without giving it any command line arguments, then the runtime system generates an exception something like,
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7)
Since we didn’t give Hello any command line arguments there wasn’t anything in args[0]. Therefore Java kicked back this not too friendly error message about an “ArrayIndexOutOfBoundsException.”
we can fix this problem by testing the length of the array before we try to access its first element (using array.length). This works well in this simple case, but this is far from the only such potential problem.
What is an Exception ?

Let us see what happens when an exception occurs and is not handled properly

When you compile and run the following program

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// a division by 0 occurs here.
int z = x/y;
System.out.println(“after didvision”);
}
}

The execution of the Test stops and this is caused by the division by zero at – x/y – an exception has been thrown but has not been handled properly.

How to handle an Exception ?

To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows

public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// try block to “SEE” if an exception occurs
try{
int z = x/y;
System.out.println(“after didvision”);
// catch clause below handles the
// ArithmeticException generated by
// the division by zero.
} catch (ArithmeticException ae)
{System.out.println(” attempt to divide by 0″);}
System.out.println(” after catch “);
}
}

The output of the above program is as follows

attempt to divide by 0
after catch

the statement – System.out.println(“after didvision”) – is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block.
The goal of exception handling is to be able to define the regular flow of the program in part of the code without worrying about all the special cases. Then, in a separate block of code, you cover the exceptional cases. This produces more legible code since you don’t need to interrupt the flow of the algorithm to check and respond to every possible strange condition. The runtime environment is responsible for moving from the regular program flow to the exception handlers when an exceptional condition arises.
In practice what you do is write blocks of code that may generate exceptions inside try-catch blocks. You try the statements that generate the exceptions. Within your try block you are free to act as if nothing has or can go wrong. Then, within one or more catch blocks, you write the program logic that deals with all the special cases.
To start a section of code which might fail or not follow through you start a try clause:
try
{
// Section of code which might fail
}
The try statement is needed in case of an exception. If the read fails in some way it will throw an exception of type java.io.IOException. That exception must be caught in this method, or the method can declare that it will continue throwing that message. Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications. After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block. Exceptions that are not caught will be passed up to the next level, such as the function that called the one which threw the exception, and so on. .
try
{
// Section of code which might fail
}
catch (Exception1ThatCanHappen E)
{
// things to do if this exception was thrown..
}
catch (Exception2ThatCanHappen E)
{
// things to do if this exception was thrown..
}
Here’s an example of exception handling in Java using the Hello World program above:
Source Code
// This is the Hello program in Java
class ExceptionalHello {

public static void main (String args[]) {

/* Now let’s say hello */
try {
System.out.println(“Hello ” + args[0]);
}
catch (Exception e) {
System.out.println(“Hello whoever you are”);
}
}

}
You may or may not print an error message. If you write an exception handler and you don’t expect it to be called, then by all means put a
System.out.println(“Error: ” + e);
This has the folowing advantages over handling your errors internally:
• You can react to an error in custom defined way. A read error does not mean that the program should crash.
• You can write code with no worry about failure which will be handled by the users of your class.
• You can group your error handling code much better.
• You can make your application more transactional focused with nested try catch blocks:
A simple Java code which demonstrates the exception handling in Java
Refer to the java API document to see all exception types that can be handled in Java.
Source Code
public class excep2
{
public static void main(String args[])
{
int i =0 ;
//Declare an array of strings
String Box [] = {“Book”, “Pen”, “Pencil”};
while(i<4)
{
try
{
System.out.println(Box[i]);

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Subscript Problem ” + e);
i++;
}
finally
{
System.out.println(“This is always printed.”);
}
i++;
}
}
}

PART-5
• Catching Exceptions
• File I/O and Streams
• How to make executable jar files in JDK1.3.1?

File I/O and Streams
You can write data to a file instead of the computer screen. You can write certain data to a file while still putting other data on the screen. Or you may need access to multiple files simultaneously. Or you may want to query the user for input rather than accepting it all on the command line. Or maybe you want to read data out of a file that’s in a particular format. In Java all these methods take place as streams. < > Using File I/O streams. The System.out.println() statement we’ve been using all along is an implementation of Streams.
A program that writes a string to a file
In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner

import java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.
Source Code
/*
* FileOutput
* Demonstration of FileOutputStream and PrintStream classes
*/

import java.io.*;

class FileOutput
{

public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream connected to “myfile.txt”
out = new FileOutputStream(“myfile.txt”);

// Connect print stream to the output stream
p = new PrintStream( out );

p.println (“This is written to a file myFile.txt”);

p.close();
}
catch (Exception e)
{
System.err.println (“Error writing to the file myFile.txt”);
}
}
}
Interactively communicating with the user
Program asking the user for their name and then prints a personalized greeting.
Source Code
import java.io.*;

class PersonalHello {

public static void main (String args[])
{

byte name[] = new byte[100];
int nr_read = 0;

System.out.println(“Your name Please?”);
try {
nr_read = System.in.read(name);
System.out.print(“Hello “);
System.out.write(name,0,nr_read);
}
catch (IOException e) {
System.out.print(“I did not get your name.”);
}

}

}
In code that does any significant input or output you’ll want to begin by importing all the various java.io classes. import.java.io.*; Most of the reading and writing you do in Java will be done with bytes. Here we’ve started with an array of bytes that will hold the user’s name.
First we print a query requesting the user’s name. Then we read the user’s name using the System.in.read() method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print “Hello.” Finally we print the user’s name.
The program doesn’t actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.
Reading Numbers
Often strings aren’t enough. A lot of times you’ll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.
The getNextInteger() method that will accept an integer from the user. Here it is:
static int getNextInteger() {

String line;

DataInputStream in = new DataInputStream(System.in);
try {
line = in.readLine();
int i = Integer.valueOf(line).intValue();
return i;
}
catch (Exception e) {
return -1;
}

} // getNextInteger ends here
Reading Formatted Data
It’s often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.
Writing a text file
Sometimes you want to save your output in a file. To do this we’ll need to learn how to write data to a file.
Source Code
// Write the Fahrenheit to Celsius table in a file

import java.io.*;

class FahrToCelsius {

public static void main (String args[]) {

double fahr, celsius;
double lower, upper, step;

lower = 0.0; // lower limit of temperature table
upper = 300.0; // upper limit of temperature table
step = 20.0; // step size

fahr = lower;

try {

FileOutputStream fout = new FileOutputStream(“test.out”);

// now to the FileOutputStream into a PrintStream
PrintStream myOutput = new PrintStream(fout);

while (fahr <= upper) { // while loop begins here
celsius = 5.0 * (fahr-32.0) / 9.0;
myOutput.println(fahr + ” ” + celsius);
fahr = fahr + step;
} // while loop ends here

} // try ends here
catch (IOException e) {
System.out.println(“Error: ” + e);
System.exit(1);
}

} // main ends here

}
There are only three things necessary to write formatted output to a file rather than to the standard output:
1. Open a FileOutputStream using a line like
FileOutputStream fout = new FileOutputStream(“test.out”);
This line initializes the FileOutputStream with the name of the file you want to write into.
2. Convert the FileOutputStream into a PrintStream using a statement like
PrintStream myOutput = new PrintStream(fout);
The PrintStream is passed the FileOutputStream from step 1.
3. Instead of using System.out.println() use myOutput.println(). System.out and myOutput are just different instances of the PrintStream class. To print to a different PrintStream we keep the syntax the same but change the name of the PrintStream.
Reading a text file
Now that we know how to write a text file, let’s try reading one. The following code accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.
// Imitate the Unix cat utility

import java.io.*;

class cat {

public static void main (String args[]) {

String thisLine;

//Loop across the arguments
for (int i=0; i < args.length; i++) {

//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args[i]);

// now turn the FileInputStream into a DataInputStream
try {
DataInputStream myInput = new DataInputStream(fin);

try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println(“Error: ” + e);
}
} // end try
catch (Exception e) {
System.out.println(“Error: ” + e);
}

} // end try
catch (Exception e) {
System.out.println(“failed to open file ” + args[i]);
System.out.println(“Error: ” + e);
}
} // for end here

} // main ends here

}
PART-5
• Catching Exceptions
• File I/O and Streams
• How to make executable jar files in JDK1.3.1?

How to make executable jar files in JDK1.3.1?
Instructions for creating an Executable .jar file
Make or modify the Manifest.MF to YourManifest.MF.

1) YourClassNameWithMain is the class name (case sensitive) without .class extension
2) No extra spaces following the YourClassName withMain.

Manifest-Version:1.0
Main-Class: YourClassNameWithMain
Created-by:1.2(Sun Microsystems Inc.)
On Command line : type the following
jar cvfm YourJarFileName.jar YourManifest.MF*

or

jar cvfm YourJarFileName.jar YourManifest.MF -C classes yourClassPath
Drag-drop the YourJarFileName.jar to your desktop double click it, it runs
If your program only has System.out.println (“whatever”); statements, it will
display nothing. The same will happen when you run it useing java at command line
3. 8. 1. The ? Operator (Ternary)

 

 

public class MainClass {
public static void main(String args[]) {
int i, k;

i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print(“Absolute value of “);
System.out.println(i + ” is ” + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print(“Absolute value of “);
System.out.println(i + ” is ” + k);
}
}

 

Absolute value of 10 is 10
Absolute value of -10 is 10

4. 2. 1. The switch Statement
1. An alternative to a series of else if is the switch statement.
2. The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.
3. The expression used in the switch statement must return an int or an enumerated value.
The syntax of the switch statement is as follows.

switch (expression) {
case value_1 :

statement (s);
break;
case value_2 :
statement (s);
break;
.
.
.
case value_n :
statement (s);
break;
default:
statement (s);
}

Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.
Here is an example of the switch statement:

public class MainClass {

public static void main(String[] args) {
int i = 1;
switch (i) {
case 1 :
System.out.println(“One.”);
break;
case 2 :
System.out.println(“Two.”);
break;
case 3 :
System.out.println(“Three.”);
break;
default:
System.out.println(“You did not enter a valid value.”);
}
}

}

 

You need some windows code to see it run
Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to zip utility, and more Java.

You can use it on any machine installed JDK
Create a folder name it anything
Make that folder your current directory
put all your files for turning in (do not put any extra) in that directory.

Be sure to put your html file, if there is one
At your dos prompt, while you are in the directory that you created , type in:
jar cvf Prj02.jar*
This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 that can be replaced by any of your desired jar file name.
To test it, you can extract the contents of jar file by typing:
jar xvf Prj02.jar

 

4. 3. 1. The while Statement
1. One way to create a loop is by using the while statement.
2. Another way is to use the for statement
The while statement has the following syntax.

while (booleanExpression) {
statement (s)
}

1. statement(s) will be executed as long as booleanExpression evaluates to true.
2. If there is only a single statement inside the braces, you may omit the braces.
3. For clarity, you should always use braces even when there is only one statement.
As an example of the while statement, the following code prints integer numbers that are less than three.

public class MainClass {

public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}
}

}

 

To produce three beeps with an interval of 500 milliseconds, use this code:

public class MainClass {

public static void main(String[] args) {
int j = 0;
while (j < 3) {
java.awt.Toolkit.getDefaultToolkit().beep();
try {
Thread.currentThread().sleep(500);
} catch (Exception e) {
}
j++;
}
}

}

 

Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on the break statement to escape from the loop.

public class MainClass {

public static void main(String[] args) {
int k = 0;
while (true) {
System.out.println(k);
k++;
if (k > 2) {
break;
}
}
}

}

 

 

Using the while loop to calculate sum

 

public class MainClass {
public static void main(String[] args) {
int limit = 20;
int sum = 0;
int i = 1;

while (i <= limit) {
sum += i++;
}
System.out.println(“sum = ” + sum);
}
}

 

4. 3. 3. While loop with double value

 

public class MainClass {
public static void main(String[] args) {
double r = 0;
while(r < 0.99d) {
r = Math.random();
System.out.println(r);
}
}
}

 

0.4377278997305387
0.2688654455422754
0.36392537297385574
0.15254413511361042
0.6688621030424611
0.143156733550304
0.3867695752401421
0.6348496031126075
0.8262243996358971
0.057290108917235516
0.48887104413122007
0.9181002018325309
0.03580026338719999
0.6915245271034702
0.06281957479185263
0.7484170566879976
0.08309381253696246
0.7708638307798187
0.6586973690207539
0.3606321940413979
0.17404632324149583
0.1007512703731156
0.7971297767971545
0.4461084890266951
0.8627269068871244
0.04984737498714209
0.2597921665157922
0.5410470601800582
0.5779541886682865
0.1847556794086489
0.32127067165147705
0.12266607697656651
0.62729812639505
0.12191275953517977
0.72308829958122
0.5766115831015479
0.03444891261877858
0.3034596140603594
0.058872682884219985
0.85618745813345
0.07472991871327217
0.32676415639620604
0.6390549075075913
0.09246846051500635
0.9135703200463736
0.661365290176903
0.834153688687532
0.6340862529502882
0.3240420706550172
0.07246065490188025
0.35761285323105796
0.9964556875646731
4. 3. 4. Java’s ‘labeled while’ loop

 

public class MainClass {
public static void main(String[] args) {
int i = 0;
outer: while (true) {
System.out.println(“Outer while loop”);
while (true) {
i++;
System.out.println(“i = ” + i);
if (i == 1) {
System.out.println(“continue”);
continue;
}
if (i == 3) {
System.out.println(“continue outer”);
continue outer;
}
if (i == 5) {
System.out.println(“break”);
break;
}
if (i == 7) {
System.out.println(“break outer”);
break outer;
}
}
}
}
}
Outer while loop
i = 1
continue
i = 2
i = 3
continue outer
Outer while loop
i = 4
i = 5
break
Outer while loop
i = 6
i = 7
break outer
4. 4. 1. The do-while Statement
The do-while statement is like the while statement, except that the associated block always gets executed at least once.
Its syntax is as follows:

do {
statement (s)
} while (booleanExpression);

Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.

public class MainClass {

public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 3);
}

}

 

This prints the following to the console:

0
1
2

The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.

public class MainClass {

public static void main(String[] args) {
int j = 4;
do {
System.out.println(j);
j++;
} while (j < 3);
}

}

 

This prints the following on the console.
4
. 4. 2. The do while loop in action

 

do {
// statements
} while (expression);
public class MainClass {
public static void main(String[] args) {
int limit = 20;
int sum = 0;
int i = 1;

do {
sum += i;
i++;
} while (i <= limit);

System.out.println(“sum = ” + sum);
}
}

sum = 210
4. 5. 1. The for Statement
The for statement is like the while statement, i.e. you use it to create loop. The for statement has following syntax:

for ( init ; booleanExpression ; update ) {
statement (s)
}

1. init is an initialization that will be performed before the first iteration.
2. booleanExpression is a boolean expression which will cause the execution of statement(s) if it evaluates to true.
3. update is a statement that will be executed after the execution of the statement block.
4. init, expression, and update are optional.
The for statement will stop only if one of the following conditions is met:
1. booleanExpression evaluates to false
2. A break or continue statement is executed
3. A runtime error occurs.
4. 5. 2. For statement in detail
It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.
For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is not visible anywhere else since it is declared within the for loop.

public class MainClass {

public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i + ” “);
}
}
}

 

The initialization part of the for statement is optional.

public class MainClass {

public static void main(String[] args) {
int j = 0;
for (; j < 3; j++) {
System.out.println(j);
}
// j is visible here
}

}

 

The update statement is optional.

public class MainClass {

public static void main(String[] args) {
int k = 0;
for (; k < 3;) {
System.out.println(k);
k++;
}
}

}

 

You can even omit the booleanExpression part.

public class MainClass {

public static void main(String[] args) {
int m = 0;
for (;;) {
System.out.println(m);
m++;
if (m > 4) {
break;
}
}
}

}

 

If you compare for and while, you’ll see that you can always replace the while statement with for. This is to say that

while (expression) {

}

can always be written as

for ( ; expression; ) {

}

 

4. 5. 3. A loop allows you to execute a statement or block of statements repeatedly

 

public class MainClass {
public static void main(String[] args) {
for (int i = 0; i < 8; i++) {
System.out.println(“Hi.”);
}
}
}

Hi.
Hi.
Hi.
Hi.
Hi.
Hi.
Hi.
Hi.

 

4. 5. 4. The numerical for loop

 

for (initialization_expression ; loop_condition ; increment_expression) {
// statements
}
public class MainClass {
public static void main(String[] args) {
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable

for (int i = 1; i <= limit; i++) {
sum = sum + i;
}
System.out.println(“sum = ” + sum);
}
}

 

4. 5. 5. initialization_expression: define two variables in for loop

 

public class MainClass {

public static void main(String[] arg) {
int limit = 10;
int sum = 0;
for (int i = 1, j = 0; i <= limit; i++, j++) {
sum += i * j;
}
System.out.println(sum);
}
}

330
1. The break statement is used to break from an enclosing do, while, for, or switch4. 7. 1. The break Statement statement.
2. It is a compile error to use break anywhere else.
3. ‘break’ breaks the loop without executing the rest of the statements in the block.
For example, consider the following code

public class MainClass {

public static void main(String[] args) {
int i = 0;
while (true) {
System.out.println(i);
i++;
if (i > 3) {
break;
}
}
}

}

 

The result is
0
1
2
3

 

4. 8. 1. The continue Statement
The continue statement stops the execution of the current iteration and causes control to begin with the next iteration.
For example, the following code prints the number 0 to 9, except 5.

public class MainClass {

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}
}

}

 

4. 8. 3. The Labeled continue statement

 

public class MainClass {
public static void main(String[] args) {
int limit = 20;
int factorial = 1;

OuterLoop: for (int i = 1; i <= limit; i++) {
factorial = 1;
for (int j = 2; j <= i; j++) {
if (i > 10 && i % 2 == 1) {
continue OuterLoop;
}
factorial *= j;
}
System.out.println(i + “! is ” + factorial);
}
}
}

1! is 1
2! is 2
3! is 6
4! is 24
5! is 120
6! is 720
7! is 5040
8! is 40320
9! is 362880
10! is 3628800
12! is 479001600
14! is 1278945280
16! is 2004189184
18! is -898433024
20! is -2102132736
4. 8. 4. Calculating Primes: using continue statement and label
continue may be followed by a label to identify which enclosing loop to continue to.

public class MainClass {
public static void main(String[] args) {
int nValues = 50;

OuterLoop: for (int i = 2; i <= nValues; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
continue OuterLoop;
}
}
System.out.println(i);
}
}
}

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
7. 3. 1. How to define an Array
1. An array is a named set of same-type variables.
2. Each variable in the array is called an array element.
3. The first element will have an index of 0.

public class MainClass {

public static void main(String[] arg) {
int[] intArray = new int[10];

for (int i = 0; i < 10; i++) {
intArray[i] = 100;
}

for (int i = 0; i < 10; i++) {
System.out.println(intArray[i]);
}

}

}

100
100
100
100
100
100
100
100
100
100
7. 3. 2. Initializing array elements by index

 

public class MainClass {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println(“April has ” + month_days[3] + ” days.”);
}
}

April has 30 days.
. 3. 3. Alternative Array Declaration Syntax
For example, the following two declarations are equivalent:

int al[] = new int[3];
int[] a2 = new int[3];

The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the same time:

int[] nums, nums2, nums3; // create three arrays
7. 3. 4. Anonymous arrays are declared similarly to regular arrays

 
new type[] {comma-delimited-list}

 

public class MainClass {
public static void main (String args[]) {
int array1[] = {1, 2, 3, 4, 5};

for(int i: array1){
System.out.println(i);

}
}
}

1
2
3
4
5

7. 3. 5. An array is a Java object

 

public class MainClass {
static String[] names;

public static void main(String[] a) {

if (names == null) {
System.out.println(“true”);
} else {
System.out.println(“false”);
}

}

}

true

7. 3. 6. To reference the components of an array
To reference the components of an array, use an index after the variable name. For example, the following snippet creates an array of four String objects and initializes its first member.
7. 3. 7. The Length of an Array

 

public class MainClass {

public static void main(String[] arg) {
int[] intArray = new int[10];

for (int i = 0; i < intArray.length; i++) {
intArray[i] = 100;
}

for (int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}

}

}

100
100
100
100
100
100
100
100
100
100

public class MainClass {

public static void main(String[] args) {
String[] names = new String[4];
names[0] = “Hello World”;

}

}

 

 

. 3. 8. Initializing Arrays

 

public class MainClass{

public static void main(String[] arg){
int[] primes = {2, 3, 5, 7, 11, 13, 17}; // An array of 7 elements

for (int i = 0; i < primes.length; i++) {
System.out.println(primes[i]);
}
}

}

2
3
5
7
11
13
17

 

. 3. 10. Arrays of Characters

 

public class MainClass{

public static void main(String[] arg){
char[] message = new char[50];
java.util.Arrays.fill(message, ‘A’);
for(char ch: message){
System.out.println(ch);
}
}
}

A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
7. 3. 11. Using the Collection-Based for Loop with an Array
You can now use it to iterate over an array or a collection without the index. Use this syntax to iterate over an array:

for (componentType variable: arrayName)

Where arrayName is the reference to the array, componentType is the component type of the array, and variable is a variable that references each component of the array.

import java.util.Arrays;

public class MainClass {

public static void main(String[] arg) {
double[] data = new double[50]; // An array of 50 values of type double
Arrays.fill(data, 1.0); // Fill all elements of data with 1.0

for (double d: data) {
System.out.println(d);
}

}
}

1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
7. 3. 12. Changing Array Size
Once an array is created, its size cannot be changed. If you want to change the size, you must create a new array and populates it using the values of the old array.

public class MainClass {

public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };

int[] temp = new int[4];
int length = numbers.length;
for (int j = 0; j < length; j++) {
temp[j] = numbers[j];
}
numbers = temp;

}

}

 

7. 3. 9. Using a for loop to iterate over all the elements and set the values

 

public class MainClass {

public static void main(String[] arg) {
double[] data = new double[50]; // An array of 50 values of type double
for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1
data[i] = 1.0;
}

for (int i = 0; i < data.length; i++) { // i from 0 to data.length-1
System.out.println(data[i]);
}

}
}

1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0

 

import java.io.*;
public class AddTwoNo{
public static void main(String[] args){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println(“Enter the first no: “);
String num1 = br.readLine();
System.out.println(“Enter the second no: “);
String num2 = br.readLine();
int n1 = Integer.parseInt(num1);
int n2 = Integer.parseInt(num2);
int sum = n1+n2;
System.out.println(“Sum: “+sum);
System.out.println(“Enter any name to display: “);
String name = br.readLine();
System.out.print(“You Have Entered: “+name);
}catch (IOException e){
System.out.println(e);
}
}
}//–close

 

 

5. 17. 1. Creating Objects
1. Using the new keyword.
2. new is always followed by the constructor of the class.
For example, to create an Employee object, you write:
Employee employee = new Employee();

Here, ’employee’ is an object reference of type Employee.
1. Once you have an object, you can call its methods and access its fields, by using the object reference.
2. You use a period (.) to call a method or a field.
For example:

objectReference.methodName
objectReference.fieldName

The following code, for instance, creates an Employee object and assigns values to its age and salary fields:

public class MainClass {

public static void main(String[] args) {
Employee employee = new Employee();
employee.age = 24;
employee.salary = 50000;
}

}

class Employee {
public int age;
public double salary;
public Employee() {
}
public Employee(int ageValue, double salaryValue) {
age = ageValue;
salary = salaryValue;
}
}

 

AWT
14. 1. 1. Handle screen updates

 
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
g.drawString (Long.toString(System.currentTimeMillis()), 10, 30);
repaint(1000);
}
}

public class SettingFont {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

14. 2. 1. Off Screen Paint: create Graphics from BufferedImage

 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Arc2D;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
private BufferedImage offImg;

public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D) g;

// Draw the pie chart
Arc2D.Float arc = new Arc2D.Float(Arc2D.PIE);
arc.setFrame(140, 200, 67, 46);
arc.setAngleStart(45);
arc.setAngleExtent(270);
g2.setColor(Color.gray);
g2.draw(arc);
g2.setColor(Color.red);
g2.fill(arc);
g2.setColor(Color.black);
g2.drawString(“Arc2D.PIE”, 140, 190);
}

public Graphics2D createDemoGraphics2D(Graphics g) {
Graphics2D g2 = null;

if (offImg == null || offImg.getWidth() != getSize().width
|| offImg.getHeight() != getSize().height) {
offImg = (BufferedImage) createImage(getSize().width, getSize().height);
}

if (offImg != null) {
g2 = offImg.createGraphics();
g2.setBackground(getBackground());
}

// .. set attributes ..
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

// .. clear canvas ..
g2.clearRect(0, 0, getSize().width, getSize().height);

return g2;
}

public void paint(Graphics g) {
if (getSize().width <= 0 || getSize().height <= 0)
return;

Graphics2D g2 = createDemoGraphics2D(g);
draw(g2);

g2.dispose();

if (offImg != null && isShowing()) {
g.drawImage(offImg, 0, 0, this);
}
}

}

public class OffScreenPaint {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
14. 3. 1. The Three Font Styles
Constant Description
Font.BOLD The bold style constant
Font.ITALIC The italicized style constant
Font.PLAIN The plain style constant

 

14. 3. 2. Use fonts in paint

 
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
Font courier = new Font (“Courier”, Font.PLAIN, 12);
Font system = new Font (“System”, Font.BOLD, 16);
Font helvetica = new Font (“Helvetica”, Font.BOLD, 18);

g.setFont (courier);
g.drawString (“Courier”, 10, 30);
g.setFont (system);
g.drawString (“System”, 10, 70);
g.setFont (helvetica);
g.drawString (“Helvetica”, 10, 90);
}
}

public class SettingFont {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

14. 4. 1. Draw Arc

 

import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
g.drawArc (10, 10, 200, 200,50,50);
}
}

public class DrawArc {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
14. 4. 2. Fill Arc

 

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillArc(20, 20, 200, 200,200,200);
}
}

public class FillArc {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

14. 4. 3. Arc2D PIE

 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;

// Draw the pie chart
Arc2D.Float arc = new Arc2D.Float(Arc2D.PIE);
arc.setFrame(140, 200, 67, 46);
arc.setAngleStart(45);
arc.setAngleExtent(270);
g2.setColor(Color.gray);
g2.draw(arc);
g2.setColor(Color.red);
g2.fill(arc);
g2.setColor(Color.black);
g2.drawString(“Arc2D.PIE”, 140, 190);
}
}

public class Graphics2DDrawArcPIE {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

14. 4. 4. Arc2D OPEN

 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;

//Draw the open arc
Arc2D.Float arc = new Arc2D.Float(Arc2D.OPEN);
arc.setFrame(140,100, 67, 46);
arc.setAngleStart(45);
arc.setAngleExtent(270);
g2.setColor(Color.gray);
g2.draw(arc);
g2.setColor(Color.green);
g2.fill(arc);
g2.setColor(Color.black);
g2.drawString(“Arc2D.OPEN”, 140, 90);
}
}

public class Graphics2DDrawArcOPEN {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

14. 4. 5. Arc2D Chord

 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;

//Draw the chord

Arc2D.Float arc1 = new Arc2D.Float(Arc2D.CHORD);
arc1.setFrame(140,30, 67, 46);
arc1.setAngleStart(45);
arc1.setAngleExtent(270);
g2.setColor(Color.blue);
g2.draw(arc1);
g2.setColor(Color.gray);
g2.fill(arc1);
g2.setColor(Color.black);
g2.drawString(“Arc2D.CHORD”, 140, 20);
}
}

public class Graphics2DDrawArcChord {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
14. 5. 1. java.awt.Color
A Color object represents a color. Color class provides static fields that return a specific Color object: BLACK, BLUE, GREEN, RED, CYAN, ORANGE, YELLOW.
For example, to obtain a Color object that represents green, use this code:

Color color = Color.GREEN;

Create a custom color by passing red-green-blue (RGB) values to the Color class’s constructor:

Color myColor = new Color (246, 27, 27);

To change a component’s color, call the setForeGround and setBackGround methods of the component.

component.setForeGround (Color.YELLOW);
component.setBackGround (Color.RED);
14. 5. 2. To compare two Color objects you can use the equals() method

 

import java.awt.Color;
public class MainClass {
public static void main(String[] a) {
Color myBlack = new Color(0, 0, 0); // Color black
Color myWhite = new Color(255, 255, 255); // Color white
System.out.println(myBlack.equals(myWhite));
}
}

false

 

14. 5. 3. Using the getRGB() method for comparing colors

 

import java.awt.Color;
public class MainClass {
public static void main(String[] a) {
Color myBlack = new Color(0, 0, 0); // Color black
Color myWhite = new Color(255, 255, 255); // Color white
System.out.println(myBlack.getRGB() == myWhite.getRGB());
System.out.println(myBlack.getRGB());
System.out.println(myWhite.getRGB());
}
}

false
-16777216
-1

14. 5. 4. Construct Color object

 

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;

public class ColorSample {
public static void main(String args[]) {
JFrame f = new JFrame(“JColorChooser Sample”);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton(“Pick to Change Background”);
Color myBlack = new Color(0,0,0); // Color black
// Color myWhite = new Color(255,255,255); // Color white
// Color myGreen = new Color(0,200,0); // A shade of green

button.setBackground(myBlack);
f.add(button, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}

14. 5. 5. Java Predefined Colors
Predefined Color RGB Values
black (0,0,0)
blue (0,0,255)
cyan (0,255,255)
darkGray (64,64,64)
gray (128,128,128)
green (0,255,0)
lightGray (192,192,192)
magenta (255,0,255)
orange (255,200,0)
pink (255,175,175)
red (255,0,0)
white (255,255,255)
yellow (255,255,0)

 

14. 5. 6. Using color with and Bit and

 

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
Color[] colors = new Color[24];

public MyCanvas() {
int rgb = 0xff;
for (int i = 0; i < 24; i++) {
colors[i] = new Color(rgb);
rgb <<= 1;
if ((rgb & 0x1000000) != 0) {
rgb |= 1;
rgb &= 0xffffff;
}
}
}

public void paint(Graphics g) {
int i = 10;
for (Color c : colors) {
g.setColor(c);
i += 10;
g.drawLine(i, 10, 200, 200);
}
}
}

public class DrawLine {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

14. 6. 1. Complex Paths: Star

 

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
Point2D.Float point = new Point2D.Float(100, 100); // store start point
GeneralPath p = new GeneralPath(GeneralPath.WIND_NON_ZERO);
p.moveTo(point.x, point.y);
p.lineTo(point.x + 20.0f, point.y – 5.0f); // Line from start to A
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 5.0f, point.y – 20.0f); // Line from A to B
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 5.0f, point.y + 20.0f); // Line from B to C
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x + 20.0f, point.y + 5.0f); // Line from C to D
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x – 20.0f, point.y + 5.0f); // Line from D to E
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x – 5.0f, point.y + 20.0f); // Line from E to F
point = (Point2D.Float)p.getCurrentPoint();
p.lineTo(point.x – 5.0f, point.y – 20.0f); // Line from F to g
p.closePath(); // Line from G to start
g2D.draw(p);
}
}
public class PaintStar {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
14. 7. 1. Draw a line

 
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.drawLine(20, 20, 200, 200);

}
}

public class DrawLine {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

 

14. 8. 1. Draw Oval

 

import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
g.drawOval (10, 10, 200, 200);
}
}

public class DrawOval {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}

 

14. 9. 1. Draw Polygon

 

import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

public void paint(Graphics g) {
int[] x = new int[]{100,200,300,400};
int[] y = new int[]{400,300,300,100};
g.drawPolygon (x, y, x.length);
}
}

public class DrawPolygon {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
14. 10. 1. Cyclic Gradient Paint

 

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
class GradientPane extends JComponent {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
Point2D.Float p1 = new Point2D.Float(150.f, 75.f); // Gradient line start
Point2D.Float p2 = new Point2D.Float(250.f, 75.f); // Gradient line end
float width = 300;
float height = 50;
GradientPaint g1 = new GradientPaint(p1, Color.WHITE, p2, Color.DARK_GRAY, true); // Cyclic
// gradient
Rectangle2D.Float rect1 = new Rectangle2D.Float(p1.x – 100, p1.y – 25, width, height);
g2D.setPaint(g1); // Gradient color fill
g2D.fill(rect1); // Fill the rectangle
g2D.setPaint(Color.BLACK); // Outline in black
g2D.draw(rect1); // Fill the rectangle
g2D.draw(new Line2D.Float(p1, p2));
}
}
public class CyclicGradientPaint {
public static void main(String[] a) {
JFrame window = new JFrame(“Cyclic Gradient Paint”);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new GradientPane());
window.setVisible(true);
}
}

 

14. 10. 2. Acyclic Gradient Paint

 

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
class GradientPane extends JComponent {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
Point2D.Float p1 = new Point2D.Float(150.f, 75.f); // Gradient line start
Point2D.Float p2 = new Point2D.Float(250.f, 75.f); // Gradient line end
float width = 300;
float height = 50;
Rectangle2D.Float rect1 = new Rectangle2D.Float(p1.x – 100, p1.y – 25, width, height);
GradientPaint g2 = new GradientPaint(p1, Color.WHITE, p2, Color.DARK_GRAY, false); // Acyclic
// gradient
rect1.setRect(p1.x – 100, p1.y – 25, width, height);
g2D.setPaint(g2); // Gradient color fill
g2D.fill(rect1); // Fill the rectangle
g2D.setPaint(Color.BLACK); // Outline in black
g2D.draw(rect1); // Fill the rectangle
g2D.draw(new Line2D.Float(p1, p2));
}
}
public class AcyclicGradientPaint {
public static void main(String[] a) {
JFrame window = new JFrame(“Acyclic Gradient Paint”);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new GradientPane());
window.setVisible(true);
}
}

 

Advertisements

Will get back to you soon. :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s