Sunday 25 September 2011

Frequent error

I was going through my answers on my Yahoo Answers profile
It was amazing
Atleast 25% were related to a common error
Using == to compare strings
We could not use == to compare two strings because they are the objects of String class present in java.lang package
To compare two strings we should use equals method
String s= "Hello";
if( s.equals("Hello") )
or
if( "Hello".equals(s) )
The second one is said to be more faster
To compare two string ignoring case
if( s.equalsIgnoreCase( "Hello"))

Friday 12 August 2011

Magic Square

I designed an interesting program

I wrote code for the creation and initialization
of a magic square of the given odd size. I implemented the
following algoritm:

- put 1 in the middle cell of the first row;
- every next value must be placed in a cell
one row up and one column right relative to the previous one;
- if the destinaton of the next cell appears outside of the
array, enter the later from the opposite end;
- if the destinaton of the next cell is already occupied,
then move just one row down relative to the previous cell.

For example,

for size = 3,

8    1    6
3    5    7
4    9    2

the sum of all rows and columns is 15


Here is the code
class Grid
{
int num;
public void fillGrid(int n)
{
int ar[][]=new int[n][n];
num=n;
fill(ar);
int r=0,c=n/2,i;
for(i=1;i<=(n*n);i++)
{
if(ar[r][c]==0)
ar[r][c]=i;
else
ar[++r][c]=i;

/*printArray(ar);
System.out.println("\n\n\n\n");*/

if((r-1)<0 && (c+1)>=n)
r++;
else
{
if((r-1)<0)
{
r=n-1;
c++;
}
else if((c+1)>=n)
{
r--;
c=(c+1)-n;
}
else if(ar[r-1][c+1]==0)
{
r--;
c++;
}
}
}
printArray(ar);
}
void fill(int Ar[][])
{
int i,j;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
Ar[i][j]=0;
}
}
void printArray(int Ar[][])
{
int i,j;
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
System.out.print("\t "+Ar[i][j]);
System.out.println("");
}
}
}


Saturday 6 August 2011

Binary Search in an array

import java.util.Arrays;
import java.util.Scanner;
public class BinarySearch
{
// precondition: array a[] is sorted
public int search(int[] a,int key)
{
int lo = 0;
int hi = a.length - 1;
while (lo <= hi)
{
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid])
hi = mid - 1;
else if (key > a[mid])
lo = mid + 1;
else return mid;
}
return -1;
}
public static void main(String[] args)
{
int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++)
{
arr[i] = input.nextInt();
}
BinarySearch search = new BinarySearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if (n!=-1 )
{
System.out.println("Found at index: " + n);
}
else
{
System.out.println("Not Found");
}
}

}

Linear Search in an array in java

Linear Search in Java

In this section, we are going to find an element from an array using Linear Searching. Linear searching is a good way to find an element from the array. The array can be of any order, it checks whether a certain element (number , string , etc. ) is in a specified array or not. Basically it is used for small arrays. In the given code, we have allowed the user to enter the numbers to be stored into the arrays. If the element is found we can return the index where the element is located in the array. If the element is not found we can return -1.
Here is the code:

import java.util.Scanner;

public class LinearSearch
{
public int find(final int[] data, final int key)
{
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}

public static void main(String[] args)
{
int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if (n!=-1 )
{
System.out.println("Found at index: " + n);
} else
{
System.out.println("Not Found");
}
}

}

Output:

Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10
Enter the element to search:5
Found at index: 4

Friday 22 July 2011

How to find the documentation of any java library class or interface

Suppose we want to check this class
java.util.Array
There are two ways
1.If you have an Internet connection then just google
oracle java.util.Array
This gives you the latest documentation
2.If you do not have Internet due to any reason then go to the java folder
open JDK
there will be a compressed folder with name src
open it and then open java folder
then open util
then you can find Array named java source file just open it in a IDE and generate documentation

Monday 18 July 2011

Providing command line arguments

Here is the code of the file
public class Hello
{
public static void main(String args[])
{
if(args.length==1)
System.out.println("Hello "+args[0]);
}
}
we save it in Hello.java and compile it by javac Hello.java
Then we run it like this
java Hello Codex
and it prints out
Hello Codex
but if we want to provide multiple words as our name then we do like this
java Hello "Codex Java"
and it prints out
Hello Codex Java

Sunday 17 July 2011

Setting tool tip Text for any JComponent

Tool Tip Text
Creating a tool tip for any JComponent object is easy. Use the setToolTipText method to set up a tool tip for the component. For example, to add tool tips to a button, you add only one line of code:
b1.setToolTipText("Button 1")

The following is the code of program we want to compile and run
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Save it with the name HelloWorld.java
Now Suppose we save it at D:\java
First we change to D:\java by using cd as shown in image


Now we compile and run it like this
javac HelloWorld.java
java HelloWorld
see the image


If you get an error saying javac was not recognized as an internal or external command or batch file
then you need to set path of javac
So right click on My Computer and select Properties
Now go to Advanced
Now create a new Environmental variable with the value to the bin folder of java

Thursday 7 July 2011

Using varargs
varargs allow you to pass more than one parameter to a function
example
class Example
{
pubic static void main(String args[])
{
Example ob=new Example();
ob.printNum(5,6,7);
ob.printNum(1,2,3,4);
}
void printNum(int... a)
{
int i;
for(i:a)
System.out.println(a);
}
}
How to compile a java program from inside another java program
Suppose you need to compile HelloWorld.java and run from another program
here is a code
Runtime r=Runtime.getRuntime();
Process p=r.exec("javac HelloWorld.java");
p.waitFor();
Process run=(Runtime.getRuntime).exec("java HelloWorld");

Sunday 3 July 2011

Anonymous inner classes


Anonymous inner class
An anonymous inner class is one that is not assigned a name. This section illustrates how an
anonymous inner class can facilitate the writing of event handlers. Consider the applet shown
in the following listing. As before, its goal is to display the string “Mouse Pressed” in the
status bar of the applet viewer or browser when the mouse is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
There is one top-level class in this program: AnonymousInnerClassDemo. The init( )
method calls the addMouseListener( ) method. Its argument is an expression that defines
and instantiates an anonymous inner class. Let’s analyze this expression carefully.
The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the
braces defines an anonymous inner class. Furthermore, that class extends MouseAdapter. This
new class is not named, but it is automatically instantiated when this expression is executed.
Because this anonymous inner class is defined within the scope of
AnonymousInnerClassDemo, it has access to all of the variables and methods within
the scope of that class. Therefore, it can call the showStatus( ) method directly.
As just illustrated, both named and anonymous inner classes solve some annoying
problems in a simple yet effective way. They also allow you to create more efficient code.






 
You can find some useful programs at Example page

Sunday 26 June 2011

This blog is designed for tutorials and codes for java programs