Friday, 1 March 2013

Declaration of java variables

This is what you have to know about doing a little bit of simple mathematics using the java programming language. Say we want to write a program that adds up two numbers,5 and 3. There are two approaches to this problem, we can either declare two variables and add the two variables together to get the answer or we can just add the two numbers up at the print statement. lets have a look at how we would do this:

  public class Addition{ 
     public static void main(String[] args){ 
        System.out.println(5 + 3); }
 }

the above solution just adds up the two numbers and prints the result. The calculation is done within the print statement. Now say we want to be able to use 5 and 3 again, maybe for another operation..the following way would be the better way of approaching this problem.

  public class Addition{
       public static void main(String[] args){
              int x = 5; 
              int y = 3; 
              System.out.println(x+y);
           }
 }

 the above solution works much better because if we want to reuse the variables again we will just have to add a println statement that reads:

System.out.println(x-y);

we dont have to write 5-3 agin. so basically thats how you add two integers.

 IMPORTANT INFORMATION 

 declaring integers:

  •  int x= 5; this means an integer value of 5 is stored in a variable called x, integers are numbers with no decimal places.
  •  double x = 5.2; this means a number with a decimal place, eg, 5.2 is stored in a value called x. next java session we will be doing strings.

0 comments:

Post a Comment