Java: Very simple (part2)

Google+ Pinterest LinkedIn Tumblr +

Java variables:

Java is almost like C++ in variables. To define a variable there are three main methods:

1.TypeOfVariable NameOfVariable;

2.TypeOfVariable NameOfVariable=initial_value;

3.TypeOfVariable NameOfVariable1, NameOfVariable2, NameOfVariable3;

The following is an example:

int I;

int j=1;

int k,l;

the variables that are used for mathematical operations are:

boolean ==> true or false

char==> 16-bit, Unicode character

byte==> 8-bit, signed, two’s complement integer

short==> 16-bit, signed, two’s complement integer

int==> 32-bit, signed, two’s complement integer

long==> 64-bit, signed, two’s complement integer

float==> 32-bit, IEEE 754, floating-point value

double==>64-bit, floating point

let’s see an example with the program uses the type:

class test

{

public static void main(String args[])

{

int i,j;

float flt;

i=1000;

j=20;

flt=(float)i*(float) j;

System.out.println(flt);}

}

Now compile and run the test.java file, the results would be :20000

In the line int i,j; two integer variable i,j are defined, without initial value

Then their value is set to 1000, 20 respectively

Also the variable from the type of float is defined, and the value is set equal to multiplication of i,j.

The casting operation:

In the line: “flt=(float)i*(float) j;” a casting operation is done, in this file type of i,j is converted to float to make the operation. Imagine you want to change the type a variable from double to int, or int to float. If just before the variable name in the parenthesis put the type you like, the variable would be considered from that type in your equation.

In the last line the value of multiplication is output. This shows println can output different types of data.

Share.

About Author

Leave A Reply