Wednesday 26 March 2014

Paint Shapes - Paint With File-Handling

As promised, we are back with a whole new Paint Applet, this time using javax.swing and JFrame. If you havent seen our previous attempt at the Paint Brush Applet, you can view it here. The bugs that we encountered last time have been somewhat solved in this applet.

First of all, the output looks something like this:

As you can see, one can draw rectangle, round rectangle and ovals to their file. The applet provides facility to save their file, rename it, save it in a different location and to view saved files. 

You can view the actual source code here. We have tried our best to comment wherever necessary. Still, if you have any doubts or any kind of ambiguity, please feel free to leave a comment: 

BUGS AND HOW THEY ARE SOLVED:

Now we will show how the 3 bugs mentioned in Paint Brush Applet are solved.


  1. The shapes that are added do not now disappear when paint() is called again (implicitely and explicitely). This is because all shapes are stored in an ArrayList of the name "shapes". The paint function simply draws all the shapes in the list again, thus losing none!
  2.  File Handling concepts are used to store and open files. Note that the files thus created do not have any extensions like .jpg, etc. and are thus read by the Windows System as of the type "file". It cannot be rendered effectively by any application other than this applet. Results may/may not be different in Linux-based systems because of its "Everything is a file" policy.
  3.  The "drawing area" is defined separately and does not include the menu bar, thus solving this error.

Saturday 15 March 2014

Basic Calculator Applet


After about 1-2 days of work, I finally created a Java Applet of a simple binary calculator which performs binary operations on positive numbers. The main aim was to solve using this calculator an expression like:
32+45/89*6 = 5.19101

from left-to-right, step by step i.e. computing two variables at a time.(so you enter 32 + 45 = and the result (77) then becomes your first operand)
basic binary calculator using java.applet class

The idea was not to give a demonstration of the calculator algorithm, but to show the use of the applet class and the basic components like buttons, text fields, etc. Thus, this can be the ideal code for anyone who is planning to make a small project using java applet class. The functions and the overall view and flow of the code is deliberately made very simple so that even those who are not-so-experienced with applets can understand.
I encourage the readers to go through the code and mail/leave a comment if you have doubts, suggestions or if you made an improvised version of the code!


Thursday 13 March 2014

Addition Of Two Numbers Using Linked Lists


Another very frequently searched algorithm is to add two very long numbers (in the order of zillions) using Linked Lists.


IMPLEMENTATION:


We use the Linked List to implement such a logic. Here, we make use of the fact that “int” in java has the range -2^31 to 2^31 which is 10 digits long. Therefore, every node in the list can hold maximum upto 10 digits. If the number has more than 10 digits, the More Significant Digits are pushed in the previous node. Thus 2 Lists are created for 2 numbers and they are then added node-by-node. The carry, if generated is added to the next pair of nodes to get the proper answer.


As usual, we have used our own version of Linked List to make the addition, deletion, and searching nodes processes transparent.





The main Addition class which calls the above class is as follows:

NOTE: We have created the program keeping in mind only positive integers. Floating point numbers may/may not work in this program depending on the number!
NOTE: A more elegent solution will be to input the number from Most Significant Digits and keep pushing the nodes into a stack. Thus, we will have 2 stacks for 2 numbers. Now, all we need to do is add the node pointed by the top of each stack with each other and and keep pushing it into a "result" stack.

The Josephus Problem


Problem Statement:
A group of soldiers is surrounded by the enemy from all the sides. There is no hope of victory for them and they have only 1 horse. In order to choose which soldier amongst them gets the chance to get on the horse and escape/call for reinforcements, they devise a method. The soldiers are arranged in a circle. A number n is picked up at random from a chit-box. Then a name is also picked up at random from another box. Starting from the soldier whose name came from the box, they count clockwise till n. When the count reaches n, that soldier is removed from the circle and is no longer counted. The counting then starts again from the next soldier. This is done continuously till only one soldier remains and that soldier is allowed to escape on the horse.
Implementation:
We use a Circular Linked List to solve the problem, as the last node in a circular list is connected to the first, thus there is no node with next address null at any time. The list is traversed n times and when a soldier has to be removed, that particular node is deleted from the list. Eventually, the list will have only 1 node pointing to itself (it is still a circular list) and containing the name of the soldier that can escape.

Now, java.util already has Linked List functionalities, yet it seemed prudent to make the readers understand the inner functionalities of the list. Hence, a new class of Circular Linked List is made complete with add, delete, search functionalities.

The actual Josephus Class that calls this CircularLinkedList class is as follows:

An example of the output is as follows:

 Enter the names of the soldiers in clockwise order. Press '-' key when done. a
[a, labWorkDSA.CircularLinkedList@ec5aba9]
b
Node added
[a, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@ec5aba9]
c
Node added [a, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@423252d6][c, labWorkDSA.CircularLinkedList@ec5aba9]
d
Node added [a, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@423252d6][c, labWorkDSA.CircularLinkedList@5fbd8c6e][d, labWorkDSA.CircularLinkedList@ec5aba9]
e
Node added [a, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@423252d6][c, labWorkDSA.CircularLinkedList@5fbd8c6e][d, labWorkDSA.CircularLinkedList@154ebadd][e, labWorkDSA.CircularLinkedList@ec5aba9]
-
Pick up a chit from the number box. Enter the number
5
Pick up a chit from the name box. Enter the name
a
e deleted
[a, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@423252d6][c, labWorkDSA.CircularLinkedList@5fbd8c6e][d, labWorkDSA.CircularLinkedList@ec5aba9]
a deleted
[b, labWorkDSA.CircularLinkedList@423252d6][c, labWorkDSA.CircularLinkedList@5fbd8c6e][d, labWorkDSA.CircularLinkedList@5388ebd2]
c deleted
[d, labWorkDSA.CircularLinkedList@5388ebd2][b, labWorkDSA.CircularLinkedList@5fbd8c6e]
d deleted
[b, labWorkDSA.CircularLinkedList@5388ebd2]
The soldier that can escape on the horse is : b

The Story Behind "public static void main"


All the beginners in Java language are first taught the Hello World program, which although very simple looking, contains a lot of the functionality secrets of Java.
The first method that a new java programmer writes is the “main” method.
The entire Hello World program looks something like the following:
public class HelloWorld {
 public static void main(String[] args) {
  System.out.println("Hello World");
 }
}


The output, obviously is:
Hello World


Let us explore the main method and all its keywords one by one:
The first thing one should know that the execution of a java program starts from the main function. After loading the program, the Java Virtual Machine (JVM) scans the program to search for “public static void main (String[] args)”
Public: “public” is an access-specifier and it means that the method can be called from outside of the class. The main method has to public so that the JVM can call it and begin the program.
Static: “static” means that only one copy of the main function is shared between all objects of the class and one doesn’t have to initialize a class object to call the main method. (For more information on “static”, click here)
Void: “void” is a return type. It indicates that the main function does not return anything. This is quite logical, as the main function is called implicitly by the JVM and not by another function. So it has no function to return value to.
(String[] args): The entire phrase inside the parentheses are arguments passed to the main function. The argument type is an array of the type java.lang.string and the name of the array is “args”. Consider the following program:

public class HelloWorld {
 public static void main(String[] args) {
  System.out.println("Hello World"); 
    for (int i = 0; i < args.length; i++) {
  System.out.println(args[i]);
     }
   }
}



If you are operating from the command prompt/terminal, and you enter
       java HelloWorld I’m Batman

The output will be:

Hello World

I’m

Batman
If you type: java HelloWorld “I’m Batman”, the output is:
Hello World
I’m Batman
If you are using the Eclipse IDE, you can enter the “program arguments” from Run>Run Configurations>(x)= Arguments (That’s the second tab) and then enter your arguments.
Run Configurations In Eclipse.jpg

What does "static" mean in Java?


I have gone through many books of java but not many give sufficient explanation of what is the meaning of the keyword "static" in Java and when does one use it.


STATIC VARIABLES:


Making a variable static basically means that only one copy of the variable is shared between all the objects of the class. If one object changes the value of that variable, all the variables get the updated value.

