Monday, May 27, 2013

How to check datatype in java!

Hi community!
I have sample code for checking datatype in java. Let's go to check it!

public class DataTypeInJava {
public static void main(String[] args) {

System.out.println("\nFor byte datatype");
System.out.println("Max "+ Byte.MAX_VALUE);
System.out.println("Mix "+ Byte.MIN_VALUE);
System.out.println("Size :"+ Byte.SIZE+ "bits");

System.out.println("\nFor short datatype");
System.out.println("Max "+ Short.MAX_VALUE);
System.out.println("Mix "+ Short.MIN_VALUE);
System.out.println("Size :"+ Short.SIZE+ "bits");

System.out.println("\nFor int datatype");
System.out.println("Max "+ Integer.MAX_VALUE);
System.out.println("Mix "+ Integer.MIN_VALUE);
System.out.println("Size :"+ Integer.SIZE+ "bits");

System.out.println("\nFor long datatype");
System.out.println("Max "+ Long.MAX_VALUE);
System.out.println("Mix "+ Long.MIN_VALUE);
System.out.println("Size :"+ Long.SIZE+ "bits");

System.out.println("\nFor float datatype");
System.out.println("Max "+ Float.MAX_VALUE);
System.out.println("Mix "+ Float.MIN_VALUE);
System.out.println("Size :"+ Float.SIZE+ "bits");

System.out.println("\nFor double datatype");
System.out.println("Max "+ Double.MAX_VALUE);
System.out.println("Mix "+ Double.MIN_VALUE);
System.out.println("Size :"+ Double.SIZE+ "bits");

System.out.println("\nFor boolean datatype");
System.out.println("Type "+ Boolean.FALSE +" and "+ Boolean.TRUE);

System.out.println("\nFor character datatype");
System.out.println("Size "+ Character.SIZE);
System.out.println("Type "+ Character.TYPE);


}
}

Sample Game in Java!

Sample Game:

First way!

import java.util.Random;
public class Player {
String result="";String name="";
public String player(){
Random rnd = new Random();
int i = rnd.nextInt(3);
if(i == 0)
result = "Paper";
else if(i == 1)
result = "Crisor";
else
result = "Rock";
return result;
}
public static void main(String[] args) {
Player p1 = new Player();
Player p2 = new Player();

p1.name = "Player1";
p2.name = "Player2";

String pla1 =p1.player();; String pla2=p2.player();
if(pla1 == "Crisor" && pla2 == "Paper"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p1.name + " is win!");
}else if(pla1 == "Rock" && pla2 == "Crisor"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p1.name + " is win!");
}else if(pla1 == "Paper" && pla2 == "Rock"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p1.name + " is win!");
}else if(pla2 == "Crisor" && pla1 == "Paper"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p2.name + " is win!");
}else if(pla2 == "Rock" && pla1 == "Crisor"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p2.name + " is win!");
}else if(pla2 == "Paper" && pla1 == "Rock"){
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2);
System.out.println(p2.name + " is win!");
}else{
System.out.println(p1.name + " is " + pla1 + " and " + p2.name + " is " + pla2+".Plase play again!");
}
}
}

Thursday, May 23, 2013

How to calculate Decimal into Binary number.

Edited by Sean Hickey, Tom Viren, Sondra C, Lucas Halbert and 65 others

Convert from Decimal to Binary
The decimal (base ten) numeral system has ten possible values (0,1,2,3,4,5,6,7,8, or 9) for each place-value. In contrast, the binary (base two) numeral system has two possible values, often represented as 0 or 1, for each place-value.
To avoid confusion while using different numeral systems, the base of each individual number may be specified by writing it as a subscript of the number. For example, the decimal number 156 may be written as 15610 and read as "one hundred fifty-six, base ten". The binary number 10011100 may be specified as "base two" by writing it as 100111002.
Since the binary system is the internal language of electronic computers, serious computer programmers should understand how to convert from decimal to binary. Here's how to do it.

Choosing a method of conversion

  • Short division by two with remainder (easier for beginners)
  • Comparison with descending powers of two and subtraction

Method One: Short Division by Two with Remainder

This method is much easier to understand when visualized on paper. It relies only on division by two.
  1. 1
    Set up the problem. For this example, let's convert the decimal number 15610 to binary.
    • Write the decimal number as the dividend inside an upside-down "long division" symbol.
    • Write the base of the destination system (in our case, "2" for binary) as the divisor outside the curve of the division symbol.
  2. 2
    Write the integer answer (quotient) under the long division symbol, and write the remainder (0 or 1) to the right of the dividend.
    • Basically, if the dividend is even, the binary remainder will be 0; if the dividend is odd, the binary remainder will be 1.
  3. 3
    Continue downwards, dividing each new quotient by two and writing the remainders to the right of each dividend. Stop when the quotient is 0.
  4. 4
    Starting with the bottom remainder, read the sequence of remainders upwards to the top. For this example, you should have 10011100. This is the binary equivalent of the decimal number 156. Or, written with base subscripts: 15610 = 100111002
    • This method can be modified to convert from decimal to any base. The divisor is 2 because the desired destination is base 2. If the desired destination is a different base, replace the 2 in the method with the desired base. For example, if the desired destination is base 9, replace the 2 with 9. The final result will then be in the desired base.

Method Two: Descending Powers of Two and Subtraction

  1. 1
    List the powers of two in a "base 2 table" from right to left. Start at 20, evaluating it as "1". Increment the exponent by one for each power. The list, to ten elements, would look like this: 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
  2. 2
    Figure out the greatest power that will fit into the number you want to convert to binary. For this example, let's convert the decimal number 15610 to binary. What is the greatest power of two that will fit into 156? Since 128 fits, write a 1 for the leftmost binary digit, and subtract 128 from your decimal number, 156. You now have 28.
  3. 3
    Move to the next lower power of two. Can 64 fit into 28? No, so write a 0 for the next binary digit to the right.
  4. 4
    Can 32 fit into 28? No, so write a 0.
  5. 5
    Can 16 fit into 28? Yes, so write a 1, and subtract 16 from 28. You now have 12.
  6. 6
    Can 8 fit into 12? Yes, so write a 1, and subtract 8 from 12. You now have 4.
  7. 7
    Can 4 (power of two) fit into 4 (working decimal)? Yes, so write a 1, and subtract 4 from 4. You have 0.
  8. 8
    Can 2 fit into 0? No, so write a 0.
  9. 9
    Can 1 fit into 0? No, so write a 0.
  10. 10
    Put together the binary answer. Since there are no more powers of two in the list, you are done. You should have 10011100. This is the binary equivalent of the decimal number 156. Or, written with base subscripts: 15610 = 100111002.
    • Repetition of this method will result in memorization of the powers of two, which will allow you to skip Step 1.




Convert from Decimal number to Binary , Octal , and Hexa number in java

 Hi everyone!

Today I want to share sample code to convert Decimal number into
Binary , Octal , and Hexa number that I was written in java Language.

Let's go!

import java.util.Scanner;

public class DecimalToBinary {
    public static void main(String[] args) {
        System.out.print("In decimal nunber: ");
           int i = new Scanner(System.in).nextInt();
          
           // convert from decimal number to binary number
           toBinary(i);
           System.out.println("------------------------------------------ ");
           System.out.print("Convert from decimal= "+i+" in binary is : ");
           sBinary(i);
          
           // convert from decimal number to octal number
           System.out.println();
           System.out.println("------------------------------------------- ");
           toOctal(i);
           System.out.println("------------------------------------------ ");
           System.out.print("Convert from decimal= "+ i +" in octal is : ");
           sOctal(i);
          
           // convert from decimal number to hexa number
           System.out.println();
           System.out.println("------------------------------------------- ");
           toHexa(i);
           System.out.println("------------------------------------------ ");
           System.out.print("Convert from decimal= "+ i +" in hexa is : ");
           sHexa(i);
       }
        /** Use method in java */
       public static void toBinary(int i){
           System.out.print("Convert from decimal= " + i + " in binary is : ");
           System.out.println(Integer.toBinaryString(i));
       }
       public static void toOctal(int i){
           System.out.print("Convert from decimal= " + i+ " in octal is : ");
           System.out.println(Integer.toOctalString(i));
       }
       public static void toHexa(int i){
           System.out.print("Convett from decimal= " + i + " in hexa is : ");
           System.out.println(Integer.toHexString(i));
       }
      
      
       /** Create method myself*/
       public static Object sBinary(int i){
           int remainder;
            if (i <=1) {
                System.out.print(i);
                return null;  
            }
            remainder= i %2;
            sBinary(i >>1);
            System.out.print(remainder);
            {
              return null;
            }
       }
      
       public static void sOctal(int i){
           String s = "";
           do {
               int digit = i % 8;
                   s = digit + s;
                   i = i / 8 ;
           }while (i > 0);
           System.out.println(""+s);
       }
      
       public static void sHexa(int i){
           String s = "";
           do {
               int digit = i % 16;
               if (digit == 15)
                   s = "f" + s;
               else if(digit == 14)
                   s = "e" + s;
               else if(digit == 13)
                   s = "d" + s;
               else if(digit == 12)
                   s = "c" + s;
               else if(digit == 11)
                   s = "b" + s;
               else if(digit == 10)
                   s = "a" + s;
               else
                s = digit + s;
                   i = i / 16 ;
           }while (i > 0);
           System.out.println(""+s);
       }
}

Wednesday, May 22, 2013

Upcasting and Downcasting in Java Programming

Upcasting and downcasting are important part of Java, which allow us to build complicated programs using simple syntax, and gives us great advantages, like Polymorphism or grouping different objects. Java permits an object of a subclass type to be treated as an object of any superclass type. This is called upcasting. Upcasting is done automatically, while downcasting must be manually done by the programmer, and i'm going to give my best to explain why is that so.

Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects.

Throughout this tutorial i'm going to use Animal hierarchy to explain how class hierarchy works.

Inheritance

updown.png

What we have here, is a simplified version of an Animal Hierarchy. You can see, that Cat and Dog are both Mammals, which extends from Animal, which silently extends from Object. By silently, i mean, that Java automatically extends every class from Object class, which isn't extended from something else, so everything is an Object (except primitives).

Now, if you ask - is Cat an Object - It doesn't extend Object, it extends Mammal?
By inheritance Cat gets all the properties its ancestors have. Object is Cat's grandgrandparent, which means Cat is also an Object. Cat is also an Animal and a Mammal, which logically means - if Mammals possess mammary glands and Animals are living beings, then Cat also has mammary glands and is living being.

Basic JTable and Netbeans

What this means for a programmer, is that we don't need to write for every possible Animal, that it has health. We just need to write it once, and every Animal gets it through inheritance.
Consider the following example:

class Animal {
int health = 100;
}

class Mammal extends Animal { }

class Cat extends Mammal { }

class Dog extends Mammal { }

public class Test {
public static void main(String[] args) {
Cat c = new Cat();
System.out.println(c.health);
Dog d = new Dog();
System.out.println(d.health);
}
}


When running the Test class, it will print "100" and "100" to the console, because both, Cat and Dog inherited the "health" from Animal class.

Upcasting and downcasting

First, you must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.
For example, if you create a Cat and upcast it to Animal, then the object doesn't stop from being a Cat. It's still a Cat, but it's just treated as any other Animal and it's Cat properties are hidden until it's downcasted to a Cat again.
Let's look at object's code before and after upcasting:
Cat c = new Cat();
System.out.println(c);
Mammal m = c; // upcasting
System.out.println(m);

/*
This printed:
Cat@a90653
Cat@a90653
*/


As you can see, Cat is still exactly the same Cat after upcasting, it didn't change to a Mammal, it's just being labeled Mammal right now. This is allowed, because Cat is a Mammal.

Note that, even though they are both Mammals, Cat cannot be cast to a Dog. Following picture might make it a bit more clear.
updown2.png

Although there's no need to for programmer to upcast manually, it's allowed to do.
Consider the following example:

Mammal m = (Mammal)new Cat();


is equal to

Mammal m = new Cat();


But downcasting must always be done manually:

Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat


Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException.

Double buffering, movement, and collision detection

This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Consider the following example:

Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}


Note, that casting can't always be done in both ways. If you are creating a Mammal, by calling "new Mammal()", you a creating a Object that is a Mammal, but it cannot be downcasted to Dog or Cat, because it's neither of them.
For example:
Mammal m = new Mammal();
Cat c = (Cat)m;


Such code passes compiling, but throws "java.lang.ClassCastException: Mammal cannot be cast to Cat" exception during running, because im trying to cast a Mammal, which is not a Cat, to a Cat.

General idea behind casting, is that, which object is which. You should ask, is Cat a Mammal? Yes, it is - that means, it can be cast.
Is Mammal a Cat? No it isn't - it cannot be cast.
Is Cat a Dog? No, it cannot be cast.
Important: Do not confuse variables with instances here. Cat from Mammal Variable can be cast to a Cat, but Mammal from Mammal variable cannot be cast to a Cat.

Creating an Executable Jar File

Cats cant purr, while being labeled something else
If you upcast an object, it will lose all it's properties, which were inherited from below it's current position. For example, if you cast a Cat to an Animal, it will lose properties inherited from Mammal and Cat. Note, that data will not be lost, you just can't use it, until you downcast the object to the right level.
Why is it like that? If you have a group of Animals, then you can't be sure which ones can meow() and which ones can bark(). That is why you can't make Animal do things, that are only specific for Dogs or Cats.
updown7.png

However the problem above is not an obstacle, if you choose to use polymorphism. Polymorphism uses automatic downcast during method calls. I'm not going to go into details with this one, so i'm referring to Polymorphism tutorial by Turk4n: http://forum.codecal...lymorphism.html
updown5.png

Upcasting during method calling

The beauty of casting is that programmer can make general methods, which can take a lot of different classes as an argument.
For example:

public static void stroke(Animal a){
System.out.println("you stroke the "+a);
}


This method can have what ever Animal or it's subclass as an argument. For example calling:

Cat c = new Cat();
Dog d = new Dog();
stroke(c); // automatic upcast to an Animal
stroke(d); // automatic upcast to an Animal


..is a correct code.

updown3.png

however, if you have a Cat, that is currently being held by Animal variable, then this variable cannot be argument for a method, that expects only Cats, even though we currently have a instance of Cat - manual downcasting must be done before that.

updown4.png

About variables

Variables can hold instance of objects that are equal or are hierarchically below them. For example Cat c; can hold instances of Cat and anything that is extended from a Cat. Animal can hold Animal, Mammal, etc..
Remember, that instances will always be upcasted to the variable level.

"I really need to make a Dog out of my Cat!"

Well, you can't do it by casting. However, objects are nothing else, but few methods and fields. That means, you can make a new dog out of your Cat's data.

Let's say you have a Cat class:

class Cat extends Mammal {
Color furColor;
int numberOfLives;
int speed;
int balance;
int kittens = 0;

Cat(Color f, int n, int s, int B){
this.furColor = f;
this.numberOfLives = n;
this.speed = s;
this.balance = b;
}
}


and a Dog class.

class Dog extends Mammal {
Color furColor;
int speed;
int barkVolume;
int puppies = 0;

Dog(Color f, int n, int s, int B){
this.furColor = f;
this.speed = s;
this.barkVolume = b;
}
}


and you want to make a Dog out of the Cat. All you need to do, is, place a method inside of the Cat class, that converts the fields and returns a new Dog based on that.

public Dog toDog(int barkVolume){
Dog d = new Dog(furColor, speed, barkVolume);
d.puppies = kittens;
return d;
}


As you can see, they don't match that well, so some fields were inconvertible, and some data had to be made from scratch. Notice, that numberOfLives and Balance were not converted, and barkVolume was completely new data. If you have 2 Classes, that match perfectly, then hurray, but it rarely happens.
conversion can now be called from where ever you need:

Cat c = new Cat(Color.black, 9, 20, 40);
Dog d = c.toDog(50);