Archive for October, 2013


Polymorphism…

POLYMORPHISM

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Example:

Let us look at an example.

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:

  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal:

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.

Virtual Methods:

In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

/* File name : Employee.java */
public class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
  {
      address = newAddress;
  }
  public int getNumber()
  {
     return number;
  }
}

Now suppose we extend Employee class as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
  {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Now you study the following program carefully and try to determine its output:

/* File name : VirtualDemo.java */
public class VirtualDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta,  UP",
                                 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA",
                                 2, 2400.00);
      System.out.println("Call mailCheck using 
                                   Salary reference --");
      s.mailCheck();
      System.out.println("\n Call mailCheck using 
                                   Employee reference--");
      e.mailCheck();
    }
}

This would produce following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here we instantiate two Salary objects . one using a Salary reference s, and the other using an Employee reference e.

While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler seese.mailCheck(), the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

CODE

package polymorphism;

/**
*
* @author aprimit
*/
public class BaseClass {

public String base = “BaseClass”;

public BaseClass() {
}
}


package polymorphism;

/**
*
* @author aprimit
*/
public class DeriveClass extends BaseClass {

public String derive = “DeriveClass”;

public DeriveClass() {
}
}


/**
*
* @author aprimit
*/
public class Polymorphism {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
BaseClass b = new DeriveClass();
/*
* base class reference storing derive class object
* superType – subType relation
*/
System.out.println(b.base);

DeriveClass d = (DeriveClass)b;
/*
* casting origional object back into its form
*/
System.out.println(d.derive);
}
}

OUTPUT : BaseClass

Derive Class

Inheritance…

INHERITANCE

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}

Now based on the above example, In Object Oriented terms following are true:

  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are sub classes of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say:

  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:

