Friday, 31 January 2014

Arithmetic Operators


Operator Performs
+ Additon (also used for String concatenation)
- Subtraction
/ Division
* Multiplication
% Gives Remainder
++ Pre or post increment
-- Pre or post decrement

class ArithmeticOperation{
 public static void main(String args[]){
  int operand1 = 30;
  int operand2 = 10;

  System.out.println("Addition of operand1 and operand2 is " + (operand1 + operand2));
  System.out.println("Subtraction of operand1 and operand2 is " + (operand1 - operand2));
  System.out.println("Multiplication of operand1 and operand2 is " + (operand1 * operand2));
  System.out.println("Division of operand1 and operand2 is " + (operand1 / operand2));
  System.out.println("Remainder of operand1 and operand2 is " + (operand1 % operand2));
 }
}

Output
Addition of operand1 and operand2 is 40
Subtraction of operand1 and operand2 is 20
Multiplication of operand1 and operand2 is 300
Division of operand1 and operand2 is 3
Remainder of operand1 and operand2 is 0

Some points to be Noted
1. Multiplication, Division and remainder operators has more priority than Addition and Subtraction operators.

  Example
class ArithmeticPriority{
 public static void main(String args[]){
  int var1 = 10, var2 = 20;
  int result = var1+var2*var1;
  System.out.println(result);
  
  result = var1-var2/var1;
  System.out.println(result);
  
  result = var1+var2%var1;
  System.out.println(result);
 }
}
 
Output
210
8
10

Explanation
    for the Expression
        result = var1+var2*var1
                = 10 + 20*10
                = 10 +200
                = 210

        result = var1-var2/var1
                = 10-20/10
                = 10-2
                = 8

        result = var1+var2%var1
                = 10 + 20 % 10
                = 10 + 0
                = 10

2. Remainder operator always returns the sign of numerator
    Ex:
        5 % 2 = 1
        -5 % 2 = -1

class RemainderEx{
 public static void main(String args[]){
  int var1 = 25, var2 = 10;
  System.out.println(var1%var2);
  
  var1= -25;
  System.out.println(var1%var2);
 }
}

Operators In Java                                                 Arithmetic Operators: ++, --                                                 Home

Operators in Java

An operator is a symbol which perform an operation

An operator is said to be unary, if it performs operation on single operand.
   Ex:
      int a = 10;
      a++;

An operator is said to be binary, if it performs operation on two operands
   Ex:
      int a=10, b=20;
      int c = a-b;

An Operator is said to be ternary if it perform operation on three operands
   Ex:
      int a = 10, b=20, c;
      c= (a>b) ? a : b;

Operators in java are divided into 4 major categories
   Logical
   Bitwise

otheroperators like (assignment, comma, etc.,)

More About primitive types                                                 Arithmetic Operators                                                 Home

More About primitive types

1. sizes Of primitive data types

Data Type Size (in bytes)
byte 1
short 2
int 4
long 8
float 4
double 8
char 2

boolean: The boolean data type has only two possible values: true and false. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

2. If you are using primitive data types as local variables, then you must initialize the variable before using. Other wise compiler will throw error.

Example
class PrimitiveDeclaration{
 public static void main(String args[]){
  int var1;
  System.out.println(var1);
 }
}

When you tries to compile the above program below error thrown

PrimitiveDeclaration.java:5: error: variable var1 might not have been initialized
 System.out.println(var1);
 ^
1 error

3. Assigning data to compatibility types
Java permits to assign a value of one data type to the value of other if types are compatible. I.e, we can assign a data of float to double, byte to int, char to int etc.,

When you assign a character variable to int variable, then int variables store the Uni code of the variable.

Example
class Compatible{
 public static void main(String args[]){
  char charVar = 'a';
  int intCharVar = charVar;
  byte byteVar = 100;
  short shortVar = byteVar;
  int intVar = shortVar;
  long longVar = intVar;
  float floatVar = longVar;
  double doubleVar = floatVar;
  
  System.out.println(charVar);
  System.out.println(intCharVar);
  System.out.println(byteVar);
  System.out.println(shortVar);
  System.out.println(intVar);
  System.out.println(longVar);
  System.out.println(floatVar);
  System.out.println(doubleVar);
 }
}

Output
a
97
100
100
100
100
100.0
100.0

4. If you are trying to assign data of one type to the other incompatible type compiler will throw error.

Example
class Compatible{
 public static void main(String args[]){
  int intVar = 10;
  boolean a = intVar;
 }
}
While compiling you will get the below error

Compatible.java:6: error: incompatible types
 boolean a = floatVar;
 ^
 required: boolean
 found: float
1 error

5. If you want to assign a higher data type value to compatible lower data type, then you should externally cast it, otherwise compiler will throw an error by saying “possible loss of precision”.

Syntax:  
   dataType value1 = (dataType) value2;

class Compatible{
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 }
}

while compiling you will get the below error.

Compatible.java:5: error: possible loss of precision
 char ch = doubleVar;
 ^
 required: char 
 found: double
1 error

To solve the above error, we need to cast explicitly like below

class Compatible{ 
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = (char)doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 } 
}

