Thursday 4 August 2011

java constructor

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube1() {
  length = 10;
  breadth = 10;
  height = 10;
 }
 Cube1(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
 }
 public static void main(String[] args) {
  Cube1 cubeObj1, cubeObj2;
  cubeObj1 = new Cube1();
  cubeObj2 = new Cube1(10, 20, 30);
<font size=-1>
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } }

Download Cube1.java

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Java Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context
public class Cube2 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube2() {
  this(10, 10);
  System.out.println("Finished with Default Constructor");
 }
 Cube2(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having 2 params");
 }
 Cube2(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having 3 params");
 }
 public static void main(String[] args) {
  Cube2 cubeObj1, cubeObj2;
  cubeObj1 = new Cube2();
  cubeObj2 = new Cube2(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
 }
}

public class Cube2 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube2() {
  this(10, 10);
  System.out.println("Finished with Default Constructor");
 }
 Cube2(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having 2 params");
 }
 Cube2(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having 3 params");
 }
 public static void main(String[] args) {
  Cube2 cubeObj1, cubeObj2;
  cubeObj1 = new Cube2();
  cubeObj2 = new Cube2(10, 20, 30);
  System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
 }
}

Output

Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000
Download Cube2.java

Constructor Chaining

Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube() {
  this(10, 10);
  System.out.println("Finished with Default Constructor of Cube");
 }
 Cube(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having
         2 params of Cube");
 }
 Cube(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having
         3 params of Cube");
 }
}

public class SpecialCube extends Cube {

 int weight;
 SpecialCube() {
  super();
  weight = 10;
 }
 SpecialCube(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having
         2 params of SpecialCube");
 }
 SpecialCube(int l, int b, int h) {
  super(l, b, h);
  weight = 20;
  System.out.println("Finished with Parameterized Constructor having
         3 params of SpecialCube");
 }
 public static void main(String[] args) {
  SpecialCube specialObj1 = new SpecialCube();
  SpecialCube specialObj2 = new SpecialCube(10, 20);
  System.out.println("Volume of SpecialCube1 is : "
    + specialObj1.getVolume());
  System.out.println("Weight of SpecialCube1 is : "
    + specialObj1.weight);
  System.out.println("Volume of SpecialCube2 is : "
    + specialObj2.getVolume());
  System.out.println("Weight of SpecialCube2 is : "
    + specialObj2.weight);
 }
}
Download SpecialCube.java
Output
Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20
The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.
Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call.
class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having
        3 params of Cube");
 }
}

public class SpecialCube1 extends Cube {

 int weight;
 SpecialCube1() {
  super(10, 20, 30); //Will Give a Compilation Error without this line
  weight = 10;
 }
 public static void main(String[] args) {
  SpecialCube1 specialObj1 = new SpecialCube1();
  System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume());
 }
}
Output
Finished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000
Download SpecialCube1.java

java classes and objects

Introduction to Java Classes
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.
A class has the following general syntax:
<class modifiers>class<class name>
<extends clause> <implements clause>
{

// Dealing with Classes (Class body)

&lt;br /&gt;&lt;font size=-1&gt;

<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().
public class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
}
How do you reference a data member/function?
This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).

For example:
cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.
Consider this simple Java program showing the use of static fields and static methods
// Class and Object initialization showing the Object Oriented concepts in Java
class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public static int numOfCubes = 0; // static variable
 public static int getNoOfCubes() { //static method
  return numOfCubes;
 }
 public Cube() {
  numOfCubes++; //
 }
}

public class CubeStaticTest {

 public static void main(String args[]) {
  System.out.println("Number of Cube objects = " + Cube.numOfCubes);
  System.out.println("Number of Cube objects = "
    + Cube.getNoOfCubes());
 }
}
Download CubeStaticTest.java
Output
Number of Cube objects = 0
Number of Cube objects = 0

Final Variable, Methods and Classes

In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.
Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.

Introduction to Java Objects

The Object Class is the super class for all classes in Java.
Some of the object class methods are

equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.
Below is an example showing the creation of Cube objects by using the new operator.
public class Cube {

 int length = 10;
 int breadth = 10;
 int height = 10;
 public int getVolume() {
  return (length * breadth * height);
 }
 public static void main(String[] args) {
  Cube cubeObj; // Creates a Cube Reference
  cubeObj = new Cube(); // Creates an Object of Cube
  System.out.println("Volume of Cube is : " + cubeObj.getVolume());
 }
}
Download Cube.java

Method Overloading

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading

public class MethodOverloadDemo {

 void sumOfParams() { // First Version
  System.out.println("No parameters");
 }
 void sumOfParams(int a) { // Second Version
  System.out.println("One parameter: " + a);
 }
 int sumOfParams(int a, int b) { // Third Version
  System.out.println("Two parameters: " + a + " , " + b);
  return a + b;
 }
 double sumOfParams(double a, double b) { // Fourth Version
  System.out.println("Two double parameters: " + a + " , " + b);
  return a + b;
 }
 public static void main(String args[]) {
  MethodOverloadDemo moDemo = new MethodOverloadDemo();
  int intResult;
  double doubleResult;
  moDemo.sumOfParams();
  System.out.println();
  moDemo.sumOfParams(2);
  System.out.println();
  intResult = moDemo.sumOfParams(10, 20);
  System.out.println("Sum is  " + intResult);
  System.out.println();
  doubleResult = moDemo.sumOfParams(1.1, 2.2);
  System.out.println("Sum is  " + doubleResult);
  System.out.println();
 }
}
Download MethodOverloadDemo.java
Output
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30

Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

Below is a code snippet to shows the interfaces that a Class Implements:
Class cls = java.lang.String.class;
Class[] intfs = cls.getInterfaces();
// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]
// The interfaces for a primitive type is an empty array
cls = int.class;
intfs = cls.getInterfaces(); // []
Below is a code snippet to show whether a Class Object Represents a Class or Interface:
Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false

Java Access Specifiers

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.
Access Modifiers
1. private
2. protected
3. default
4. public

public access modifier
Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.
private access modifier
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.
protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

&lt;br /&gt;&lt;font size=-1&gt;
default access modifier
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.
Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers.
The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below.
package pckage1;

class BaseClass {

 public int x = 10;
 private int y = 10;
 protected int z = 10;
 int a = 10; //Implicit Default Access Modifier
 public int getX() {
  return x;
 }
 public void setX(int x) {
  this.x = x;
 }
 private int getY() {
  return y;
 }
 private void setY(int y) {
  this.y = y;
 }
 protected int getZ() {
  return z;
 }
 protected void setZ(int z) {
  this.z = z;
 }
 int getA() {
  return a;
 }
 void setA(int a) {
  this.a = a;
 }
}

public class SubclassInSamePackage extends BaseClass {

 public static void main(String args[]) {
  BaseClass rr = new BaseClass();
  rr.z = 0;
  SubclassInSamePackage subClassObj = new SubclassInSamePackage();
  //Access Modifiers - Public
  System.out.println("Value of x is : " + subClassObj.x);
  subClassObj.setX(20);
  System.out.println("Value of x is : " + subClassObj.x);
  //Access Modifiers - Public
  //     If we remove the comments it would result in a compilaton
  //     error as the fields and methods being accessed are private
  /*     System.out.println("Value of y is : "+subClassObj.y);

   subClassObj.setY(20);

   System.out.println("Value of y is : "+subClassObj.y);*/
  //Access Modifiers - Protected
  System.out.println("Value of z is : " + subClassObj.z);
  subClassObj.setZ(30);
  System.out.println("Value of z is : " + subClassObj.z);
  //Access Modifiers - Default
  System.out.println("Value of x is : " + subClassObj.a);
  subClassObj.setA(20);
  System.out.println("Value of x is : " + subClassObj.a);
 }
}
Output
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20
The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).
import pckage1.*;

public class SubClassInDifferentPackage extends SubclassInSamePackage {

 public int getZZZ() {
  return z;
 }

 public static void main(String args[]) {
  SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage();
  SubclassInSamePackage subClassObj = new SubclassInSamePackage();
  //Access specifiers - Public
  System.out.println("Value of x is : " + subClassObj.x);
  subClassObj.setX(30);
  System.out.println("Value of x is : " + subClassObj.x);
  //Access specifiers - Private
  //      if we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are private
  /*      System.out.println("Value of y is : "+subClassObj.y);

   subClassObj.setY(20);

   System.out.println("Value of y is : "+subClassObj.y);*/
  //Access specifiers - Protected
  //      If we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are protected.
  /*      System.out.println("Value of z is : "+subClassObj.z);

   subClassObj.setZ(30);

   System.out.println("Value of z is : "+subClassObj.z);*/
  System.out.println("Value of z is : " + subClassDiffObj.getZZZ());
  //Access Modifiers - Default
  //      If we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are default.
  /*

   System.out.println("Value of a is : "+subClassObj.a);

   subClassObj.setA(20);

   System.out.println("Value of a is : "+subClassObj.a);*/
 }
}
Output
Value of x is : 10
Value of x is : 30
Value of z is : 10
The third class is ClassInDifferentPackage.java which is present in a different package then the first one.
import pckage1.*;