Consider the following code snippet:
class StateOfACountry; 
 public String stateName;
 public String CM_name;
 public static String PM_name;
  
 public static void main(String []args){
  StateOfACountry state1 = new StateOfACountry();
  state1.CM_name = "CM1";
  state1.PM_name = "PM";
  System.out.println("State 1 CM name " + state1.CM_name);
  System.out.println("State 1 PM name " + state1.PM_name);
 
  StateOfACountry state2 = new StateOfACountry();
  System.out.println("State 2 CM name " + state2.CM_name);
  System.out.println("State 2 PM name " + state2.PM_name);
  
  state2.CM_name = "CM2";
  state2.PM_name = "PMabc";
  
  System.out.println("State 2 CM name " + state2.CM_name);
  System.out.println("State 2 PM name " + state2.PM_name);

  System.out.println("State 1 CM name " + state1.CM_name);
  System.out.println("State 1 PM name " + state1.PM_name);
  }
}
The output is:
State 1 CM name CM1
State 1 PM name PM
State 2 CM name null
State 2 PM name PM
State 2 CM name CM2
State 2 PM name PMabc
State 1 CM name CM1
State 1 PM name PMabc
In the above example, the variables stateName, CM_name are not static while the variable PM_Name is. This is correct logically because if there are many states in a country, the Chief Minister (CM) of one state may be different from another. However, all states will share the same Prime Minister (PM) name. Thus we see that, if there is a variable which is common amongst all the objects in the same class, we should treat it as static.

Now, consider a case of re-elections. If the CM of state1 is changed, it is not necessary that the CM of state2 be changed as well. However, if the PM of the country is changed, then the change is reflected on the PM of all the states! (which is correct logically).
Thus, we see that the static variables belongs to the class on a whole and not to a particular object of the class. In the above case, a Prime Minister (PM) belongs to a country on a whole, rather than the state of a country.
All such variables which are not tied to an object should be made static in your programs.
STATIC FUNCTIONS:
The definition of static extends to functions as well i.e. a copy of static function is shared between all the objects of the class. A function is made static when two static functions have nothing in common between them.
Also, there is an additional clause: Static functions can access and operate on only static variables. This, of course, is logical as static functions are something that belong to the class rather than an object, and therefore should operate only on variables that too belong to the class.
Accessing non-static variables in static functions causes an error (try it!)
Consider the above example, now modified:
class StateOfACountry{
   public String stateName;
   public String CM_name;
   public static String PM_name;
           
   public static void changePM(String newPM_name){
     PM_name = newPM_name;
   }
           
   public void changeCM(String newCM_name){
     this.CM_name = newCM_name;
   }
 
   public static void main(String []args){
 
      StateOfACountry state1 = new StateOfACountry();
      state1.CM_name = "CM1";
      state1.PM_name = "PM";
           
      StateOfACountry state2 = new StateOfACountry();     
      state2.CM_name = "CM2";
      state2.PM_name = "PMabc";
      state1.changeCM("newCM1");
      System.out.println(state1.CM_name);
      System.out.println(state2.CM_name);
           
      state1.changePM("newPM1");
      System.out.println(state1.PM_name);
      System.out.println(state2.PM_name);          
     }
}

The output is:

newCM1

CM2

newPM1

newPM1


Thus we see that the function changeCM operates on the CM_name of a particular object, while the static function changePM operates on the static variable PM_name which is common for all the objects in the class.


INITIALIZING A STATIC VARIABLE:


Since static variables are not tied to any objects, they need not be initialized using an object. In other words, they do not have an “object state”.

public class MeaningOfStatic {
public static int var = display();
  public MeaningOfStatic() {
     System.out.println("Constructor Entered. Object is instantiated.");
  }
 public static int display(){
     System.out.println("Hello World");
     System.out.println(var);
     return 10;
   }
 
  public static void main(String[] args) {
     System.out.println("Main entered.");
     MeaningOfStatic object = new MeaningOfStatic();
     object.display();
     System.out.println(Math.PI);
     System.out.println(Math.sqrt(2)); //No object of Math is                                                initialized to invoke sqrt, because its static! 
     }
}

The output is:

Hello World

0
Main entered.
Constructor Entered. Object is instantiated.
Hello World
10
Thus we see that the static variable var was declared even before an object was initialized. It was also assigned value using the static function even before the main function was started! Because it isn’t tied to any particular object.
All lang.Math methods in java are static (e.g. Math.Random(), Math.sqrt()) because it wouldn’t make sense to tie all this methods to an object i.e. the methods Math.random, Math.sqrt have nothing in common.