6. Always assign a value to a float variable by appending “f” to it like below
float floatVar = 10.09f

other wise compiler will throw error.

class Compatible{
 public static void main(String args[]){
  float floatVar = 10.09;
  System.out.println(floatVar);
 }
}

While compiling you will get the below error

Compatible.java:3: error: possible loss of precision
 float floatVar = 10.09;
 ^
 required: float
 found: double
1 error

To solve the above error define the float variable like below
    float floatVar = 10.09f;

Data Types in Java                                                 Operators in Java                                                 Home

Data Types in Java


Java supports mainly two categories of Data Types
     1. Primitive Types
    2. Reference Types

1. Primitive Types
    Java language supports 8 primitive types of data.
    Those are:
        byte, short, int, long
        float, double
        boolean
        char

        byte, short, int and long used to store integer values
        float and double used to store real values.
        Boolean used to store true or false values
        char is used to store single character.

How to define variable

    Syntax:
        dataType variableName = value;

    Example:
       int intVariable = 10;

        Here
            dataType is int
            variableName is intVariable
            value is 10


A variable is a named memory location, which holds a value.

Naming convention to define a variable

1. A variable name must start with a character or underscore

2. Variable name can contain alpha numeric characters

3. varibale names shouldn't be a reserverd or keyword of java

4. By convention a variable name starts with small letter, abd each sub sequent word starts with capital letter.
Ex: noOfChar, mySalary etc.,

Java Keywords
Keyword is a reserved word, which has special meaning defined for it.


abstract continue for New switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while

Note: All keywords are in lower case only

/* Simple Program to Print the variable values */
class DataTypes{
     public static void main(String args[]){
        byte byteVariable = 10;
        short shortVariable = 20;
        int intVariable = 30;
        long longVariable = 40;
        float floatVariable = 10;
        double doubleVariable = 20.123;
        boolean booleanVariable = false;
        char charVariable ='A';
    
        System.out.println("******************************************");
        System.out.println("Value Of byte Variable is " + byteVariable);
        System.out.println("Value Of short Variable is " + shortVariable);
        System.out.println("Value Of int Variable is " + intVariable);
        System.out.println("Value Of long Variable is " + longVariable);
        System.out.println("Value Of float Variable is " + floatVariable);
        System.out.println("Value Of double Variable is " + doubleVariable);
        System.out.println("Value Of boolean Variable is " + booleanVariable);
        System.out.println("Value Of char Variable is " + charVariable);
        System.out.println("******************************************");
     }
 }

Output
******************************************
Value Of byte Variable is 10
Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 40
Value Of float Variable is 10.0
Value Of double Variable is 20.123
Value Of boolean Variable is false
Value Of char Variable is A
******************************************

Reference Types
In java Strings, Arrays and Objects are considered to be reference types. Will discuss more about these in later posts.

Some Points to Remember

1. Like many other languages Java doesn't support unsigned numbers. There is no unsigned specifier in Java

class UnsignedEx{
 unsigned int a;
}

When you try to compile the above class, below error is thrown.

UnsignedEx.java:2: error: <identifier> expected
   unsigned int a;
    ^
UnsignedEx.java:2: error: <identifier> expected
   unsigned int a;
   ^
2 errors

2. In java all the bytes, shorts are promoted to int before performing operations on them, So we need to explicitly cast them.

class ConversionEx{
    public static void main(String args[]){
        byte b1 = 1;
        byte b2 = 2;
        byte b = (b1 + b2);
    
        System.out.println(b);

        short s1 = 1;
        short s2 = 2;
        short s = (s1 + s2);
    
        System.out.println(s);
    }
}

  When you tries to compile the above program, compiler throws the below error

ConversionEx.java:6: error: possible loss of precision
 byte b = (b1 + b2);
 ^
 required: byte
 found:    int

ConversionEx.java:10: error: possible loss of precision
 short s = (s1 + s2);
 ^
 required: short
 found:    int
2 errors
 
To make the program compiles fine, we need to explicitly cast, after performing the operation

class ConversionEx{
    public static void main(String args[]){
        byte b1 = 1;
        byte b2 = 2;
        byte b = (byte)(b1 + b2);
        System.out.println(b);
        
        short s1 = 1;
        short s2 = 2;
        short s = (short)(s1 + s2);
        System.out.println(s);
    }
}
 
Output
3
3


3. In Java, if one of the operand is double, then other also promoted as double, and the final result will be double

Example

 class ConversionEx{
    public static void main(String args[]){
        float f1 = 1.1f;
        double f2 = 1.2f;
        float f = (f1 + f2);
        System.out.println(f);
    }
}


When you tries to compile the above program, compiler throws the below error

   ConversionEx.java:6: error: possible loss of precision
      float f = (f1 + f2);
      ^
      required: float
      found: double
1 error

To make the program run, cast the result to float.
class ConversionEx{
    public static void main(String args[]){
        float f1 = 1.1f;
        double f2 = 1.2f;
        float f = (float)(f1 + f2);
        System.out.println(f);
    }
}
  
Output
2.3000002



Hello World Application                                                 More About primitive types                                                 Home