Archive

Archive for the ‘Computers Stuff’ Category

Learn everything by looking into pictures

October 14, 2009 Leave a comment

When ever i think of learning something which is very new to time i usually think of  any video or any picture so that i can grasp it very easily and very quickly…  so here is the link for the people who hates reading (i hate reading all the time)

videos you will get it in Youtube but pictures  are very rare..

I found a very special site (May be its special for me ) here is the link for it http://inpics.net

have fun dudes…

Best Regards,
Siddik Shaik

Categories: Computers Stuff Tags:

Google Search Shorcuts

October 14, 2009 Leave a comment

Here i want to share the google tips (Effective Search )

Have a look up on it

Google Shortcut Finds Pages That Have…
nokia phone the words nokia and phone
sailing OR boating either the word sailing or the word boating
“love me tender” the exact phrase love me tender
printer -cartridge the word printer but NOT the word cartridge
Toy Story +2 movie title including the number 2
~auto looks up the word auto and synonyms
define:serendipity definitions of the word serendipity
how now * cow the words how now cow separated by one or more words
+ addition; 978+456
subtraction; 978-456
* multiplication; 978*456
/ division; 978/456
% of percentage; 50% of 100
^ raise to a power; 4^18 (4 to the eighteenth power)
old in new (conversion) 45 celsius in Fahrenheit
site:(search only one website) site:websearch.about.com “invisible web”
link:(find linked pages) link:www.lifehacker.com
#…#(search within a number range) nokia phone $200…$300
daterange:(search within specific date range) bosnia daterange:200508-200510
safesearch: (exclude adult content) safesearch:breast cancer
info: (find info about a page) info:www.websearch.about.com
related: (related pages) related:www.websearch.about.com
cache: (view cached page) cache:google.com
filetype:(restrict search to specific filetype) zoology filetype:ppt
allintitle: (search for keywords in page title) allintitle:”nike” running
inurl:(restrict search to page URLs) inurl:chewbacca
site:.edu (specific domain search) site:.edu, site:.gov, site:.org, etc.
site:country code (restrict search to country) site:.br “rio de Janeiro”
intext:(search for keyword in body text) intext:parlor
allintext: (return pages with all words specified in body text) allintext:north pole
book(search book text) book The Lord of the Rings
phonebook:(find a phone number) phonebook:Google CA
bphonebook: (find business phone numbers) bphonebook:Intel OR
rphonebook:(find residential phone numbers) rphonebook:Joe Smith Seattle WA
movie:(search for showtimes) movie:wallace and gromit 97110
stocks:(get a stock quote) stocks:ncesa
weather:(get local weather) weather:97132
Categories: Others Tags:

JAVA Conversions

October 14, 2009 Leave a comment

Dealing with nulls Then  Just go through these conversions

Java – comparing strings

Use == for primitive data types like int

If (mystring == null)

Use the equals() method to compare objects

Use .equals for strings : if (a.equals(“cat”))

Java – Converting int to string

String myString = Integer.toString(my int value)

   or

String str = “” + i

Java – Converting String to int

int i = Integer.parseInt(str);

   or
int i = Integer.valueOf(str).intValue();

double to String :

String str = Double.toString(i);

long to String :

String str = Long.toString(l);

float to String :

String str = Float.toString(f);

String to double :

double d =
Double.valueOf(str).doubleValue();

String to long :

long l = Long.valueOf(str).longValue();
   or

long l = Long.parseLong(str);

String to float :

float f = Float.valueOf(str).floatValue();


decimal to binary :

   int i = 42;

String binstr = Integer.toBinaryString(i);


decimal to hexadecimal :

   int i = 42;
   String hexstr = Integer.toString(i, 16);
   or
   String hexstr = Integer.toHexString(i);
   or (with leading zeroes and uppercase)
   public class Hex {
     public static void main(String args[]){
       int i = 42;
       System.out.print
         (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
      }
     }

hexadecimal (String) to integer :

int i = Integer.valueOf("B8DA3", 16).intValue();
   or

int i = Integer.parseInt(“B8DA3”, 16);

ASCII code to String

int i = 64;

String aChar = new Character((char)i).toString();

integer to ASCII code (byte)

char c = 'A';

int i = (int) c; // i will have the value 65 decimal

integer to boolean

b = (i != 0);

boolean to integer

i = (b)?1:0;

Categories: Java Tags: ,

Free JAVA Lectures (Direct Download)

October 14, 2009 2 comments

Free JAVA Lectures .. Just Click on the links its direct download link…Enjoy

Any of these lectures can be read using
OpenOffice.org

http://freejavalectures.googlepages.com/

Categories: Java Tags: ,

Some of the best Sites to learn Programming Languages

October 14, 2009 Leave a comment

Hello every one…

Here i have found many sites for learning Java, Jsp,JS and other Programming Languages. Mainly Concentrating on JAVA

1) Here is the first one mindprod Click Here.