public class Dog extends Mammal{
   public static void main(String args[]){

      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

This would produce following result:

true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.

Example:

public interface Animal {}

public class Mammal implements Animal{
}

public class Dog extends Mammal{
}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal

interface Animal{}

class Mammal implements Animal{}

class Dog extends Mammal{
   public static void main(String args[]){

      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

This would produce following result:

true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:

public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
	private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. SO basically what happens is the users would ask the Van class to do a certain action and the Vann class will either do the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance

Lets CODE

package Inheritance; 

/**
*
* @author apriimit
*/
public class Area {
private int length;
private int breadth;

public Area()//Constructor called…
{
length=5;
breadth=4;

}
public int getArea()
{
return length*breadth;
}
}


package Inheritance;

/**
*
* @author aprimit
*/
public class Volume extends Area {
protected int height;
public Volume()
{
height=6;
}
public int getVolume()
{
return super.getArea()*height;/*
length,breadth are private,hence can not
access here directly…super refers to the imme-
* diate parent class
*/
}
public static void main(String[] args)
{
Area a=new Area();
Volume v=new Volume();
System.out.println(“This program illustrates the concept of Single Inheritance”);

System.out.println(“Area is: ” + a.getArea());
System.out.println(“Volume is:” +v.getVolume());
}

}

OUTPUT :This program illustrates the concept of Single Inheritance

Area is:20

Volume is:120

JAVA Strings continued…

Take this example of a String Function which converts the lower case alphabets to upper case.

package Strings;

/**
*his
* @author aprimit
*/
public class String_function {

public static void main(String[] args) {
System.out.println(“This program sets the name with proper CASE…”);
String name = “aPRimit gARG”;

int l = name.length(), s = 0, i;
System.out.println(“The length of the string is :” + l);

s = name.indexOf(” “);
System.out.print(“The space is at :” + s);
System.out.println();

String first = name.substring(0, s);
String second = name.substring(s + 1);
first = first.toLowerCase();
second = second.toLowerCase();
first = String.valueOf(first.charAt(0)).toUpperCase() + first.substring(1);
second = String.valueOf(second.charAt(0)).toUpperCase() + second.substring(1);
System.out.println(String.format(“%s %s”, first, second));
}
}

OUTPUT : This program sets the name with proper CASE…

The length of the string is :12

The space is at :7

APRIMIT GARG

JAVA Strings…

STRINGS.

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:

The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its valuein this case, “Hello world!’.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

public class StringDemo{
   public static void main(String args[]){
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}

This would produce following result:

hello

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then you should use String Buffer & String BuilderClasses.

String Length:

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo{
   public static void main(String args[]){
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

This would produce following result:

String Length is : 17

Concatenating Strings:

The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

which results in:

"Hello, world!"

Let us look at the followinge example:

public class StringDemo{
   public static void main(String args[]){
      String string1 = "saw I was ";
      System.out.println("Dot " + string1 + "Tod");
   }
}

This would produce following result:

Dot saw I was Tod

Creating Format Strings:

You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of:

System.out.printf("The value of the float variable is " +
                  "%f, while the value of the integer " +
                  "variable is %d, and the string " +
                  "is %s", floatVar, intVar, stringVar);

you can write:

String fs;
fs = String.format("The value of the float variable is " +
                   "%f, while the value of the integer " +
                   "variable is %d, and the string " +
                   "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Methods:

Here is the list methods supported by String class:

SN Methods with Description
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o) 
Compares this String to another Object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb) 
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
7 static String copyValueOf(char[] data) 
Returns a String that represents the character sequence in the array specified.
8 static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
10 boolean equals(Object anObject)
Compares this string to the specified object.
11 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12 byte getBytes()
Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
13 byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15 int hashCode()
Returns a hash code for this string.
16 int indexOf(int ch) 
Returns the index within this string of the first occurrence of the specified character.
17 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
18 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
20 String intern()
Returns a canonical representation for the string object.
21 int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
23 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
24 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
25 int length()
Returns the length of this string.
26 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
31 String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
32 String[] split(String regex)
Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex)
Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
39 char[] toCharArray()
Converts this string to a new character array.
40 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42 String toString()
This object (which is already a string!) is itself returned.
43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44 String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.

File Handling (Part-2)…

Let us handle some files….

Firstly,we will copy data from one file to another :

package FileHandling;

/**
*
* @author aprimit
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(“This program copies content from one file to another”);
String src = “/home/aprimit/Desktop/J2SE/new file”;
String des = “/home/aprimit/Desktop/J2SE/new file1”;
try {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(des);

int copy;
System.out.println(“The content is being copied: “);
while ((copy = fis.read()) != -1) {
fos.write(copy);
}
} finally {
fis.close();
fos.close();

}
} catch (IOException e) {
System.out.println(“Exception has been handled: ” + e);

}

System.out.println(“Done”);
}
}

OUTPUT : This program copies content from one file to another

The content is being copied:

Done

Continue reading

File Handling (Part-1)…

Files & Input/Output

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic functionlity related to streams and I/O. We would see most commonly used example one by one:

Reading Console Input:

Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. Here is most common syntax to obtain BufferedReader:

BufferedReader br = new BufferedReader(new 
                      InputStreamReader(System.in));

Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.

Reading Characters from Console:

To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:

int read( ) throws IOException

Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException.

The following program demonstrates read( ) by reading characters from the console until the user types a “q”:

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new 
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // read characters
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

Here is a sample run:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q

Reading Strings from Console:

To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

The following program demonstrates BufferedReader and the readLine( ) method. The program reads and displays lines of text until you enter the word “end”:

// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}

Here is a sample run:

Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

Writing Console Output:

Console output is most easily accomplished with print( ) and println( ), described earlier. These methods are defined by the class PrintStream which is the type of the object referenced by System.out. Even though System.out is a byte stream, using it for simple program output is still acceptable.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:

void write(int byteval)

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written.

Example:

Here is a short example that uses write( ) to output the character “A” followed by a newline to the screen:

import java.io.*;

// Demonstrate System.out.write().
class WriteDemo {
   public static void main(String args[]) {
      int b; 
      b = 'A';
      System.out.write(b);
      System.out.write('\n');
   }
}

This would produce simply ‘A’ character on the output screen.

A

Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier to use.

Reading and Writing Files:

As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

Java I/O StreamsThe two important streams are FileInputStream and FileOutputStream which would be discussed in this tutorial:

FileInputStream:

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file.:

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows:

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it’s end of file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned.
5 public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links:

FileOutputStream:

FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn’t already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file.:

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First we create a file object using File() method as follows:

File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to stream or to do other operations on the stream.

SN Methods with Description
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.
3 public void write(int w)throws IOException{}
This methods writes the specified byte to the output stream.
4 public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following links:

Example:

Following is the example to demonstrate InputStream and OutputStream:

import java.io.*;

public class fileStreamTest{

   public static void main(String args[]){

   try{
      byte bWrite [] = {11,21,3,40,5};
      OutputStream os = new FileOutputStream("C:/test.txt");
      for(int x=0; x < bWrite.length ; x++){
         os.write( bWrite[x] ); // writes the bytes
      }
      os.close();

      InputStream is = new FileInputStream("C:/test.txt");
      int size = is.available();

      for(int i=0; i< size; i++){
         System.out.print((char)is.read() + "  ");
      }
      is.close();
   }catch(IOException e){
      System.out.print("Exception");
   }	
   }
}

The above code would create file test.txt and would write given numbers in binary format. Same would be output on the stdout screen.

File Navigation and I/O:

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.

Directories in Java:

Creating Directories:

There are two useful File utility methods which can be used to create directories:

  • The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
  • The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates “/tmp/user/java/bin” directory:

import java.io.File;

class CreateDir {
   public static void main(String args[]) {
      String dirname = "/tmp/user/java/bin";
      File d = new File(dirname);
      // Create directory now.
      d.mkdirs();
  }
}

Compile and execute above code to create “/tmp/user/java/bin”.

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Reading Directories:

A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory( ) method will return true.

You can call list( ) on that object to extract the list of other files and directories inside. The program shown here illustrates how to use list( ) to examine the contents of a directory:

import java.io.File;

class DirList {
   public static void main(String args[]) {
      String dirname = "/java";
      File f1 = new File(dirname);
      if (f1.isDirectory()) {
         System.out.println( "Directory of " + dirname);
         String s[] = f1.list();
         for (int i=0; i < s.length; i++) {
            File f = new File(dirname + "/" + s[i]);
            if (f.isDirectory()) {
               System.out.println(s[i] + " is a directory");
            } else {
               System.out.println(s[i] + " is a file");
            }
         }
      } else {
         System.out.println(dirname + " is not a directory");
    }
  }
}

This would produce following result:

Directory of /mysql
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory

Day-42 …

Updating Net Beans IDE (7.1.2)

When i updated my operating system with ubuntu 12.04 LTS ,the first thing i installed was NETBEANS IDE.The Ubuntu Software Centre recommmended the NetBeans 7.0.1. IDE.

I started downloading various packages required for the IDE as required by any other software.It was simple and easy to implement  toy programs,but when i went for some advanced  e.g.Implementing Swings using GUI,the IDE with 7.0.1 version seemed to have had broken down.
On reopening of the Ubuntu Software Centre,i found reviews describing somewat the same problem.

Reviews:-

  • Unfit for distribution in its current state – Precise / 7.0.1

This is seriously broken.

hitting enter in a php file deletes the current line, and it says ‘please wait…’ at the top left of the editor forever. after undoing all changes it still insists that there are changes to be saved and closing without saving still results in it syncing the unchanged file to a remote server if that’s where you got it from. Saving includes about 20 FTP commands including attempting to delete FILENAME.old, renaming FILENAME.old to FILENAME, renaming FILENAME to FILENAME.old, renaming FILENAME.new to FILENAME, no in that order, not in a way which makes sense. The behaviour concerned me enough that I hit CTRL-BACKSPACE to kill X before it could do any amount of damage on my FTP server.

  • 7.0.1 is to faulty

Had to download and install 7.1.2 manually because visual swing editing didn’t work on Ubuntu 12.0.4. This edition was just a headache.

  • The Ubuntu build of netbeans is almost completley unseable.

I love netbeans itself but the Ubuntu 12.04 build is utterly broken. My first problem was that the menu is dark on dark background, which is annoying but just about useable.

I then installed the php addon, which installed fine but turned out to be utterly unuseable. When editing a source file, pressing the “enter” key did absolutley nothing other than display a “please wait” message in the status area. A lesser problem is that it marked html tags in red, even though they were correctly closed. I gave up at that point and installed the latest version of netbeans from the website.

In short you should download netbeans from the official website, not from Ubuntu

Installing NetBeans 7.1.2

Finally,downloaded NetBeans IDE 7.1.2 from its official website i.e. www.netbeans.org/.The downloaded file was of about 166MB,but the noticable thing was its extension.The IDE file was a ‘.sh‘ file.Now the next challenge for me was to install it.
Then i tried Googling it so as to  install the latest version on my system.Some sites asked me to change the mode of the file using ‘chmod‘ command in the terminal.

Unfortunately,i was unable to change its mode although i tried my best.

Exploring through various links brought me to an alternative to install that ‘.sh‘ file.

  • Go to the terminal
  • Change the directory,the directory where the file is located.
  •  Write ” sudo sh ./filename.sh
  • Hit ENTER


The file got installed..!!

Arrays continued…

Lets have a look at the following toy program which accepts age from the user and finds their mean.Additionally,it also finds out how many people are above,below and at par the mean age

package Array;

/**
*
* @author aprimit
*/

import java.util.Scanner;

public class acceptAge_mean {

public static void main(String[] args) {
System.out.println(“This program is to accept age and find mean….”);

Scanner number = new Scanner(System.in);
System.out.print(“Input the number of students…”);
int n = number.nextInt();

int sum = 0, i;
int age[] = new int[n];
for (i = 0; i < n; i++) {
System.out.print(“Enter the age of student [” + (i + 1) + “]….”);
age[i] = number.nextInt();
sum = sum + age[i];
}
float mean = (float) sum / n;
System.out.println (“Mean is”+ mean);
int a = 0, b = 0, c = 0;
for (i = 0; i < n; i++) {
if (age[i] > mean) {
a++;
} else if (age[i] < mean) {
b++;
} else {
c++;
}
}
System.out.println(“Above Mean: ” + a);
System.out.println(“Below Mean: ” + b);
System.out.println(“At Par Mean: ” + c);
}
}

OUTPUT: This program is to accept age and find mean….

Input the number of students…

5

Enter the age of student [” + (i + 1) + “]….

20

34

56

55

18

Mean is 36.6

Above Mean:2

Below Mean:3

At Par Mean:0

Arrays…

ARRAYS

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar;   // preferred way.

or

dataType arrayRefVar[];  //  works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList;         // preferred way.

or

double myList[];         //  works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

  • It creates an array using new dataType[arraySize];
  • It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 toarrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double type, and assigns its reference to myList.:

double[] myList = new double[10];

Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.

Java Array

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {
   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

This would produce following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {
   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

This would produce following result:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}

You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0; i = result.length - 1; 
                      i <  list.length; i++, j--) {
    result[j] = list[i];
  }
  result result;
}

The Arrays Class:

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

SN Methods with Description
1 public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2 public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
3 public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
4 public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)