Search Java Programs

Wednesday, February 10, 2010

How to initialize an Array and how to copy the array

In this tutorial we are going to see how to initialize an Array and how to copy the array. Java has several types to initialize an array now we are going to see some types to initializing.

//Array initialization
public class Init1
{
public static void main(String[] args)
{
Integer[] value1 = { new Integer(1), new Integer(2), new Integer(3), };
Integer[] value2 = new Integer[] { new Integer(1), new Integer(2),new Integer(3), };
}
}


//Array Initializers
public class Init2
{
public static void main(String[] args)
{
int[] values = { 2, 7, 9 };
System.out.println("values.length = " + values.length);
for (int i = 0; i < values.length; i++) {
System.out.println("values[" + i + "] = " + values[i]);
}
String[] Weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday","Saturday" };
System.out.println("\nWeekdays.length = " + Weekdays.length);
for (int i = 0; i < Weekdays.length; i++) {
System.out.println("Weekdays[" + i + "] = " + Weekdays[i]);
}
}
}

public class CopyEx
{
public static void main(String[] args)
{
char[] firstchar = { 'a', 'e', 'w', 'e', 'l', 'c', 'o', 'm', 'e', 'a',
'l', 'l', 'o' };
char[] secondchar = new char[10];

System.arraycopy(firstchar, 2, secondchar, 0, 10);
System.out.println(new String(secondchar));
}
}

/*output:
welcomeall*/

Type Casting in Java

In this tutorial we are going to see how to typecast in java. Now we are going to see the syntax and sample code to convert each and every data type into other type.
//Integer code1
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=Integer.parseInt(s);
System.out.println(i);
Float f=99.7f;
int i1=Integer.parseInt(f);
}
}

//Integer code2
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=(int)s;
System.out.println(i);
}
}


//Integer to String
int a=97;
String s=Integer.toString(a);

(or)
String s=””+a;


//Double to String
String s=Double.toString(doublevalue);

//Long to String
String s=Long.toString(longvalue);

//Float to String
String s=Float.toString(floatvalue);

//String to Integer
String s=”7”;
int i=Integer.valueOf(s).intValue();

(or)
int i = Integer.parseInt(s);

//String to Double
double a=Double.valueOf(s).doubleValue();

//String to Long
long lng=Long.valueOf(s).longValue();

(or)
long lng=Long.parseLong(s);

//String to Float
float f=Float.valueOf(s).floatValue();

//Character to Integer
char c=’9’;
int i=(char)c;

//String to Character
String s=”welcome”;
char c=(char)s;

inheritance in Java

In this tutorial we are going to see how to inherit a class. For that we simply incorporate the definition of one class into another class by using extends keyword. Now we create a superclass named parent and a subclass named child. This program displays the parent class contents, child class contents and sum of the contents.
class parent
{
int pi,pj;
void showpipj()
{
System.out.println("pi and pj:"+pi+" "+pj);
}
}

class child extends parent
{
int pk;
void showpk()
{
System.out.println("pk:"+pk);
}
void sum()
{
System.out.println("pi+pj+pk:"+(pi+pj+pk));
}
}

class InheritExample
{
public static void main(String arg[])
{
parent p=new parent();
child c=new child();
p.pi=2;
p.pj=7;
System.out.println("contents of parent class");
p.showpipj();
System.out.println();
c.pi=18;
c.pj=27;
c.pk=9;
System.out.println("contents of child class");
c.showpipj();
c.showpk();
System.out.println();
System.out.println("sum of pi,pj,pk in child");
c.sum();
}
}
output:
contents of parent class
pi and pj:2 7
contents of child class
pi and pj:18 27
pk:9
sum of pi,pj,pk in child
pi+pj+pk:54

cloneable in Java

In this tutorial we are going to see use of cloneable interface and how to use it. The cloneable interface defines no members. It is used to indicate that a class allows a bitwise copy of an object to be made. If you try to call clone() on a class that does not implement Cloneable, a CloneNotSupportedException is thrown. When a clone is made the constructor for the object being cloned is not called. A clone is a copy of the original.

class Customer implements Cloneable 
{
String name;
int income;
public Customer(String name, int income)
{
this.name = name;
this.income = income;
}

public Customer()
{
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public void setIncome(int income)
{
this.income = income;
}

public int getIncome()
{
return this.income;
}

public Object clone() throws CloneNotSupportedException
{
try
{
return super.clone();
}
catch (CloneNotSupportedException cnse)
{
System.out.println("CloneNotSupportedException thrown " + cnse);
throw new CloneNotSupportedException();
}
}
}

public class MainClass
{
public static void main(String[] args)
{
try
{
Customer c= new Customer("Angel", 9000);
System.out.println(c);
System.out.println("The Customer name is " + c.getName());
System.out.println("The Customer pay is " + c.getIncome());

Customer cClone = (Customer) c.clone();
System.out.println(cClone);
System.out.println("The clone's name is " + cClone.getName());
System.out.println("The clones's pay is " + cClone.getIncome());

}
catch (CloneNotSupportedException cnse)
{
System.out.println("Clone not supported");
}
}
}

Java program for Associate keys with values

In this tutorial we are going to see how to associate keys with values. Here we are going to see how to create own methods for mapping the keys with values and how to get the value using Key.
public class AssociateExample
{

private Object[][] o;

private int in;

public AssociateExample(int length)
{
o = new Object[length][2];
}

public void put(Object key, Object value)
{
if (in >= o.length)
throw new ArrayIndexOutOfBoundsException();
o[in++] = new Object[] { key, value };
}

public Object get(Object key)
{
for (int i = 0; i < in; i++)
if (key.equals(o[i][0]))
return o[i][1];
throw new RuntimeException("Failed to find key");
}

public String toString()
{
String result = "";
for (int i = 0; i < in; i++)
{
result += o[i][0] + " : " + o[i][1];
if (i < in - 1)
result += "\n";
}
return result;
}

public static void main(String[] args)
{
AssociateExample connect = new AssociateExample(6);
connect.put("education", "business");
connect.put("globe", "warm");
connect.put("people", "refugees");
connect.put("politician", "god");
connect.put("god", "gone");
connect.put("water", "gold");
try
{
connect.put("extra", "object");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Can't put new objects!..");
}
System.out.println(connect);
System.out.println(connect.get("god"));

}
}

Output:

Can't put new objects!..
education : business
globe : warm
people : refugees
politician : god
god : gone
water : gold
gone

FileWriter in Java

FileWriter creates a Writer that you can use to write to a file. Its most commonly used constructors are shown here:

FileWriter(String filePath)
FileWriter(String filePath, boolean append)


FileWriter(File fileObj)

They can throw an IOException or a SecurityException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file.

Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.

The following example is a character stream version of an example shown earlier when FileOutputStream was discussed. This version creates a sample buffer of characters by first making a String and then using the getChars( ) method to extract the character array equivalent. It then creates three files. The first, file1.txt, will contain every other character from the sample. The second, file2.txt, will contain the entire set of characters. Finally, the third, file3.txt, will contain only the last quarter.





// Demonstrate FileWriter.
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\\n"
+ " to come to the aid of their country\\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.lengthbuffer.
length/4,buffer.length/4);
f2.close();
}
}

FileReader in Java

The FileReader class creates a Reader that you can use to read the contents of a file. Its two most commonly used constructors are shown here:

FileReader(String filePath)
FileReader(File fileObj)

Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.

The following example shows how to read lines from a file and print these to the standard output stream. It reads its own source file, which must be in the current directory.

// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}

Byte Array Output Stream in Java - ByteArrayOutputStream

ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the destination. ByteArrayOutputStream has two constructors, shown here:

ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)

In the first form, a buffer of 32 bytes is created. In the second, a buffer is created with a size equal to that specified by numBytes. The buffer is held in the protected buf field of ByteArrayOutputStream. The buffer size will be increased automatically, if needed. The number of bytes held by the buffer is contained in the protected count field of ByteArrayOutputStream.

The following example demonstrates ByteArrayOutputStream:




// Demonstrate ByteArrayOutputStream.
import java.io.*;
class ByteArrayOutputStreamDemo {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = s.getBytes();
f.write(buf);
System.out.println("Buffer as a string");
System.out.println(f.toString());
System.out.println("Into array");
byte b[] = f.toByteArray();
for (int i=0; i<b.length; i++) {
System.out.print((char) b[i]);
}
System.out.println("\\nTo an OutputStream()");
OutputStream f2 = new FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}

When you run the program, you will create the following output. Notice how after the call to reset(), the three X's end up at the beginning.

Buffer as a string
This should end up in the array
Into array
This should end up in the array
To an OutputStream()
Doing a reset
XXX

This example uses the writeTo() convenience method to write the contents of f to test.txt. Examining the contents of the test.txt file created in the preceding example shows the result we expected:

This should end up in the array

ByteArrayOutputStream

ByteArrayInputStream

ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source. This class has two constructors, each of which requires a byte array to provide the data source:

ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)

Here, array is the input source. The second constructor creates an InputStream from a subset of your byte array that begins with the character at the index specified by start and is numBytes long.

The following example creates a pair of ByteArrayInputStreams, initializing them with the byte representation of the alphabet:




// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b,
0,3);
}
}

The input1 object contains the entire lowercase alphabet, while input2 contains only the first three letters.

A ByteArrayInputStream implements both mark() and reset(). However, if mark() has not been called, then reset() sets the stream pointer to the start of the stream-which in this case is the start of the byte array passed to the constructor. The next example shows how to use the reset() method to read the same input twice. In this case, we read and print the letters "abc" once in lowercase and then again in uppercase.



import java.io.*;
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
}
}


This example first reads each character from the stream and prints it as is, in lowercase. It then resets the stream and begins reading again, this time converting each character to uppercase before printing. Here's the output:

abc
ABC

Website Design by Mayuri Multimedia