the above  site is awesome  i can say that u will find all the things related to JAVA here. Infact not only java if you go to HOME then you find some more intresting things..Have fun

2) I would Strongly suggest every one who is new to this web technology just go through the www.w3schools.com

Here in the above site you will get all the basics.. Start with this site..

Hack any Java class using Reflection

October 14, 2009 Leave a comment

Ever wondered what evil power can be unleashed when using reflection? Do you think private methods are really only accessible from within the declaring class? Do you think that a private field can only be modified from within the declaring class? No? That’s what I thought!! In this blog, I will try to demonstrate that it is always important to correctly set the security properties of your applications. For instance, let’s look at the following example where we successfully retrieve a private password from another class:

1.  class A {
2.    private static String getPassword() {
3.      return "someHighlyPreciousPassword";
4.    }
5.  }
6.
7. public class Test {
8.   public static void main(String[] args) throws Exception {
9.     Class cl = Class.forName("A");
10.    java.lang.reflect.Method[] m = cl.getDeclaredMethods();
11.    m[0].setAccessible(true);
12.    String password = (String) m[0].invoke(null, null);
13.    System.out.println("I got it:" + password);
14.  }
15.}
Output:

 I got it: someHighlyPreciousPassword

Ok, the example is not really sexy. Let’s mess up a class that implements the Singleton pattern. In the normal case, a singleton object is supposed to be the only instance of a given class. To achieve this, we usually declare the class constructor private, so that no one can invoke it. Well, as demonstrated below, with reflection we can bypass this restriction and create a second “singleton object”.

1.  class A {
2.    public static final A singleton = new A("I'm the only instance of class A");
3.    private String name;
4.    private A(String name) {
5.      this.name = name;
6.    }
7.    public String toString() {
8.      return this.name;
9.    }
10. }
11.
12. public class Test {
13.   public static void main(String[] args) throws Exception {
14.     Class cl = Class.forName("A");
15.     java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
16.     c[0].setAccessible(true);
17.     A anotherA  = (A) c[0].newInstance(new Object[]{"Not anymore!!"});
18.     System.out.println(A.singleton);
19.     System.out.println(anotherA);
20.   }
21. }
Output:

 I'm the only instance of class A
 Not anymore!!

Using this technique, you can create an instance of any non-abstract class, even if all its constructors are declared private. For instance, below we create an instance of the Math class even though it is useless since the Math class has no instance method. Still, it is possible to do it.

1.  public class Test {
2.  public static void main(String[] args) throws Exception {
3.      Class cl = Class.forName("java.lang.Math");
4.      java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
5.      c[0].setAccessible(true);
6.      Math mathInstance = (Math) c[0].newInstance(null);
7.      System.out.println(mathInstance);
8.    }
9.  }
Output:

 java.lang.Math@1cde100

Finally, let’s mess with the Runtime class which has one private static field for storing the current Runtime instance. This is another example of a badly implemented singleton class. Let’s look at the code below. We first retrieve the current runtime object and display it (3-4). Then, we set the Runtime.currentRuntime static field to null, which means that all successive calls to Runtime.getRuntime() will yield null (6-9) since currentRuntime is initialized at class loading time. We then get the currentRuntime field again and display its value (11-12). And finally, we try to use the current runtime to execute a command for displaying the content of the current directory (14). The output talks for itself.

1.  public class Test {
2.    public static void main(String[] args) throws Exception {
3.      Runtime r = Runtime.getRuntime();
4.      System.out.println("Before: Runtime.getRuntime() yields " + r);
5.
6.      Class cl = Class.forName("java.lang.Runtime");
7.      java.lang.reflect.Field f = cl.getDeclaredField("currentRuntime");
8.      f.setAccessible(true);
9.      f.set(null, null);
10.
11.     r = Runtime.getRuntime();
12.     System.out.println("After: Runtime.getRuntime() yields " + r);
13.
14.     r.exec("dir"); //raises NullPointerException!!
15.   }
16. }
Output:

 Before: Runtime.getRuntime() yields java.lang.Runtime@cac268
 After: Runtime.getRuntime() yields null
 Exception in thread "main" java.lang.NullPointerException
       at Test.main(Test.java:59)

All this could have been avoided if the currentRuntime field had been declared final. Nothing prevents setAccessible(true) to be called on the field (8) but when the set(null, null) method is called, IllegalAccessException is thrown with the message “Field is final”.

I’m pretty sure that there is a huge amount of code out there that could be broken this way. Watch out!!
Bottom line: singleton fields should always be declared private static final!!! Moreover, make sure you never grant ReflectPermission and RuntimePermission.accessDeclaredMembers in the java.policy file of your production code.

