Search Java Tutorials

Custom Search

What You Will Want to Complete This Tutorial?

You must have at least 1st and 2nd pre-requirements to start the tute. Other requirements will require for last chapters only. These all are free to use and download!
  1. Java Development Kit Standard Edition (JDK / J2SE) Any Version(www.java.com)
  2. Any Text Editor (Note Pad quite enough or get Notepad++ from (http://notepad-plus.sourceforge.net)
  3. Java Run Time Environment (JRE) Any Version(www.java.com)
  4. Java Enterprise Edition (J2EE) for advanced developing (For last few chapters)(www.java.com)
  5. Java Wireless Toolkit for Mobile Application Development (For Mobile Application Development Chapters) (www.java.com)
  6. Tomcat Web Server to run Servlets. (www.tomcat.apache.org/)
Your operating system may be any version of Windows.
What will you learn (As a summary)?
  1. How to build console and windowed applications using Java
  2. How to build web page elements with Java Applets
  3. How to build Database Programs with Java
  4. How to build enterprise applications with Beans
  5. How to add Email functions to Java programs
  6. How to program smart devices (Phone, PDA etc…) with Java

How to cast or convert variables in Java?

Casting is a data type conversion technique. You many use these castings often. As we mentioned earlier, every keyboard input receives as String. Imagine, you’re making calculator software. To do mathematical functions with numbers you want data types like integer, long, float, byte or short but not Strings. Then you need to do the conversion Strings into integer, long etc…

If you need to convert value in a larger capacity data type in to a smaller capacity data type, then you need a casting.

Ex: (long variables capacity: 8 bits, and integer variables capacity 4 bits. Casing the value in long into integer)
Int myInteger = (int)myLong;

Casing can be used to conversions of two different data types with similar capacity.
Ex: (integers are 4 bits and floats are 4 bits too. Casing the value in integer into float)
Float myfloat = (float)myInteger;

Sample Program:
Case: We will define 3 variables and we will cast them.

public class Casting
{
public static void main(String[] args)
{
int myInteger = 64; //integers are 4bytes
float myFloat = 0; //floats are 4bytes
byte myByte = 0; // bytes are 1 byte

System.out.println("Casting similar capacity variables...");
myFloat = (float)myInteger;
System.out.println(myFloat);

System.out.println("Casing larger variable value into samller...");
myByte = (byte)myInteger;
System.out.println(myByte);

}
}


This is the output:


No comments: