Sunday, 20 May 2012

Overriding Methods in Java – Basic Rules

 

What is Overriding  ?

When a class inherits a certain method from its parent class or superclass , that method can be overridden , unless it is marked final , private or static.

Basically overriding is done to make the method inherited , more class specific.

E.g.

Capture

Rules for overriding ~

  • The return type and the argument of the method defined in the super class should be same in the subclass (can be seen in the above example).
  • Private methods are not inherited , hence cannot be overridden.
  • Methods marked Final cannot be overridden. Had it been the case the keyword final would have lost it’s significance.
  • Static methods cannot be overridden they are hidden.

Consider the following Example:

Capture

The Output is :

Has Brakes

Has Disc Brakes

if we define main method as

Capture

The output is :

Has Brakes

Has Brakes

The following table summarizes what happens when you define a method with the same signature as a method in a superclass

Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
  • While overriding we can only release the level of access of the method specified in the superclass or keep it the same. We CANNOT restrict the method further.

E.g.

If there is a protected method defined in the superclass and is inherited and is tried to be overridden with an access specifier less restricted than protected i.e. Private , then it will give a ERROR ! If it is overridden as a Public method or a Protected method it runs SUCCESSFULLY.

REMEMBER : Level of restriction ~

public < protected < default < private

Thursday, 17 May 2012

Studying Useful Class's Methods




Where to Find Useful Java Classes ?

In Windows there is a .zip file named "src.zip" located usually at the address

C:\Program Files\Java\jdk1.7.0_03

What Next ?

Now extract the file in a folder . It is recommended to copy this .zip file and then extract it in a new folder .

Open the location of that class in the extracted folder and copy it to a new folder.