@ This topic is taken from Javaranch

Categories: Java Tags:

StringBuilder vs StringBuffer vs String.concat

October 14, 2009 Leave a comment
illustration
How long is a piece of String?

Introduction

Concatenation of Strings is very easy in Java – all you need is a ‘+’. It can’t get any easier than that, right? Unfortunately there are a few pitfalls. One thing you should remember from your first Java lessons is a small albeit important detail: String objects are immutable. Once constructed they cannot be changed anymore.

Whenever you “change” the value of a String you create a new object and make that variable reference this new object. Appending a String to another existing one is the same kind of deal: a new String containing the stuff from both is created and the old one is dropped.

You might wonder why Strings are immutable in first place. There are two very compelling reasons for it:

  1. Immutable basic types makes things easier. If you pass a String to a function you can be sure that its value won’t change.
  2. Security. With mutable Strings one could bypass security checks by changing the value right after the check. (Same thing as the first point, really.)

The performance impact of String.concat()

Each time you append something via ‘+’ (String.concat()) a new String is created, the old stuff is copied, the new stuff is appended, and the old String is thrown away. The bigger the String gets the longer it takes – there is more to copy and more garbage is produced.

Creating a String with a length of 65536 (character by character) already takes about 22 seconds on an AMD64 X2 4200+. The following diagram illustrates the exponentially growing amount of required time:

String.concat() - exponential growth
Figure 1: StringBuilder vs StringBuffer vs String.concat

StringBuilder and StringBuffer are also shown, but at this scale they are right onto the x-axis. As you can see String.concat() is slow. Amazingly slow in fact. It’s so bad that the guys over at FindBugs added a detector for String.concat inside loops to their static code analysis tool.

When to use ‘+’

Using the ‘+’ operator for concatenation isn’t bad per se though. It’s very readable and it doesn’t necessarily affect performance. Let’s take a look at the kind of situations where you should use ‘+’.

a) Multi-line Strings:

String text=
    "line 1\n"+
    "line 2\n"+
    "line 3";

Since Java doesn’t feature a proper multi-line String construct like other languages, this kind of pattern is often used. If you really have to you can embed massive blocks of text this way and there are no downsides at all. The compiler creates a single String out of this mess and no concatenation happens at runtime.

b) Short messages and the like:

System.out.println("x:"+x+" y:"+y);

The compiler transforms this to:

System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());

Looks pretty silly, doesn’t it? Well, it’s great that you don’t have to write that kind of code yourself. 😉

If you’re interested in byte code generation: Accordingly to Arno Unkrig (the amazing dude behind Janino) the optimal strategy is to use String.concat() for 2 or 3 operands, and StringBuilder for 4 or more operands (if available – otherwise StringBuffer). Sun’s compiler always uses StringBuilder/StringBuffer though. Well, the difference is pretty negligible.

When to use StringBuilder and StringBuffer

This one is easy to remember: use ’em whenever you assembe a String in a loop. If it’s a short piece of example code, a test program, or something completely unimportant you won’t necessarily need that though. Just keep in mind that ‘+’ isn’t always a good idea.

StringBuilder and StringBuffer compared

StringBuilder is rather new – it was introduced with 1.5. Unlike StringBuffer it isn’t synchronized, which makes it a tad faster:

StringBuilder compared with StringBuffer
Figure 2: StringBuilder vs StringBuffer

As you can see the graphs are sort of straight with a few bumps here and there caused by re-allocation. Also StringBuilder is indeed quite a bit faster. Use that one if you can.

Initial capacity

Both – StringBuilder and StringBuffer – allow you to specify the initial capacity in the constructor. Of course this was also a thing I had to experiment with. Creating a 0.5mb String 50 times with different initial capacities:

different initial capacities compared
Figure 3: StringBuilder and StringBuffer with different initial capacities

The step size was 8 and the default capacity is 16. So, the default is the third dot. 16 chars is pretty small and as you can see it’s a very sensible default value.

If you take a closer look you can also see that there is some kind of rhythm: the best initial capacities (local optimum) are always a power of two. And the worst results are always just before the next power of two. The perfect results are of course achieved if the required size is used from the very beginning (shown as dashed lines in the diagram) and no resizing happens at all.

Some insight

That “PoT beat” is of course specific to Sun’s implementations of StringBuilder and StringBuffer. Other implementations may show a slightly different behavior. However, if these particular implementations are taken as target one can derive two golden rules from these results:

  1. If you set the capacity use a power of two value.
  2. Do not use the String/CharSequence constructors ever. They set the capacity to the length of the given String/CharSequence + 16, which can be virtually anything.
Categories: Java Tags: