Wednesday, September 8, 2010

Array sample program

hello world.. hello programmers... i want to share to you how to make a sample program array using java..

I hope you learn and enjoy reading my blog...

import java.io.*;

public class javaarray
{
public static void main(String args[])
{
int x[]=new int[3];

x[0]=100;
x[1]=200;
x[2]=300;

//display result

System.out.println("The array[0]=" + x[0]);
System.out.println("The array[1]=" + x[1]);
System.out.println("The array[2]=" + x[2]);

}
}

next time i will post another sample program using array. using loop to print the array element.

Array in java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.

class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers

anArray = new int[10]; // allocates memory for 10 integers

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
System.out.println("Element at index 6: " + anArray[6]);
System.out.println("Element at index 7: " + anArray[7]);
System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
}
}

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000

In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. You'll learn about the various looping constructs (for, while, and do-while) in the Control Flow section.
Declaring a Variable to Refer to an Array
The above program declares anArray with the following line of code:

int[] anArray; // declares an array of integers

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array — it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the square brackets after the array's name:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable.

anArray = new int[10]; // create an array of integers

If this statement were missing, the compiler would print an error like the following, and compilation would fail:

ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.

Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Here the length of the array is determined by the number of values provided between { and }.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}

The output from this program is:

Mr. Smith
Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The code

System.out.println(anArray.length);

will print the array's size to standard output.
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:

class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

The output from this program is:

caffein


next time i will post another exam program using java.

Wednesday, September 1, 2010

While Loop get even numbers

hello programmers.... i want to share to you how to create a program that get the even numbers using modulo operator and while loop.

here is the program:

import java.util.Scanner;

public class evennumbers
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int num;
int x=1;
System.out.print("How many numbers you want to print:");
num=input.nextInt();

while(x<=num)
{
if(x%2==0)
{
System.out.println(x);
}
x++;
}

}
}

Tuesday, August 31, 2010

Choose operators using if statement

hello programmers... this program will show to you how to use if statement. It is for computing two input numbers by the user. this is for asking the user to choose the operator they want to execute. 1- addition, 2- subtraction, 3- Multiplication, 4- Quotient. this is a very simple program using nested if statement.


here is a sample program:

import java.io.*;
import java.util.Scanner;

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

Scanner input==new Scanner(System.in);
int add=1;
int sub=2;
int mult=3;
int div=4;
int num1;
int num2;
int oper;
int sum=0,diff=0,prod=0,quo=0;
System.out.println("1- Addition");
System.out.println("2- Subtraction");
System.out.println("3- Multiplication");
System.println("4- Division");

System.out.print("Enter First Number:");
num1=input.nextInt();

System.out.print("Enter Second Number:");
num2=input.nextInt();


System.out.print("Chooose Operators:");
oper=input.nextInt();


if(oper==add)
{
sum=num1+num2;
System.out.println("The sum is:" + sum);
}


if(oper==sub)
{
diff=num1-num2;
System.out.println("The difference is:" +diff);
}



if(oper==mult)
{
prod=num1*num2;
System.out.println("The Product is:" + prod);
}



if(oper==div)
{
quo=num1/num2;
System.out.println("The quotient is:" + quo);
}
}
}

Wednesday, August 4, 2010

Sample Program using while statement

this program will ask the user to input how many grades you want to compute
and get the average and check if Passed or Failed.

import java.util.Scanner;

public class Grades
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int num;
int grd;
int start=1;
int sum=0;
int ave=0;

System.out.print("How many Grades you want to compute:");
num=input.nextInt();

while(start<=num) { System.out.print("Grade" + start + ":"); grd=inout.nextInt(); sum=sum+grd; ave=sum/num; } System.out.print("The average is:" + ave); if(ave>=75)
{
System.out.println("Remarks: Passed");
}
else
{
System.out.print("Remarks: Failed");
}

}
}

Tuesday, August 3, 2010

File Streams


There are four types of streams: InputStream, OutputStream, Reader, and Writer.
1.        Reader. A stream to read characters.
2.        Writer. A stream to write characters.
3.        InputStream. A stream to read binary data.
4.        OutputStream. A stream to write binary data.
1. Reading Binary Data
You use an InputStream to read binary data.
InputStream
  |
  +-- FileInputStream 
  |
  +-- BufferedInputStream
1.        FileInputStream enables easy reading from a file.
2.        BufferedInputStream provides data buffering that improves performance.
3.        The ObjectInputStream class is used in object serialization.

2. Writing Binary Data
The OutputStream abstract class represents a stream for writing binary data
OutputStream
  |
  +--FileOutputStream
  |
  +--BufferedOutputStream. 
  |
  +--ObjectOutputStream
1.        FileOutputStream provides a convenient way to write to a file.
2.        BufferedOutputStream provides better performance.
3.        ObjectOutputStream class plays an important role in object serialization.
 3. OutputStream
The OutputStream class defines three write method overloads, which are mirrors of the read method overloads in InputStream:
1.        The first overload writes the lowest 8 bits of the integer b to this OutputStream.
2.        The second writes the content of a byte array to this OutputStream.
3.        The third overload writes length bytes of the data starting at offset offset.
     close() method closes the OutputStream.
      flush() method forces any buffered content to be written out to the sink.
S

while statement program

Problem: Create program that ask the user to input "How many hello world you want to print" and the output show number and hello world.

import java.util.Scanner;

public class helloworld
{
public static void main(String args[])
{
    Scanner input=new Scanner(System.in);
    int num;
    int start=1;
  System.out.print("How hello world you want to display");
  num=input.nextInt();

  while(start<= num)
  {
     System.out.println(start + ".Hello");
    start++;
  }

}
}