Use javadoc tool (discussed in the previous blog->http://1-armed-blog.blogspot.in/2012/05/how-to-know-about-methods-in-class.html ) to generate an index.html file of the Class.

After extracting the src.zip file the src folder :











Studying the index.html file helps us know the methods defined in the class well .




















Saturday, 12 May 2012

How to know about methods in a Class

Using Javap and Javadoc

This blog illustrates the use of 2 tools of Java : javap and javadoc
Java has a set of Tools which can be used to display the methods defined in a Class. These tools can be used to find out which methods have been defined in the class without reading the code.
These tools can be used to make a documentation about user defined Class or default classes which are defined in the jdk.

There are two tools discussed:
1. javap - the Java Class File Disassembler
             The javap command disassembles a class file. javap prints out the package, protected, and public fields and methods of the classes passed to it.
2. javadoc
            Javadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, interfaces, constructors, methods, and fields.

The following will illustrate the use of javap and javadoc for Windows.

javap

As discussed above , javap just gives the name of the methods of the class file.
Its a simple process.


-Reach the Directory where the .class file is located , of which the methods have to be    found out by using cmd-prompt of windows and
type-

 javap<space>NameOfClass

Following figures shows the cmd when we disassamble the StringBuffer.class file :




















Observe that all the methods with there parameter's data type have been displayed in the cmd-prompt.


JAVADOC

This is a lovely tool ! The Javadoc tool parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields. You can use it to generate the API (Application Programming Interface) documentation or the implementation documentation for a set of source files.
If you want to learn about the methods of a class which has many confusing methods which you cannot remember , like the String class , make HTML pages describing its methods , sorts out the methods according to your need , ready for you to study and use them.

It includes very simple steps:
1. The .java file , of which the methods have to be found , is copied into a separate folder.
2. Reaching that folder using cmd-prompt and typing:

"javadoc<space>NameOfJavaFile.java"

yields a series of commands.


4. cmd-prompt will generate several lines of commands by itself.
5. Opening the folder where the .java file was put shows lots of HTML pages. The file "index.html" will have all your your methods listed with description !

Following pictures show the use of javadoc on StringBuffer class which have been copied to a folder named "StringBuffer" :
















The folder in which the .java file has been copied to looks like : 


















Clicking on the "index" file gives* :



















For more on javadoc visit->http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html


So these 2 tools are very handy and very important if a particular class and its methods are to be studied.
*Note : index page might look different for different versions of jdk. Here jdk 1.6 has been used.

Friday, 11 May 2012

Multiplying Large Numbers in JAVA without using BigInteger Class



I am practicing programs in java these days on the Website  http://www.javaladders.com. They have a 3-Stared problem called Multiplying Large Numbers. I found it pretty interesting.
The objective of this exercise is two multiply any 2 numbers. The numbers can be extremely large (i.e. run into hundreds of digits) and are provided as strings. 
You are not supposed to use the Java class Biginteger.
The expected output is a string which represents the product of the two numbers.
 In the following code I have used basic Java functions for doing operations on Strings.

Here is the code for the problem. You can enter any large numbers. 

Program:

  
import java.util.Scanner;
    public class LargeMultiply {
    // main method
    public static void main(String args[]) {
    System.out.println("\n\t \t WELCOME TO OneArmed Blog !!! \n");
    System.out.println("\t \t Multiplying 2 Large Numbers \n");
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter 1st Number:"); //input first number
    String inputA = sc.next(); // taking string input
    System.out.println("Enter 2nd Number:"); //input second number
    String inputB = sc.next(); // taking string input
    LargeMultiply inst = new LargeMultiply();
                //Object creation of class LargeMultiply
    String v = inst.multiply(inputA, inputB); 
 // calling method multiply()
    System.out.println("RESULT:");
    System.out.println(v); // Output result
    }
    /*-- multiply method , return type String ,
 2 String parameters---- */
    public String multiply(String num1, String num2) {
    String[] str1 = num1.split("");
  //Split the number string into array with each element
 //   containing single digit
    String[] str2 = num2.split("");
    int m1 = 0;
    int m2 = 0;
    String[] resultStringArray = new String[str2.length];
    //Initializing the resultString array which has input 
 // string2 in Array form with each element
    //in different Index
    LargeMultiply inst1 = new LargeMultiply();
  //multiply every element of String2 with the String1
 //  using multiplySmall() method
    for (int j = str2.length - 1; j > 0; j--)
    resultStringArray[j] = inst1.multiplySmall(num1, str2[j]);
              // call to multiplySmall() method
    for (int i = num2.length() - 1; i > 0; i--) {
    for (int j = 1; j <= i; j++) {
    resultStringArray[j] = resultStringArray[j].concat("0");
 //concat number of zeroes which are equal to the number of
 //digits in 2nd number
    }
    }
    String finalResult = "0"; // Initialize output String
    for (int j = str2.length - 1; j > 0; j--) {
    finalResult = inst1.add(finalResult, resultStringArray[j]);
                      //call to adding large numbers method
    }
    return finalResult;  //return result
    }
 /*----Method to multiply a single digit to large digits----- */
    public String multiplySmall(String large, String small) {
    int smallInt = Integer.parseInt(small);
 //String to int conversion
    String[] s = large.split("");
    String[] largeStringArray = new String[s.length - 1];
                     //Initiate a String array
    //as discussed earlier split function makes
  //an array which has first element “” empty
    //so in order to remove that element 
 //we have to make another array,here it is
    //largeStringArray
    for (int i = 0; i < largeStringArray.length; i++) {
    largeStringArray[i] = s[i + 1];
    }
     
    int[] largeInt = new int[largeStringArray.length];
     //make a integer array for num1 which is considered large
    for (int i = 0; i < largeStringArray.length; i++) {
    largeInt[i] = Integer.parseInt(largeStringArray[i]);
      //String to int conversion of every element
    }
             //Logic for carry
    int carry = 0;
    String[] resultCarry = new String[2];
      //carry number represented by 2 element String array
    String result = "";// result to be stored in string form
    int resultInt = 0;//carry in form of integer
    //int count = 0;
    for (int i = largeStringArray.length - 1; i >= 0; i--) {
    resultInt = largeInt[i] * smallInt + carry;
 //multiplying every element of the largeInt
 //  with single digit integer
    carry = 0;//after every multiplication carry to be made zero
    if (i == 0) { // if no carry
    resultInt = resultInt;   // no change
    } else { // If carry then
    if (resultInt / 10 > 0) {
       //if output on multiplying is of 2 digits
    String s2 = Integer.toString(resultInt);
    //convert int to String
    String[] s3 = s2.split("");
 // Split the Result on basis of every digit
    carry = Integer.parseInt(s3[1]);
           //make the first digit stored on index 1, carry
    resultInt = resultInt % 10;
       //keep the unit place digit of the carry 
    //result which is concated later
    }
    }
    result = Integer.toString(resultInt).concat(result);
   //convert unit place of result to String and concat
 //   it with previous results
    }
    return result;
    //return result, which is multiplication of single
 // digit number of num2 to the whole num1
    }
   /*----------Method to add 2 large numbers-------- */
    public String add(String num1, String num2) {
    char[] tempChar1 = num1.toCharArray();
    //converting String num1 to character Array using
 //  toCharArray() function
    char[] tempChar2 = num2.toCharArray();
    //converting String num2 to character Array
  //using toCharArray() function
    char[] ch2;
    char[] ch1;
    //condition to check which number is longer
    if (tempChar1.length > tempChar2.length) { // if 1st is larger
    ch2 = tempChar1; // assign ch2 to num1
    ch1 = tempChar2; // assign ch1 to num2
    } else { //if second is larger
    ch2 = tempChar2;// assign ch2 to num2
    ch1 = tempChar1;// assign ch1 to num1
    } // so always the small number gets stored in ch1
    String ans = ""; //Initiating Result String, ans
    int tempAns = 0;
    int carry = 0;
    int smallerStringIndex;
    char smallerStringNumber;
    smallerStringIndex = ch1.length - 1;
    //represents index for smaller number
    for (int i = ch2.length - 1; i >= 0; i--) {
    //if index becomes negative add '0'
 // at the start of smaller digit, will have no effect
    if (smallerStringIndex < 0) {
    smallerStringNumber = '0';
    } else {
    smallerStringNumber = ch1[smallerStringIndex];
    }
    tempAns = (smallerStringNumber + ch2[i] - 96 + carry);
    // -96 the ASCII value gives actual value of the char in int
    if (tempAns >= 10) {
    //if there is a carry
    tempAns = tempAns - 10;
    //tempAns now contains the unit digit after addition
    ans = tempAns + ans;
    carry = 1; //assign 1 to carry
    } else {
    ans = tempAns + ans; //case of no carry
    carry = 0;
    }
    smallerStringIndex--; //reduce index by 1
    }
    if (carry == 1) {
    ans = "1" + ans;
    //adding String "1" to final result if at the 
 //end the last digits add up to give a carry
    }
    return ans; //return result in String
    }
    }

OUTPUT SCREEN :



Shaurya Rohatgi