Java Basics - Variable and Data Types Part 2

Variable Types (numbers)

Integer: int exampleVariable       //store (-) and (+) numbers that are small
Long:    long exampleVariable   //store (-) and (+) numbers that are big
Double: double exampleVariable //store fractions with decimal places

Variable Types (text)

String:          String = String fullText = "example";
Character:    char answer = 'b' or  char answer = '3';

Variable Types (decisions)

Boolean: boolean fact = true; 

//Can only have two values, true or false.

Variable Arithmetic

Addition: int x = 2+3    //=5
Subtraction: int y=5-2   //=3
Multiplication:  int days = 7*4 //= 28

Division:        double div =5/2 //=2
                       double div = 5/2.0; //=2.5 
                        (Note: the 2.0 forces it to store the fractional part instead of throwing it away)


Combining arithmetic variables.

double paid = 10;
double change = 3.25;
double tip = (paid-change)*0.2 // Note here that parenthesis are added as computers perform multiplication or divisions before addition or subtractions

______________________________________________

Truncation

//This is cutting off the digits to the right of a decimal point.
double div = 5/2;  2.5 = 2 (Note the 5 was deleted ie truncated)


________________________________________________

Casting

Convert a variable type into another variable type

For Example

        double future = 15.6;

         int approx = (int) future; //the second part is the integer

        System.out.println (int); //Would result in 15.


Another example of casting can show how we can force the division of integers to produce a fraction

int x= 5;
int y =2;

double accurate = (double)x/y; //essentially its resulting in the following operation 5.0 / 2  = 2.5
System.out.println(accurate); // would result an output of 2.5

_________________________________________________

Adding Comments

This is how you add a single line comment

//this is a comment

This is how you add a multi line comment

/*
This is a multiline comment section
Many comments can be written  here
*/




Comments

Popular posts from this blog

Java Basics - Variable and Data Types Part 1

OOP - Objects and Classes