public class ClassInDifferentPackage {

 public static void main(String args[]) {
  SubclassInSamePackage subClassObj = new SubclassInSamePackage();
  //Access Modifiers - Public
  System.out.println("Value of x is : " + subClassObj.x);
  subClassObj.setX(30);
  System.out.println("Value of x is : " + subClassObj.x);
  //Access Modifiers - Private
  //      If we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are private
  /*      System.out.println("Value of y is : "+subClassObj.y);

   subClassObj.setY(20);

   System.out.println("Value of y is : "+subClassObj.y);*/
  //Access Modifiers - Protected
  //      If we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are protected.
  /*      System.out.println("Value of z is : "+subClassObj.z);

   subClassObj.setZ(30);

   System.out.println("Value of z is : "+subClassObj.z);*/
  //Access Modifiers - Default
  //      If we remove the comments it would result in a compilaton
  //      error as the fields and methods being accessed are default.
  /*      System.out.println("Value of a is : "+subClassObj.a);

   subClassObj.setA(20);

   System.out.println("Value of a is : "+subClassObj.a);*/
 }
}
Output
Value of x is : 10
Value of x is : 30
Download all the 3 source files

java control flow statements

Selection Statements

The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo {

 public static void main(String[] args) {
&lt;font size=-1&gt;
int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
Output
b > a
Download IfStatementDemo.java
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>

Below is an example that demonstrates conditional execution based on if else statement condition.

public class IfElseStatementDemo {

 public static void main(String[] args) {
  int a = 10, b = 20;
  if (a > b) {
   System.out.println("a > b");
  } else {
   System.out.println("b > a");
  }
 }
}
Output
b > a
Download IfElseStatementDemo.java
Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch. Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>

case labeln: <statementn>
default: <statement>
} // end switch

When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {

 public static void main(String[] args) {
  int a = 10, b = 20, c = 30;
  int status = -1;
  if (a > b && a > c) {
   status = 1;
  } else if (b > c) {
   status = 2;
  } else {
   status = 3;
  }
  switch (status) {
  case 1:
   System.out.println("a is the greatest");
   break;
  case 2:
   System.out.println("b is the greatest");
   break;
  case 3:
   System.out.println("c is the greatest");
   break;
  default:
   System.out.println("Cannot be determined");
  }
 }
}
Output
c is the greatest
Download SwitchCaseStatementDemo.java
–~~~~~~~~~~~~–
Control statements control the order of execution in a java program, based on data values and conditional logic.
There are three main categories of control flow statements;
Selection statements: if, if-else and switch.
Loop statements: while, do-while and for.
Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution

Iteration Statements

While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
<statements>

Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10.
public class WhileLoopDemo {

 public static void main(String[] args) {
  int count = 1;
  System.out.println("Printing Numbers from 1 to 10");
  while (count <= 10) {
   System.out.println(count++);
  }
 }
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Download WhileLoopDemo.java
Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop.
The syntax of the do-while loop is
do
<loop body>
while (<loop condition>);

Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.
public class DoWhileLoopDemo {

 public static void main(String[] args) {
  int count = 1;
  System.out.println("Printing Numbers from 1 to 10");
  do {
   System.out.println(count++);
  } while (count <= 10);
 }
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Download DoWhileLoopDemo.java
Below is an example that creates A Fibonacci sequence controlled by a do-while loop
public class Fibonacci {

 public static void main(String args[]) {
  System.out.println("Printing Limited set of Fibonacci Sequence");
  double fib1 = 0;
  double fib2 = 1;
  double temp = 0;
  System.out.println(fib1);
  System.out.println(fib2);
  do {
   temp = fib1 + fib2;
   System.out.println(temp);
   fib1 = fib2; //Replace 2nd with first number
   fib2 = temp; //Replace temp number with 2nd number
  } while (fib2 < 5000);
 }
}
Output
Printing Limited set of Fibonacci Sequence
0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0
89.0
144.0
233.0
377.0
610.0
987.0
1597.0
2584.0
4181.0
6765.0
Download Fibonacci.java
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop.
The syntax of the loop is as follows:
for (<initialization>; <loop condition>; <increment expression>)
<loop body>

The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.
public class ForLoopDemo {

 public static void main(String[] args) {
  System.out.println("Printing Numbers from 1 to 10");
  for (int count = 1; count <= 10; count++) {
   System.out.println(count);
  }
 }
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Download ForLoopDemo.java
–~~~~~~~~~~~~–
Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;
Selection statements: if, if-else and switch.
Loop statements: while, do-while and for.
Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution

Transfer Statements

Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.
public class ContinueExample {

 public static void main(String[] args) {
  System.out.println("Odd Numbers");
  for (int i = 1; i <= 10; ++i) {
   if (i % 2 == 0)
    continue;
   // Rest of loop body skipped when i is even
   System.out.println(i + "\t");
  }
 }
}
Output
Odd Numbers
1
3
5
7
9
Download ContinueExample.java
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops.
The Syntax for break statement is as shown below;
break; // the unlabeled form
break <label>; // the labeled form
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
public class BreakExample {

 public static void main(String[] args) {
  System.out.println("Numbers 1 - 10");
  for (int i = 1;; ++i) {
   if (i == 11)
    break;
   // Rest of loop body skipped when i is even
   System.out.println(i + "\t");
  }
 }
}
Output
Numbers 1 - 10
1
2
3
4
5
6
7
8
9
10
Download BreakExample.java

java operators

Java Operators

They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.
Operators in java fall into 8 different categories:
Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type
.

 Assignment Operators         =

 Arithmetic Operators         -        +        *        /        %        ++        --
 Relational Operators         >        <        >=        <=        ==        !=
&lt;font size=-1&gt;
Logical Operators && || & | ! ^ Bit wise Operator & | ^ >> >>> Compound Assignment Operators += -= *= /= %=
         <<=        >>=     >>>=

 Conditional Operator         ?:
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.


Assignment operators

The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo {

 public AssignmentOperatorsDemo() {
  //         Assigning Primitive Values
  int j, k;
  j = 10; // j gets the value 10.
  j = 5; // j gets the value 5. Previous value is overwritten.
  k = j; // k gets the value 5.
  System.out.println("j is : " + j);
  System.out.println("k is : " + k);
  //         Assigning References
  Integer i1 = new Integer("1");
  Integer i2 = new Integer("2");
  System.out.println("i1 is : " + i1);
  System.out.println("i2 is : " + i2);
  i1 = i2;
  System.out.println("i1 is : " + i1);
  System.out.println("i2 is : " + i2);
  //         Multiple Assignments
  k = j = 10; // (k = (j = 10))
  System.out.println("j is : " + j);
  System.out.println("k is : " + k);
 }
 public static void main(String args[]) {
  new AssignmentOperatorsDemo();
 }
}
Download AssignmentOperatorsDemoSource code

Arithmetic operators

Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.
The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.
String message = 100 + “Messages”; //”100 Messages”
public class ArithmeticOperatorsDemo {

 public ArithmeticOperatorsDemo() {
  int x, y = 10, z = 5;
  x = y + z;
  System.out.println("+ operator resulted in " + x);
  x = y - z;
  System.out.println("- operator resulted in " + x);
  x = y * z;
  System.out.println("* operator resulted in " + x);
  x = y / z;
  System.out.println("/ operator resulted in " + x);
  x = y % z;
  System.out.println("% operator resulted in " + x);
  x = y++;
  System.out.println("Postfix ++ operator resulted in " + x);
  x = ++z;
  System.out.println("Prefix ++ operator resulted in " + x);
  x = -y;
  System.out.println("Unary operator resulted in " + x);
  // Some examples of special Cases
  int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is
  // Integer.MIN_VALUE.
  int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is
  // Integer.MAX_VALUE.
  System.out.println("tooBig becomes " + tooBig);
  System.out.println("tooSmall becomes " + tooSmall);
  System.out.println(4.0 / 0.0); // Prints: Infinity
  System.out.println(-4.0 / 0.0); // Prints: -Infinity
  System.out.println(0.0 / 0.0); // Prints: NaN
  double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value
  // 1.0.
  double d2 = 12.0F / 8; // result: 1.5
  System.out.println("d1 is " + d1);
  System.out.println("d2 iss " + d2);
 }
 public static void main(String args[]) {
  new ArithmeticOperatorsDemo();
 }
}
Download ArithmeticOperatorsDemo Source code

Relational operators

Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java.

 public class RelationalOperatorsDemo {

    public RelationalOperatorsDemo( ) {

      int x = 10, y = 5;
      System.out.println("x > y : "+(x > y));
      System.out.println("x < y : "+(x < y));
      System.out.println("x >= y : "+(x >= y));
      System.out.println("x <= y : "+(x <= y));
      System.out.println("x == y : "+(x == y));
      System.out.println("x != y : "+(x != y));

   }

   public static void main(String args[]){
           new RelationalOperatorsDemo();
   }
 }
Download RelationalOperatorsDemo Source code

Logical operators

Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.
public class LogicalOperatorsDemo {

 public LogicalOperatorsDemo() {
  boolean x = true;
  boolean y = false;
  System.out.println("x & y : " + (x & y));
  System.out.println("x && y : " + (x && y));
  System.out.println("x | y : " + (x | y));
  System.out.println("x || y: " + (x || y));
  System.out.println("x ^ y : " + (x ^ y));
  System.out.println("!x : " + (!x));
 }
 public static void main(String args[]) {
  new LogicalOperatorsDemo();
 }
}
Download LogicalOperatorsDemo Source code
Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.
x
y
!x
x & y
x && y
x | y
x || y
x ^ y
true
true
false
true
true
false
true
false
false
false
true
true
false
true
true
false
true
true
false
false
true
false
false
false

Bitwise operators

Java provides Bit wise operators to manipulate the contents of variables at the bit level.
These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise
operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java.
public class BitwiseOperatorsDemo {

 public BitwiseOperatorsDemo() {
  int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1
  int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
  int z;
  System.out.println("x & y : " + (x & y));
  System.out.println("x | y : " + (x | y));
  System.out.println("x ^ y : " + (x ^ y));
  System.out.println("~x : " + (~x));
  System.out.println("x << y : " + (x << y));
  System.out.println("x >> y : " + (x >> y));
  System.out.println("x >>> y : " + (x >>> y));
  //There is no unsigned left shift operator
 }
 public static void main(String args[]) {
  new BitwiseOperatorsDemo();
 }
}
Download BitwiseOperatorsDemo Source code
The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below.
A
B
~A
A & B
A | B
A ^ B
1
1
0
1
1
0
1
0
0
0
1
1
0
1
1
0
1
1
0
0
1
0
0
0
Output
3,0,3
/*
 * The below program demonstrates bitwise operators keeping in mind operator precedence
 * Operator Precedence starting with the highest is -> |, ^, &
 */

public class BitwisePrecedenceEx {

 public static void main(String[] args) {
  int a = 1 | 2 ^ 3 & 5;
  int b = ((1 | 2) ^ 3) & 5;
  int c = 1 | (2 ^ (3 & 5));
  System.out.print(a + "," + b + "," + c);
 }
}
Downloadad BitwiseOperatorsDemo2 Source code

Compound operators

The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators.
Syntax:
argument1 operator = argument2.
The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.
public class CompoundOperatorsDemo {

 public CompoundOperatorsDemo() {
  int x = 0, y = 5;
  x += 3;
  System.out.println("x : " + x);
  y *= x;
  System.out.println("y :  " + y);
  /*Similarly other operators can be applied as shortcuts. Other 

   compound assignment operators include boolean logical 

   , bitwiseand shift operators*/
 }
 public static void main(String args[]) {
  new CompoundOperatorsDemo();
 }
}
Download CompoundOperatorsDemo Source code

Conditional operators

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
An example program is shown below that demonstrates the Ternary operator in java.
public class TernaryOperatorsDemo {

 public TernaryOperatorsDemo() {
  int x = 10, y = 12, z = 0;
  z = x > y ? x : y;
  System.out.println("z : " + z);
 }
 public static void main(String args[]) {
  new TernaryOperatorsDemo();
 }
}
Download TernaryOperatorsDemo Source code
/*
 * The following programs shows that when no explicit parenthesis is used then the
 conditional operator
 * evaluation is from right to left
 */

public class BooleanEx1 {

 static String m1(boolean b) {
  return b ? "T" : "F";
 }
 public static void main(String[] args) {
  boolean t1 = false ? false : true ? false : true ? false : true;
  boolean t2 = false ? false
    : (true ? false : (true ? false : true));
  boolean t3 = ((false ? false : true) ? false : true) ? false
    : true;
  System.out.println(m1(t1) + m1(t2) + m1(t3));
 }
}
Output
FFT
Download TernaryOperatorsDemo2 Source code
Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified in
the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.
In java Conversions can occur by the following ways:
  • Using a cast operator (explicit promotion)
  • Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
  • A value of one type is assigned to a variable of a different type (assignment promotion)

Operator Precedence

The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.
postfix [] . () expr++ expr–
unary ++expr –expr +expr -expr ! ~
creation/caste new (type)expr
multiplicative * / %
additive + -
shift >> >>>
relational < <= > >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = “op=”

Example
In an operation such as,
result = 4 + 5 * 3
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’ takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one operator over another applies to all the operators.

Relational Operator

In this section we will get the how to display the relational operator. First all of , we have to defined class named "RelationalOperator". To define the value inside of class values of integer type. To assign values of  numbers define the method main is overload method. The method will be assign two argument values of  integer type. Now after to call the method. After that we are going to create one class method  which is return the one by one values. Here in this program we have to create object method which is return the integer type values. So output will be display on the screen by using println() method
Here is the code of this program

import java.io.*;
class RelationalOperator
{
  public static int val1;
  public static int val2;
  public static void main(int val1, int val2)
  {
  val1=val1;
  val2=val2;
  }
  public int Equal()
  {
  if(val1 == val2)
  {
  System.out.println("both are equal");
  }
  if(val1!=val2)
  {
  System.out.println("both are notequal");
  }
  if(val1<val2)
  {
  System.out.println("Value1 is less then values2");
  }
  if(val1 > val2)
  
  {
  System.out.println(val1+" is greater then " + val2);
  }
  return(0);
  }
  
  public static void main(String arg[])
  {
  try{
  RelationalOperator relationalOperator = new RelationalOperator();
  BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the number1");
  relationalOperator.val1= Integer.parseInt(object.readLine());
  System.out.println("Enter the number2");
  relationalOperator.val2= Integer.parseInt(object.readLine());
  int equal=relationalOperator.Equal();

  }
  catch(Exception e){}
  }
}

Arithematic Operation in java

Description of program:
In this section we will get the arithmetic values. First of all, we have to define class named "ArithmaticOperation" . Inside this class we have defined two static variable of  integer type. To assign the value of the numbers define a method main which is overloaded method. This method will take two parameter of integer type. These values will be used in following methods which have declared in this program. Now call the method one by one. To get the values of the two numbers call the overloaded method main() inside main() method. Output will be display on the screen by using println() method of the System class.
Here is the code of this program
import java.io.*;

class ArithmeticOperator {
  public static int num;
  public static int num1;
  public static void main(int num1, int num2){
  num=num1;
  num1=num2;
  }
  public int Addition(){
  return(num+num1);
  }
  public int Subtract(){
  return(num-num1);
  }
  public int Multiply(){
  return(num*num1);
  }
  public int Divide(){
  return(num/num1);
  }
  public static void main(String args[]){
  try{

  ArithmeticOperator arithmeticOperator= new ArithmeticOperator();
  BufferedReader object= new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the Number");
  arithmeticOperator.num=Integer.parseInt(object.readLine());
  arithmeticOperator.num1=Integer.parseInt(object.readLine());
  int addition=arithmeticOperator.Addition();
  int subtract=arithmeticOperator.Subtract();
  int multiply=arithmeticOperator.Multiply();
  int divide=arithmeticOperator.Divide();
  System.out.println("values is num="+ arithmeticOperator.num);
  System.out.println("value is num1="+ arithmeticOperator.num1);
  
  System.out.println("Addtion is="+ arithmeticOperator.Addition());
  System.out.println("Subtruct is="+ arithmeticOperator.Subtract());
  System.out.println("Multiply is="+ arithmeticOperator.Multiply());  
  System.out.println("Divide is="+ arithmeticOperator.Divide());
  }
  catch(Exception e){}
  
  }
  }