Showing posts with label JAVA Basics Part 3. Show all posts
Showing posts with label JAVA Basics Part 3. Show all posts

Wednesday, July 4, 2012

JAVA Basics13: Java Variables and Arithmetic Expressions

Java Variables are used to store data. Variables have type, name, and value. Variable names begin with a character, such as x, D, Y, z. Other examples are xy1, abc2, Count, N, sum, Sum, product etc. These are all variable names.

Different variable types are int, char, double. A variable type tells you what kind of data can be stored in that variable.

The syntax of assignment statements is easy. Assignment statements look like this:

variableName = expression ;

For example:

int x; // This means variable x can store numbers such as 2, 10, -5.

char y; // This means variable y can store single characters 'a', 'A'.

double z; // This means variable z can store real numbers such as
10.45, 3.13411.

The above are declarations for variables x, y and z.

Important points:

1. Note that a variable has to be declared before being used.

2. The values assigned to a variable correspond to its type. Statements below represent assignment of values to a variable.

x = 100; // x is an integer variable.
y = 'A'; // y is a character variable.
abc = 10.45; // abc is of type double (real numbers).

3. Both variable declaration and assignment of values can be done in same statement. For example,

int x;
x = 100; is same as int x = 100;

4. A variable is declared only once.

int x; // Declaration for x.
x = 100; // Initialization.
x = x + 12; // Using x in an assignment statement.
Often in a program you want to give a variable, a constant value. This can be done:

class ConstDemo
{
public static void main ( String[] arg )
{
      final double PI = 3.14;
      final double CONSTANT2 = 100;
. . . . . .
}
}
The reserved word final tells the compiler that the value will not change. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of the language.)
2. Arithmetic Expressions
--------------------------
An assignment statement or expression changes the value that is held in a variable. Here is a program that uses an assignment statement:

class example
{
        public static void main ( String[] args )
{
        long x ; //a declaration without an initial value

        x = 123; //an assignment statement
        System.out.println("The variable x contains: " + x );
}
}


Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %. The % operator is the remainder or modulo operator. Arithmetic expressions are used to assign arithmetic values to variables. An expression is a combination of literals, operators, variables, and parentheses used to calculate a value.

The following code describes the use of different arithmetic expressions.

int x, y, z; // Three integer variables declared at the same time.

x = 10;
y = 12;
z = y / x; // z is assigned the value of y divided by x.
// Here z will have value 1.

z = x + y; // z is assigned the value of x+y                                     // Here z will have value 22.

z = y % x // z is assigned the value of remainder when y         // is divided by x. Here z will have value 2.

Java Boolean expressions are expressions which are either true or false. The different boolean operators are < (less than), > (greater than),
== (equal to), >= (greater or equal to), <= (less or equal), != (not equal to).

Example:

int x = 10;
int y = 4;
int z = 5;

(x < 10) // This expression checks if x is less than 10.

(y > 1) // This expression checks if y is greater than 1.

((x - y) == (z + 1)); // This expression checks
// if (x - y) equals (z + 1).

A boolean expression can also be a combination of other boolean expressions. Two or more boolean expressions can be connected using &&
(logical AND) and || (logical OR) operators.

The && operator represents logical AND. The expression is true only if both boolean expressions are true. The || operator represents logical
OR. This expression would be true if any one of the associated expressions is true.

Example:

int x = 10; int y = 4; int z = 5;

(x <= 10) && (y > 1) // This expression checks if x is less
// than 10 AND y is greater than 1.
// This expression is TRUE.

(x*y == 41) || (z == 5) // This expression checks if x*y is equal
// to 40 OR if z is equal to 5.
// This expression is FALSE


JAVA Basics 12: Java Loops (while, do-while and for loops)


A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may look like:
 
while there's more data {
  Read a Line of Data
  Do Something with the Data
}
There are many different kinds of loops in Java including whilefor, and do while loops. They differ primarily in the stopping conditions used.
For loops typically iterate a fixed number of times and then exit. While loops iterate continuously until a particular condition is met. You usually do not know in advance how many times a while loop will loop.
In this case we want to write a loop that will print each of the command line arguments in succession, starting with the first one. We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using theargs.length. Therefore we will write this with a for loop. Here's the code:
Source Code
// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      int i;
    
      /* Now let's say hello */
      System.out.print("Hello ");
      for (i=0; i < args.length; i = i++) {
        System.out.print(args[i]);
        System.out.print(" ");
      }
      System.out.println();
  }

}
We begin the code by declaring our variables. In this case we have exactly one variable, the integer i. i
Then we begin the program by saying "Hello" just like before.
Next comes the for loop. The loop begins by initializing the counter variable i to be zero. This happens exactly once at the beginning of the loop. Programming tradition that dates back to Fortran insists that loop indices be named ijklm and n in that order.
Next is the test condition. In this case we test that i is less than the number of arguments. When i becomes equal to the number of arguments, (args.length) we exit the loop and go to the first statement after the loop's closing brace. You might think that we should test for i being less than or equal to the number of arguments; but remember that we began counting at zero, not one.
Finally we have the increment step, i++ (i=i+1). This is executed at the end of each iteration of the loop. Without this we'd continue to loop forever since i would always be less than args.length.

JAVA basics 11:Java If-Else Statement


The if-else class of statements should have the following form:

if (condition) {
statements;
}

if (condition) {
statements;
} else {
statements;
}

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
All programming languages have some form of an if statement that allows you to test conditions. All arrays have lengths and we can access that length by referencing the variable arrayname.length.  We test the length of the args array as follows:
Source Code
// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length > 0) {
        System.out.println(args[0]);
      }
  }

}
Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.
What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively.
Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality. Lets look at an example when there are more then 1 statement in a branch and how braces are used indefinitely.
Source Code
import java.io.*;
class NumberTest
{
 public static void main (String[] args) throws IOException
 {
  BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );

  String inS;
  int num;

  System.out.println("Enter an integer number");
  inS = stdin.readLine();
  num = Integer.parseInt( inS ); // convert inS to int using wrapper classes

  if ( num < 0 )  // true-branch
  {
       System.out.println("The number " + num + " is negative");
     System.out.println("negative number are less than zero"); 
  }
  else   // false-branch
  {
     System.out.println("The number " + num + " is positive");
     System.out.print ("positive numbers are greater ");
     System.out.println("or equal to zero ");
  }
  System.out.println("End of program"); // always executed
 }
}
        
All conditional statements in Java require boolean values, and that's what the ==, <, >, <=, and >= operators all return. A boolean is a value that is either true or false. Unlike in C booleans are not the same as ints, and ints and booleans cannot be cast back and forth. If you need to set a boolean variable in a Java program, you have to use the constants true and falsefalse is not 0 and true is not non-zero as in C. Boolean values are no more integers than are strings.
Lets look at some examples of if-else:

//Example 1
if(a == b) {
c++; 
}
if(a != b) {
c--;
}

//Example 2
if(a == b) {
c++; 
}
else {
c--;
}

We could add an else statement like so:
Source Code
// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length > 0) {
        System.out.println(args[0]);
      }
      else {
        System.out.println("whoever you are");
      }
  }

}
Source Code
public class divisor
{
public static void main(String[] args)
         int a = 10;
         int b = 2;
         if ( a % b == 0 )
         {
               System.out.println(a + " is divisible by "+ b);
         }
         else
         {
               System.out.println(a + " is not divisible by " + b);
         }
}
Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Rusty works, but if we type java Hello Elliotte Rusty Harold, Java still only prints Hello Elliotte. Let's fix that.
We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities. 
Lets look at some examples of if-else-if:

//Example 1
if(color == BLUE)) {
System.out.println("The color is blue.");
}
else if(color == GREEN) {
System.out.println("The color is green.");
}

//Example 2
if(employee.isManager()) {
System.out.println("Is a Manager");
}
else if(employee.isVicePresident()) {
System.out.println("Is a Vice-President");
}
else {
System.out.println("Is a Worker");
}

Source Code
// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      if (args.length == 0) {
        System.out.print("whoever you are");
      }
      else if (args.length == 1) {
        System.out.println(args[0]);
      }
      else if (args.length == 2) {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
      }      
      else if (args.length == 3) {
        System.out.print(args[0]);
        System.out.print(" ");
        System.out.print(args[1]);
        System.out.print(" ");
        System.out.print(args[2]);
      }      
        System.out.println();
  }
}