|
mimoh_mi (m)
|
Final note on variables. Remember from the last note, I listed the various data types and played with numerical data types by getting the minimium and maximum values, we also talked about char for single letters. So let me just run through different way of declaring variables in Java.
Numeric Variables:
We can define numeric types using number system like decimal(default), Octal and Hexadecimal. Let just quickly show that.
//The program demonstrates how to declare and use Java Data type
public class VariablePlay2 {
public static void main(String [] args){
//Using decimal int decimal = 1000;
//using octal. add 0 as prefix int octal = 01000;
//using hexadecimal. add 0x as prefix, values are not case sensitive int hexa = 0XADC; //show that hexadecimal values are not case sensitive int hexa2 = 0xadc;
//Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("decimal value is "+decimal + " "+", octal value is "+ octal + " "+", hexa value is " + hexa + " "+", hexa2 value is "+ hexa2); } }
Result:
decimal value is 1000 , octal value is 512 , hexa value is 2780 , hexa2 value is 2780
So we can see that it is easy to use other number systems in Java, just follow the rules. Let's look at other rules.
Character:
To define a character in java, simple use char data type. Note you can assign only single letters and numbers within the rquired range as demostrated earlier. It must be placed within a single quote.Also, you can assign unicode values to a char variable but must begin with \u as prefix. Let me do some demo.
//The program demostrates how to declare and use char Data type
public class VariablePlay3 {
public static void main(String [] args){
//declare variable of char char singleLetter = 'z';
//using Unicode values char Unicode = '\u004E'; //unicode value for letter E
//using decimal char decimal = 234;
//using hexadecimal char hexa = 0x892;
//Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("Single Letter value is "+singleLetter + " "+", Unicode value is "+ unicode + " "+", decimal value is " + decimal + " "+", hexa value is "+ hexa); } }
Result:
Single Letter value is z , Unicode value is N , decimal value is O , hexa value is ?
Let's look at floating numbers, by default all floating numbers are double, just the way all integers are treated as int. So, to specify a double variable a letter D or d is used as a postfix while for float letter F or f is used to indicate that the variable is of type float. The following demo will show how.
//The program demonstrates how to declare and use Java Data type
public class VariablePlay4{
public static void main(String [] args){
//declare variable of float float balance = 1000.90f; //try removing the f, compiler scretches possible loss of precision //you will be trying to put a squize an elephant in to an ant hole.
//declare a variable of double double pay = 30003000.455; // notice here, no d or D is specified, compiler allows it // because double is the default type for floating point numbers
//using postfix d for double double change = 456.234d; // the compiler will just thank you for specifically tell her what to do. // sorry, it a compiler he or she ?
//using postfix f float fare = 38989.858f; //compiler will always force you to append f to your float declaration.
//Here, just want to print out the values, notice "" and +, just saying append one value to the // end of the other, without it, we will just get the sum of the numbers System.out.println("balance value is "+balance + " "+", pay value is "+ pay + " "+", change value is " + change + " "+", fare value is "+ fare); } }
Result:
balance value is 1000.9 , pay value is 3.0003000455E7 , change value is 456.234 , fare value is 38989.86
So, on a final lap, let's look at other issues on data type. Remember i said int is the default value for none floating point numbers, but we have a long data type, so how do we declare it. It's simple, just append a letter L or l to it as a postfix. Also note that Java is very sensitive with data types, once you declare a variable as a specific data type, the compiler ensures it is used within that data type context except for few occassions, which i am going to demostrate.Before the demo let's look at a case study.
Assuming you declare a variable of type byte and assign say 100 to it, if withing the program you added it to another number of any data type, the compiler automatically promotes the result to type int. So the gist is this, when you add two numbers of any type, you get an int as a result. So, how do get the required type back, we have to explicitely tell the compiler, hey i want my answer to be of this type by casting. If you have never heard of the word casting, not too much about it, it a process of telling the compiler that you know what you are doing and ready to help responsible for any loss of precision.
//The program demostrates how to cast Java Data type
public class VariablePlay5{
public static void main(String [] args){
//declare variable of byte byte number1 = 1;
//declare a variable of short byte number2 = 50;
/**declare a variable to hold the sum this line will not pass the compiler because the result will automatically promoted to int which is bigger than a byte */
//byte sum = number1 + number2;
/*To correct the line above, we have to explicitly cast it. will this line make it pass the compiler ? The answer is no, we are only casting number1 and not the result. */
//byte sum = (byte) number1 + number2;
// OK, will this one make pass the compiler, let watch and see.
byte sum = (byte)(number1 + number2);
//Here, because we are just outputting the result and not assigning it to any variable //it works. Here I have do some tricks to add my number1 and number2 within the println method System.out.print("The value of sum of number1 and number2 is "); System.out.println(number1 + number2);
//ok, let's output our wahala sum System.out.println("The value of sum after casting is = "+ sum); } }
Result:
The value of sum of number1 and number2 is 51 The value of sum after casting is = 51
So, when do we need to cast data types ? of course, when assigning larger data types to smaller types. From small to large is done for us by the compiler.
Let's look at the other types. We might have some cases, where we want make a logical decision if certain conditions are true or false. Ok, let see such in the next code.
//The program demonstrates how to declare and use Java Data type
public class VariablePlay6{
public static void main(String [] args){
//Declare a long data type and set the value to 10000 //appending L is not mandatory but it is always good to do so. // Some could easily tell from looking at your code long number = 10000L;
//Declare an int data type and set the value to 1000 int number2 = 1000;
/*Declare a boolean data type and set the value to false. Try changing the value to true and run it again to see the result */ Remember, it can only have a value of true or false boolean isGreater = false;
if (isGreater) {
int add = (int)(number + number2);
System.out.println("The sum is = " +add); }
int sub = (int)(number - number2);
System.out.println("The value of sub after test is = "+ sub); System.out.println("The test failed "+ isGreater);
} }
Result :
The value of sub after test is = 9000 The test failed false
Some people might have been worried as how do I declare a variable to hold say names and other things that hasn't been covered. OK, i will just demostrate that now. In Java, there is a class called String. String is handled in a very flexible way in Java. They are not among the primitive data types, but object types or what is called reference variables. They also treated specially, we find ourselves making alot of use of this type as i am going to demostrate in the next demo. Sorry before the demo, string variables are declared by puting the variable value within a double quote.
//The program demostrates how use String in Java
public class VariablePlay7{
public static void main(String [] args){
//Creating a String Reference variable by instantiating the String Class // and passing the value to it construstor String firstName = new String("Musa");
//creating s a string by just initializing it with a value String surname = "Muhammad";
//create an int to hold say age int age = 50;
// create an int to a number int number = 12;
//notice the + sign. It is used to join string objects //ie add more string together. System.out.println(firstName + surname);
//let add space between firstname and surname System.out.println(firstName + " " + surname);
//let add age to number System.out.println(age + number);
//let's print all the variables //watch this output closely //Everything was just appended to each other, if the first argument to the print method is a string //everything will just be treated as string
System.out.println(firstName + surname + age + number);
//Let print a nice looking output
System.out.println(firstName + " "+surname + " "+ "is "+age + " years old and his lucky number is "+ number);
} }
Result:
MusaMohammed Musa Muhammad 62 MusaMohammed5012 Musa Muhammad is 50 years old and his lucky number is 12
Using String could be very tricky in java, because you will need to understand how they are created and manipulated. For example , if we create String objects say to represent Dog and Cat. If we add the two, a third string will be created to hold the value while the original strings are still hanging in memory and holding their references.But when you change the reference, the value still exit in memory and we can not access them due to lack of reference,that's why we have to be very careful when using string because one might end up creating alot unreferenced string object which will just be occupying a chunk of memory.
|