Friday, April 22, 2011

JAVA Programming : Operators

JAVA Operators 

A Operator in Java is a Symbol that manipulates one or more primitive data types (arguments) to produce a result. Operators are very important part of Java programming. Below is the list of Operators available in Java.

OPERATORS
Assignment Operators
=








Arithmetic Operators
-
+
*
/
%
++
--








Relational Operators
> 
< 
>=
<=
==
!=









Logical Operators
&&
||
!












Bit wise Operator
&
|
^
>> 
>>> 










Compound Assignment Operators
+=

-=
*=
/=
%=










Conditional Operator
?:







Assignment Operator: It is the most common and simple operator that is used to assign value on its right to the operand on its left.

Arithmetic Operators: As the name suggest these are the operators that are used for performing arithmetic operations. Java provide seven arithmetic operators add, subtract, multiply, divide, mode (returns remainder), unary increment and unary decrement.

Bit Wise Operators: Bit operator in Java are use to manipulate variables at bit level. It is not recommended to use bit wise operatically in normal application programming because in makes code hard to understand. So, we are not going to discusses bit wise operators in details. In code below we shown how to use these operators.

Compound Operators:- Compound operators provide a short way or syntax to write Arithmetic and Bitwise operators. There are eleven compound operators in Java. 

Below is the Java Code that shows how to use Assignment, Arithmetic, Bit wise and Compound Operator in a program. This Class doesn't actually do anything  in terms of producing result, but it shows you the syntax to use these operators. 


public class Operators {
    public static void main(String arg[]) {

      vv//Assignment Operator
      vvint a = 1;     // a has value 1
        int b = 2;    // b has value 2
        int c = a;    // c gets the value of a i.e 1


        //Arithmetic Operators
        a = b + c;    //Addition
        a = b - c;    //subtraction
        a = b * c;    //Multiply
        a = b / c;    //Division
        a = b % c;    //Mode


        a++;      //Increment a by 1
        a--;      //Decrement a by 1

        //Bit Wise Operators
        a = a << 3;   //Left Shift 
        a = a >> 3;    //Right Shift
        a = a >>> 3;  //Unsigned Right Shift

        a = b & c;     //AND
        a = b | c;    //OR
        a = b ^ c;    //XOR

        a = a + b;  //this is normal + operation
        a += b;    //this is compound operation of above 

        //compound Operators
        a -= b;
        a *= b;
        a /= b;
        a %= b;

        a >>= 3;
        a <<= 3;
        a >>>= 3;

        a &= b;
        a |= b;
        a ^= b;
    }
}


Relational Operator:
Relational Operator in Java are binary operators i.e. they are used to compare two operands. There are six relational operators as shown above. Relational operator in java compare to numaric objects and results in a boolean value.


public class Relational{
   public static void main(String args[]){

     int a = 20, b = 10;

     System.out.println("a > b results in : "+(a > b));
     System.out.println("a < b results in : "+(a < b));
     System.out.println("a >= b 
results in :  "+(a >= b));
     System.out.println("a <= b results in :  "+(a <= b));
     System.out.println("a == b results in :  "+(a == b));
     System.out.println("a != b results in :  "+(a != b));

   }
 }



Logical Operator:
Logical operator evaluates two Java boolean values and gives results in boolean value. There are three logical operator in Java. Below is the code that shows the basics of logical operators.


public class Logical{
   public static void main(String args[]){
     boolean a = true;
     boolean b = false;

     System.out.println("a && b 
results in : (a && b));
     System.out.println("a || b results in : (a || b));
     System.out.println("!a results in : " (!a));
   }
}



Truth table for and or and not operations: Here P and Q are Boolean expressions and T stands for true and F stands for false.
Conditional Operator:
Conditional Operator is a ternary operator in Java which evaluates a expression and returns option1 if result is true else returns option2. Take a Look at the figure below.

public class Conditional {
   public static void main(String args[]){   
     int a=5;
     int b=10;
     int max;

     max= a > b ? a : b ; 
     System.out.println("Max = "+max);
   }
}



Saturday, April 16, 2011

JAVA Programming : Using Scanner for User Input

JAVA Scanner 


As we now know a little bit about Java programming we will start making our first program.  In this tutorial we learn how to get input from user. There are a number of ways for taking input form user in Java and one way is using Scanner. A Scanner class is already built in Java and present in the java.util package. A scanner takes input from various types of Input Streams.

Creating a Scanner Object:
Lets create a scanner object that accepts systems.in as input stream it means that scanner will take input from console. 

Scanner scan = new Scanner(System.in);  // System.in is an InputStream  


A scanner can take various types as input stream for example, here we have a File Reader as input stream that reads data from a file named as MyFile.


Scanner scanfile = new Scanner(new FileReader("MyFile"));           
      

Getting User Input form Console using Scanner : Lets create a class that take two integer input from user and prints their sum. To use the Scanner class, first we need to import it. Take a look at the code :


import java.util.Scanner;

public class UserInput {
  public static void main(String args[]){  
    int second ;
    int first;
    int total;
    Scanner scan = new Scanner(System.in);

    System.out.println("enter 1st no.");
    first = scan.nextInt()//stores user input into first          

    System.out.println("enter 2nd no.");
    second = scan.nextInt()//stores user input into second


    total = first + second ;  //sum of first and second  
    System.out.println("sum = "+ total)
  }
}



In the first line of code, we have an import statement to import Scanner class. Now we can use the Scanner class anywhere in our code. In our class we have three int variables first, second and total. Variable first and second will hold the user input and total will hold their sum.
To take integer input scanner has a method called nextInt. This methods reads the integer input by user. In the above code we have used this method two times and to save user input in int variables first and second.

Output of Program :


Note that if are using nextInt method and the input given is not integer, then compiler will give an error. There are some other methods that are used for different types of input.

Method
Reads
int nextInt()
Reads the next input as an int. If the input is not an integer,InputMismatchException is thrown.
long nextLong()
Reads the next token as a long. If the next token is not an long,InputMismatchException is thrown.
float nextFloat()
Reads the next input as a float. If the input is not a float, InputMismatchException is thrown.
double nextDouble()
Reads the next input as a double. If the input is not a double, InputMismatchException is thrown.
String next()
Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break.
String nextLine()
Reads the rest of the current line, excluding any line separator at the end.
void close()
Closes the scanner.

JAVA Programming : Interface

JAVA Interface 


Interfaces are declared using the interface keyword and they are like a pure abstract class i.e. every method in an Interface is an abstract method. An interface can not be instantiated they can only be implemented by other classes or can be extended by other interfaces.
Implementing a interface by a class is like making a contract that the class will implement all the methods of that interface. If a class does not implement all the methods of an implemented interface, the Java Compiler will give an error.

Syntax of a Interface:-


[access identifier] interface InterfaceName [extends Interface1, Interface2....]
{
     //adstrace method declarations
}



NOTE: Because all methods in an interface is abstract by definition so their is no need to declare them abstract by using abstract keyword.

Declaring a Interface:-
For example, lets create a interface Record which has three methods add, update and delete.


public interface Record {          
    public void add();
    public void update();
    public void delete();
}



Lets create a class Employee that implements the interface Record. Employee class must implement all the methods of Record interface.


public class Employee implements Record {   

  // fields and methods of class


  // methods of Record interface 
  public void add() {
    // set of java statements 
  }
  public void delete() {
    // set of java statements 
  }
  public void update() {
    // set of java statements   
  }

}



Tuesday, April 12, 2011

JAVA Programming : Abstract Class and Abstract Method

JAVA Abstract Classes and Abstract Methods 


Abstract Class: An abstract class is declared using abstract keyword. An abstract class is a class definition that is incomplete in the sense that it has some abstract methods. It is not compulsory that an abstract class has an abstract method but if a class has an abstract method, the class has to be declared as abstract. Abstract classes can never be initiated but they can be subclassed.

Abstract Method: Abstract method are declared using abstract keyword. Abstract methods are defined as part of the class but the inner workings (body of methods) are not provided. Abstract methods ends with semicolon instead of curly brackets. 


   public abstract class Bike {       
       abstract void gear();
       abstract void topSpeed();

   }


Why we need an Abstract Class: This is the question that many people ask about, what is the need of abstract class. The idea behind an abstract class is putting common functionality to an abstract class that other classes will extend.
For example we can have a abstract class named fan with a method for turning the fan on and off but not defining the procedure to do that i.e. with no body declaration. Now we can extend the fan class into table fan and define on and off procedure accordingly or we can extend the fan class to ceiling fan and define on and off procedure according to ceiling fan.

Monday, April 11, 2011

JAVA Programming : Variables and Scope of Variables

JAVA Variables 



A variable in Java is like place holder that can store a value that once declared can be used through out the program according to scope of that variable(discussed below). Datatypes specifies what kind of data each variables will store for example a variable declared as int cannot have char values. 


public class DeclareVariables {

    public static void main(String args[]){  
          int a=7;
          int b=9;
          int sum;
          sum = a+b;
          System.out.println("sum = "+sum);

    }
}



In DeclareVariable class, inside the main method we declared three int variables a, b and sum. Here a and b variables has some value stored and variable sum will have their addition stored in it. Output of this Java program is:


Scope of Variables: Scope of variables is the portion of program where a declared variable can be used. Scope of Variable differ according to the place where the variable is declared. A variable can be declared in various places in a Java Class.
  1. Class Body
  2. Method Body
  3. With in Statement Block
  4. As Parameter or in for loops
First three declared variables will have there scope with in the block (curly brackets) they are declared. The variable declared as parameter or in for loops are declared with in Parentheses and can be used with in the followed statement block. 


public class ScopeOfVariables {

        public static void main(String args[]){           
               for(int a=1; a<=5; a++){
                    System.out.println(a);
               }
        }
}



In above example we have a variable declared in for loop that can used only with in the statement block of that for loop.