Java Basics

Basic Syntax

The basic syntax of java is some key points, applicable on all java programs, which you need to remember and implement according to syntax :
Case Sensitiveness of Java
Java is case sensitive means it differentiate between same words but having different cases i.e. upper case and lower case. For example : 'Love' and 'love' are different words in java.
Class name Convention :
According to java convention, the first letter of program's name should be in upper case. All other letters can be in any case. The rule is not strictly applied , but you have to follow the convention for better implementation. The program also runs if your program name starts with lower case letter.
See the below example, the program name starts with upper case but it also run if your program name start with upper case :
public class Hello{

   /* by the convention, program name starts with 'H'.
    * This will print 'Welcome in java world' as the output
    */

    public static void main(String []args){
       System.out.println("Welcome in java world"); // prints Hello World
    }
} 
Method naming Convention :
According to java convention, the first letter of the method name start with lower case. The rule is not strictly applied , but you have to follow the convention for better implementation. The program also runs if your method name starts with lower case letter.
Name of the program file :
Name of the program file must be the same as class name. The letters should exactly match. For example, the upper given example should be save in a file as 'Hello.java'. The spelling, upper case letters, lower case letters must be the same. If you will not follow this, the compiler give you a error message.
public static void main(String args[])
The processing of java program starts with main( ).it is a mandatory for every java program. Without it program will not compile successfully.

Objects, Classes and Examples

Objects & Classes

ObjectsObject is the instance of the class which have 'behavior' and 'states' or we can say 'properties' in other words. For example, lion has states like color, breed etc and also have behaviors like-growling, roaring etc.
ClassA class is a template/blue print for defining the behavior and states of the objects.
Java Objects
If you look around, you will find many live example of objects like humans, bikes, cars, dogs etc.
Humans can have many states like name, complexion, nationality etc and the behaviors like talking, walking etc.
Java objects have very similar characteristics like real word objects having a state and behavior. A java object's behavior is shown via methods and it's state is stored in fields.
Object to object communication is done through methods and methods operates on object's internal state.
Java Classes
The classes in java act like blue print for making objects :
Given below a sample class :
public class MainClass {

  private int aField;

  

  public void aMethod() {}

  }
Creating an Object
As mention above an object is created from a class. The object is created in java using 'new' keyword.
You can create an object as follows :
Mainclass mc=new Mainclass( );
You can access instance variable and method as follows :
mc.firstnumber;
mc.add();

Example :

Given below complete example with output snap :
Mainclass.java
package corejava;

public class Mainclass {
 int myage;

 public Mainclass(String name) {
  // This constructor has one parameter, name.
  System.out.println("Name :" + name);
 }

 void setAge(int age) {
  myage = age;
 }

 int getAge() {
  System.out.println("Age :" + myage);
  return myage;
 }

 public static void main(String[] args) {
  /* Object creation */
  Mainclass mc = new Mainclass("Ankit");

  /* Call class method to set age */
  mc.setAge(24);

  /* Call another class method to get age */
  mc.getAge();

  /* You can access instance variable as follows as well */
  System.out.println("Fetched Value via object :" + mc.myage);
 }
}
 

Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Mainclass.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Mainclass

Name :Ankit
Age :24


Java object example, How to create object in java.

Description:
In this example, we will see how to create a object in java. An object is a main feature of object oriented programming concept. It is an instance variable of class or real-world entity. We can declare a object by using new operator. The new operator dynamically allocate memory of object and returns a reference for object.
Here, a ObjectExample class is a supper class of ObjectDemo class. Subclass has main method, and also supper class has a show() method. Which is use for displaying a string "Hello java.". The obDemo is a object of supper class.

Syntax

ClassName object=new ClassName();
ClassName object
(Reference of object)
ClassName object=new ClassName();
(allocation)

Code:

ObjectDemo.java
package com.devmanuals;
class ObjectExample {
        public void show() {
                System.out.println("Hello java.");
        }
}
public class ObjectDemo {
        public static void main(String[] arg) {
                ObjectExample obDemo = new ObjectExample();
                obDemo.show();
        }
}

Output:

Hello java.

Java object reference variable.

In this example, you will see how to create reference variable of object. Object reference variable holds object of class. Here, obExample1 is a reference variable of ObjectExample1 class. It points to the object of ObjectExample1 class. Both object and reference variable of ObjectExample1  works same.
Code:
package com.devmanuals;
class ObjectExample1
{
int num=4 ;
public void square()
{
System.out.println("Square of integer."+(num*num));     }}
public class ObjReferenceVariable {
        public static void main(String[] arg)
        {       ObjectExample1 obExample=new ObjectExample1();
                ObjectExample1 obExample1=obExample;
                obExample.square();
                obExample1.square();            
        }
}
Output:
Square of integer.16
Square of integer.16 


Java class example, Create a simple class in java.

In this example, you will see how to create class in java. A class contains both member data and function. It defines the behavior of object. The class keyword is used for declaration a class. Name of the class will be start with capital letter and  if any word is used in the class name then the first latter of this word will be capital like "JavaClassExample". The JavaClassExample is a name of class. This class also have a main method, and a for loop. This program display number from 0 to 10.
Code:
package com.devmanuals;
public class JavaClassExample {
public static void main(String[] arg)
     {
        for (int i = 0; i <10; i++) {
        System.out.println("Nuber is : "+1);
        }
     }
}
Output:
Nuber is : 0
Nuber is : 1
Nuber is : 2
Nuber is : 3
Nuber is : 4
Nuber is : 5
Nuber is : 6
Nuber is : 7
Nuber is : 8
Nuber is : 9


How to calculate factorial of a number in java.

In this example, we will see how to calculate factorial of number in java. First of all, we will define a supper class FactorialDemo and a JavaFactorialClass subclass. Supper class has two integer type variable num and fact. It also has a function name factorial(), which calculate factorial of number.

Code:
package com.devmanuals;
class FactorialDemo {
        int num = 5;
        int fact = 1;
public void factorial() {
        for (int i = 1; i <= num; i++) {
                fact = fact * i;
                }
        System.out.println("Number is: " + num);
        System.out.println("Factorial of number : " + fact);
     }
}
public class JavaFactorialClass {
public static void main(String[] arg) {
        FactorialDemo obFactorialDemo = new FactorialDemo();
        obFactorialDemo.factorial();
        }
}
Output:
Number is: 5
Factorial of number : 120

 

Basic Data Types

When variables declared, system reserved some space to store value .
In Java there are two data types :
1.Primitive Data types.
2.Refrence Data types.

Primitive Data Type

Java support 8 primitive data types, they are predefined and all of these have predefined keywords. Eight data types are as follows :
byte
  • Byte is a 8 bit data type
  • It's range is -128 to 127.
  • It's default value is zero.
  • It is the smallest java integer type. Byte is four times smaller than an int.
  • Example : byte x = 90, byte y =- 60.
short
  • Short is 16 bit signed type.
  • It's range is 32,768 to 32,767.
  • Default value is 0.
  • Short is 2 times smaller than an int.
  • Example :short s= 20000 , short r = -30000
int
  • Int is a 32-bit data type.
  • It's range is from 2,147,483,648 to 2,147,483,647.
  • For integral value int is generally used.
  • Default value is 0.
  • Example : int a = 200000, int b = -300000.
long
  • Long is 64 bit data type.
  • It's range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
  • Long is used where we need to store a wider range data than int.
  • It's default value is 0L.
  • Example : int a = 100000L, int b = -200000L.
double
  • Double is used ,when fractional precision calculation is required.
  • It is 64 bit double precision data type.
  • It's default value is Default value is 0.0d.
  • Example : double d = 123.4.
float
  • float is 32 bit single precision type.
  • It is used when fractional precision calculation is required.
  • Default value is 0.0f.
  • Example : float f1 = 234.5f.
Boolean
  • When we need to represent one bit of information, we use Boolean data type.
  • It takes two values true and false.
  • It is generally used where we need to track true/false conditions.
  • Default value is false.
  • Example : Boolean one = true.
char
  • char is 16 bit type and used to represent Unicode characters.
  • Range of char is 0 to 65,536.
  • Example . char letter ='A' .
Reference Data Types :
  • Reference data types or objects are created using class constructors. It's type can't be changed after declaration.
  • Default value of any reference variable is null.
  • A reference variable can be used to refer to any object of the declared type or any compatible type.
  • Example : Mainclass mc = new Mainclass("Ankit") . 

Java Variable Types

In Java all variable must be declared before it will be used anywhere in the program. The declaration syntax is as follows :
type identifier [ = value][, identifier [= value] ...] ;
Here 'type' is data type and 'identifier' is the variable name.
Java have following types of variable :
  • Local variables
  • Instance variables
  • Class/static variables

Local Variables

  • The variables which are declared inside methods, constructors, or blocks are known as local variables.
  • These variables have local scope i.e. it can't be access outside the program.
  • Need initial value assignment before use.
  • Access modifiers cannot be used for local variables.
Given below the sample code :
Main.java
package corejava;
public class Main {
        public void Age() {
                int age = 0;
                age = age + 7;
                System.out.println("Age: " + age);
        }

        public static void main(String args[]) {
                Main m = new Main();
                m.Age();
        }
}
In the above code 'age' is the local variable. The scope of this local variable is limited to method 'Age'.
Output
C:\Program Files\Java\jdk1.6.0_18\bin>javac Main.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Main

Age: 7

Instance Variables

  • This method declared outside methods, constructors, or blocks .
  • When memory is allocated for object, the space slot for each instance variable value is created.
  • Instance variable created and destroyed with the creation and destruction of object.
  • More than one method , constructor or block can refer to the values hold by instance variable.
  • Access modifiers can be given for instance variables.
  • The default value of instance variable for numbers is 0, for Boolean it is false, and for object references it is null.
  • Inside class , you can access variable by calling variable name directly without using any object reference. But within static methods and different class, it should be called using object reference as : ObjectReference.VariableName
Example :
In the given below example, variable 'name' is instance variable :
public class Student {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Student class only.
private int marks;
// The name variable is assigned in the constructor.
public Student(String StudName) {
name = StudName;
}
// The marks variable is assigned a value.
public void setMarks(int studMarks) {
marks = studMarks;
}
// This method prints the student's details.
public void printStud() {
System.out.println("Student name : " + name);
System.out.println("Marks :" + marks);
}
public static void main(String args[]) {
Student st = new Student("Divya");
st.setMarks(80);
st.printStud();
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Student.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Student

Student name : Divya
Marks :80

Class/Static Variable

  • Class variable also declared outside a method, constructor or a block with a 'static' keyword.
  • Class variable has only one copy for each class, regardless of how many objects are created from it.
  • Static variables are generally used as constant. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.
  • Class variable is created when program starts and ends with the program.
  • It has same default values as instance variable.
  • Static can only be accessed by using it's fully qualified name as : ClassName.VariableName
  • If you are declaring class variable as public static final, then variable(constant) should be in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.
Example :
College.java
package net.roseindia;
public class College {
        // salary variable is a private static variable
        private static int resultPercent;

        // DEPARTMENT is a constant
        public static final String BRANCH = "Computer Science";

        public static void main(String args[]) {
                resultPercent = 76;
                System.out.println(BRANCH + " Result %:" + resultPercent);
        }
}

Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac College .java

C:\Program Files\Java\jdk1.6.0_18\bin>java College

Computer Science Result %: 76


How to declare static variable in java.

In this java code, you will see how to declare a static variable in java. It is also called class variable in java. The "static" keyword is used for declaring a variable as class or static variable. In our program, there are two classes VariableDemo and StaticVariableDemo1. In supper class, there are  two static or class variable num and num1.
Code:
StaticVariableDemo1.java
package com.devmanuals;
class VariableDemo {
        static int num;
        static int num1;
}
public class StaticVariableDemo1 {
public static void main(String[] args) {
        VariableDemo.num = 22;
        VariableDemo.num1 = 12;
        System.out.println("Value of first static/class variable : "
                        + VariableDemo.num);
        System.out.println("Value of second static/class variable : "
                        + VariableDemo.num1);
        }
}
Output:
Value of first static/class variable : 22
Value of second static/class variable : 12

Example of static variable in java.

In this java code,  you will see how to all instance of a class share the same copy of static variable. There are two java classes in our program one DemoStatic and another SameCopyDemo. The DemoStatic class has two variable one class variable and other instance variable. There are two object of DemoStatic class in SameCopyDemo class. Setter and getter method is used for setting and getting value of variables. When we access value of instance variable they returns different value, but static variable returns same value.
Code:
SameCopyDemo.java
package com.devmanuals;
class DemoStatic {
        static int num1 = 0; // static/class variable
        int num = 0; // non-static/instance variable
        public int getNum1() {
                return num1;
        }
        public void setNum1(int num1) {
                DemoStatic.num1 = num1;
        }
        public int getNum() {
                return num;
        }
        public void setNum(int num) {
                this.num = num;
        }
}
class SameCopyDemo{
        public static void main(String[] arg) {
                DemoStatic obDemoStatic = new DemoStatic();
                DemoStatic obDemoStatic2 = new DemoStatic();

                obDemoStatic.setNum1(2);
                obDemoStatic2.setNum1(3);
                // Each object has same copy of static variable.
                System.out.println("Static variable value for first object : "
                                + obDemoStatic.num1);
                System.out.println("Static variable value for second object : "
                                + obDemoStatic2.num1);

                obDemoStatic.setNum(9);
                obDemoStatic2.setNum(10);
                
                // Each object has separate copy of instance variable
                System.out.println("Instance variable value for first object : "
                                + obDemoStatic.getNum());
                System.out.println("Instance variable value for second object : "
                                + obDemoStatic2.getNum());
        }
}
Output:
Static variable value for first object : 3
Static variable value for second object : 3
Instance variable value for first object : 9
Instance variable value for second object : 10

Change value of static variable by method.

In this example, you will see how to change value of static variable through method.
Code:
InitializeByMethod.java
package com.devmanuals;
class StaticDemo {
        static String name;
public static void staticVariable() {
        name = name + " " + "Singh";
        System.out.println("Value of static variable after method calling : "
                + name);
        }
}
public class InitializeByMethod {
public static void main(String[] args) {
        System.out.println("Initial value of static variable : "
                        + StaticDemo.name);
        StaticDemo.name = "Bharat";
        System.out.println("Value of static variable after initialization : "
                        + StaticDemo.name);
        StaticDemo.staticVariable();
        }
}
Output:
Initial value of static variable : null
Value of static variable after initialization : Bharat
Value of static variable after method calling : Bharat Singh

How to declare local variables in java.

In this example, you will see how to declare a local variable in java. For declaring local variables, we does not require a special keyword. It is same as instance variable, but It can be declare within method or constructer. In our program, there are two classes LocalDemo and LocalVariables. The LocalDemo class has a method name showVariable(). The showVariable() method has a variable name num, it is a local variable.
Code:
LocalVariables.java
package com.devmanuals;
class LocalDemo {
        public void showVariable() {
                int num = 22;
                System.out.println("Value of local variable : " + num);
        }
}
public class LocalVariables {

        public static void main(String[] args) {
                LocalDemo obLocalDemo = new LocalDemo();
                obLocalDemo.showVariable();
        }
}
Output:
Value of local variable : 22

Java local variable initialization.

In this example,. you will see how to initialization of local variable in java.
Note--Local variable initialization is compulsory. because it does not support any default value.
Code:
LocalVariables.java
package com.devmanuals;
class InitializeDemo {
        public void sum() {
                int num = 6;
                int num1 = 5;
                System.out.println("Sum of two number : " + (num + num1));
        }
        public void show() {
                try {
                        String name;
                        name = name + " ";
                        System.out.println();
                } catch (Exception e) {
                        System.out.println(e.getMessage());
                }
        }
}
public class LocalVariableInitialization {

        public static void main(String[] args) {
                InitializeDemo obInitializeDemo = new InitializeDemo();
                obInitializeDemo.sum();
                obInitializeDemo.show();
        }
}
Output:
Sum of two number : 11

The local variable name may not have been initialized

How to declare instance variable in java.

In this example, you will see how to declare a instance variable in java. There are two classes in our program. There are two two instance variable num and num1 in InstanceDemo class. Instance variable supports default value. There are also two method sum() and division().
Code:

LocalVariables.java
package com.devmanuals;
class InstanceDemo {
        int num = 10;
        int num1 = 20;
        public void sum() {
        System.out.println("Sum of two instance variable : " + (num + num1));
        }
        public void division() {
        System.out.println("Division of two instance variable : "
                + (num1 / num));
        }
}
public class InstanceVariable {
public static void main(String[] args) {
        InstanceDemo obDemo = new InstanceDemo();
        obDemo.sum();
        obDemo.division();
        }
}
Output:
Sum of two instance variable : 30
Division of two instance variable : 2


Java Modifier Types

A modifier is a keyword placed in a class, method or variable declaration that changes how it operates.
Java has long list of modifiers. Given below the two categories of access modifier :
  • Java Access Modifier
  • Non Access Modifier
Java Access Modifier
Java has a number of access modifier to control access for classes, variables, methods and constructors. Following are the four types :
  • default - No need of access modifier, It is automatically visible to the package.
  • private - It is used to set the visibility to class level.
  • public - for setting visibility inside and outside package.
  • protected - for setting visibility to the package and all subclasses 

Non Access Modifiers :

  • Java has a variety of non access modifier, some are given below :
  • The static modifier is used to create static class methods and variables.
  • The final modifier is used to prevent variables from being modified. It behaves like constant. It is also used to prevent overloading and inheritance.
  • The abstract modifier is used to create abstract classes and methods.
  • The synchronized and volatile modifiers are used for threads.

    Private modifiers in java.

    In this tutorial, you will see how to declare a private variable and accessibility of  private modifiers. The  "private" keyword is used for declaring a variable private, before the data type. All the private variable can be access within class. They can not be access outside of class.
    Code:

    LocalVariables.java
    package com.devmanuals;
    class ModifiresDemo {
            private String firstName = "Bharat";
            private String lastName = "Singh";
    public void privateVariable() {
            System.out.println("Value of private variable :" + firstName);
            System.out.println("Value of private variable :" + lastName);
            }
    }
    public class PrivateModifires {
            public static void main(String[] args) {
            ModifiresDemo obModifires = new ModifiresDemo();
            obModifires.privateVariable();
            }
    }
    Output:
    Value of private variable :Bharat
    Value of private variable :Singh


public modifier within class .

In this example, you will see how to create a public variable within a class in java. We will use public modifiers for declaring a variable as public. The PublecModifiers is a class in our program. It  has a public variable "name". This public variable can be access within class or out side the class. Here main method in PublicModifierClass has  access and display the value of public variable.
Note-- Public variable can be access within class or outside the class.
Code:

PublicModifiers.java
package com.devmanuals;
public class PublicModifiers {
        public static String name = "Bharat Singh";

        public static void main(String[] arg) {
                System.out.println("Use of public modifierds within class.");
                System.out.println("Public string name : " + name);
        }
}
Output:
Use of public modifierds within class.
Public string name : Bharat Singh

Use of public modifiers in super class.

In this example, you will see that the public variable can be access in sub class. There are two class  SuperDemo and PublicInSuperClass in our program. The SuperDemo class has a public variable firstName. That can we access outside the class. The PublicInSuperClass  class has a object of SuperDemo. That is used for accessing variables of supper class. By using '.' dot operator, you can access value of public variable. That is the code obSuperDemo.firstName has access and display the value of variable.
Note-- Public variable can be access outside the class.
Code:

PublicModifiers.java
package com.devmanuals;
class SuperDemo {
        public String firstName = "Bharat";
}
public class PublicInSuperClass {
        public static void main(String[] args) {
                String lastName = "Singh";
                SuperDemo obSuperDemo = new SuperDemo();
                System.out.println("Value of super class variables : "
                                + obSuperDemo.firstName);
                obSuperDemo.firstName = obSuperDemo.firstName + " " + lastName;
                System.out.println("Full name : " + obSuperDemo.firstName);     
        }
}
Output:
Value of super class variables : Bharat
Full name : Bharat Singh

public modifier within package.

With the help of this example, you will see that the public variable can be access in same package. There are two different  class in same package. These two class are  FirstClass and SecondClass. There is a public variable firstName in FirstClass.
Code:
FirstClass.java
package devmanuals.com;
public class Firstclass {
        public String firstName = "Bharat";
}
SecondClass.java
package devmanuals.com;
public class SecondClass  {

                public static void main(String[] args) {
                Firstclass obDemo=new Firstclass();
                System.out
                        .println("Accessibility of public variable with in package : ");
                System.out
                        .println("Access value of first name from FirstClass : "
                                        + obDemo.firstName);
                }
        }
Output:
Accessibility of public variable with in package :
Access value of first name from FirstClass : Bharat



Basic Operators in Java

Operators are special characters within the Java language that perform operations on arguments to return a specific result. Some of the types of basic operators are given below :
  • Arithmetic Operators
  • Relational Operators
  • Bitwise Operators
  • Boolean Logical Operators
Arithmetic Operators
In java, arithmetic operators have the same use as in algebra.  Given below table consist of list of arithmetic operators :
Operator  Result
        + Addition
        -  Subtraction (also unary minus)
       * Multiplication
        / Division
       % Modulus
      ++ Increment
      += Addition assignment
      -= Subtraction assignment
     *= Multiplication assignment
      /= Division assignment
     %= Modulus assignment
      -- Decrement
Bitwise Operators
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following  :
Operator Result
       ~ Bitwise unary NOT
      & Bitwise AND
       | Bitwise OR
      ^ Bitwise exclusive OR
     >> Shift Right
    >>> Shift Right  zero fill
    << Shift left
    &= Bitwise AND assignment
    \=  Bitwise OR assignment
    ^=  Bitwise exclusive OR assignment
   >>=  Shift Right assignment
   >>>=  Shift Right  zero fill assignment
    <<= Shift left assignment
Relational operator
The relational operator determine the relationship that one operand has to other. Specifically, they determine equality and ordering . The relational operators are shown here :
Operator Result
     = = Equal to
     != Not equal to
      > greater than 
      < less than
     >= greater than or equal to
     <= less than or equal to
Boolean Logical Operators
The Boolean logical operators shown here operates only on Boolean operands. All of the binary logical operators combine  two Boolean values to form a resultant Boolean value.
Operator Results
      & Logical AND
      \ Logical OR
      ^ Logical XOR(exclusive OR)
     || Short-circuit OR
    && Short-circuit  AND
     ! Logical Unary not
    &= AND assignment
    \= OR assignment
    ^= XOR assignment
    = = Equal to
    != Not equal to
    ? : Ternary if-then-else
Precedence of Java Operators :
Given below table shows the order of precedence for java operators, from highest to lowest :
Highest
( ) [] .
++    --     ~       !
*     /    %  
+   - 
>> >>>    <<
>   >=     <  <= 
= =  != 
&
^
|
&&
||
? :
=
Lowest

Java Loop Control Statement

When a block of code executes number of times, we referred it as loop.
The three basic loop control statements supported by java are :
  • while loop
  • do...while loop
  • for loop
  • enhance for loop

while loop control statement

The while loop repeats a statement or block while its controlling expression is true. given below it's syntax :
while(condition) {
//body of loop
}

Here, the condition can be any Boolean expression, whose outcome is either true or false. The loop executes if the condition is true. If not, the next line of code executes.
public class Main {
   public static void main(String args[]){
      int a= 10;
      System.out.println("The Changing value of 'a' during execution :");
      while( a < 20 ){
      System.out.print("a : " + a );
      a++;
      System.out.print("\n");
      }
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Main.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Main

values after loop execution :
x : 10
x : 11
x : 12
x : 13
x : 14
x : 15
x : 16
x : 17
x : 18
x : 19

do...while loop control statement :

This loop is similar to while loop but it executes at least one time. After executing set of code or block every time, it checks the condition - if condition is true then block of code executes , if not - it will not execute. The syntax of this loop control statement is given below :
do
{
   //body of loop
}while(condition);
Given below the sample code :

public class Main {
   public static void main(String args[]){
      int a= 3;
      System.out.println("The Changing value of 'a' during execution :")
      do{
         System.out.print(" a : " + a );
         a++;
         System.out.print("\n");
      }while( a < 10 );
   }
}
Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac Main.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Main

The Changing value of 'a' during execution :
a :3
a :4
a :5
a :6
a :7
a :8
a :9

for loop control statement :

This loop works as follows : At first go, it initialize the variable. After this, it checks the condition, if true then it will execute further. If not , it will terminate loop. After first go, the sequence of execution is as follows : first evaluate the condition, then execution of body of loop, and then executing the iteration expression with each pass.
The syntax given below :
for(initialization; Condition; iteration)
{
   //body
}
Example :
public class Main {
public static void main(String args[]){

for(int a = 10; a < 20; a = x+1){
System.out.print("value of a : " + a );
System.out.print("\n");
}
}
}

Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Main.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Main
x : 10
x : 11
x : 12
x : 13
x : 14
x : 15
x : 16
x : 17
x : 18
x : 19

enhance for loop (for-each)

Enhance for loop was added in java 5, which is mainly used for arrays , It is also referred as 'for-each'.  
Syntax is given as follows :
for(type itr-var: collection)
{
   //body
}
Example :
public class Main {
public static void main(String args[]){
int [] array = {10, 20, 30, 40, 50};

for(int a : array ){
System.out.print( a );
System.out.print(",");
}
System.out.print("\n");
String [] list ={"Ankit", "Kapil", "Samita", "Annu"};
for( String li : list ) {
System.out.print( li );
System.out.print(",");
}
}
}

Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Main.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Main

10,20,30,40,50,
Ankit, Kapil, Samita, Annu
The type specifies the type and itr-var specifies the name of the iteration variable that will receive the elements from a collection , one at a time, from beginning to end The collection being cycled through is specified by 'collection'. You can use various type of collection with 'for'. Most basic example is array.

Decision Making Statements

Following are the types of decision making statements :
1. if statements
2. switch statements
Using  these statements, you control the flow of your program execution.
if statement
The if statement is conditional branch statement. Using it , you can route program execution through two different path. The syntax is given below :
if (condition) statement1;
else statement 2;

Example :
public static void main(String args[]){
int a = 30;
if( a < 32 ){
System.out.print("It is inside if control statement");
}}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac If.java

C:\Program Files\Java\jdk1.6.0_18\bin>java If
It is inside if control statement
It is inside if control statement
if...else Statement :
The if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Example :
public class IfElse {
   public static void main(String args[]){
      int x = 5;

      if( x < 3 ){
         System.out.print("Inside if statement");
      }else{
         System.out.print("Inside else statement");
      }
   }
}
Example :
C:\Program Files\Java\jdk1.6.0_18\bin>javac IfElse.java

C:\Program Files\Java\jdk1.6.0_18\bin>java IfElse
Inside else statement
Nested ifs
You can create nested if inside if. On thing keep in mind that an else statement always refers to the nearest if statement that is within the same block.

Example :
public class NestedIf {
public static void main(String args[]){
int a = 3;
int b = 30;
if( a == 3 ){
if( b == 30 ){
System.out.print("a = 3 and b = 30");
}
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac NestedIf.java

C:\Program Files\Java\jdk1.6.0_18\bin>java NestedIf
a = 3 and b = 30
if-else-if Statement
This statement structure is slightly different. It contains the sequence of "else if" after first "if" but it checks the condition same as normal if ,also it got control when previous if or else if is not executed.
Example :
public class IfElseIf {
   public static void main(String args[]){
      int x = 30;

      if( x == 10 ){
         System.out.print("Value of X is 10");
      }else if( x == 20 ){
         System.out.print("Value of X is 20");
      }else if( x == 30 ){
         System.out.print("Value of X is 30");
      }else{
         System.out.print("else statement");
      }
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac NestedIf.java

C:\Program Files\Java\jdk1.6.0_18\bin>java NestedIf
Value of X is 30
Switch Statement
Switch statement provide an easy way to dispatch execution to different parts of your code based on the value of an expression.
The syntax is given below :
switch(expression){
    case value :
       //Statements
       break; //optional
    case value :
       //Statements
       break; //optional
    //You can have any number of case statements.
    default : //Optional
       //Statements
}
The 'expression" must be of type byte, short, int, or char. A switch statement can an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Example :
package corejava;
public class Switch {
private static final char c='A';
public static void main(String args[]){

switch(c)
{
case 'A' :
System.out.println("Excellent!"); break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + c);
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javacSwitch.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Switch
Excellent!
Your grade is A


Numbers in Java

In java ,when we have need of a number, we use primitive data types such byte, int, long, double etc.
During coding of an application , situation occurs when we need to use object in place of primitive data types. To implement this Java have wrapper classes for each primitive data type.
All the wrapper classes ( Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.
The process of writing a primitive data type into an object is called wrapping an Object and it is handled  by compiler. The process is called boxing. Similarly the compiler unboxes the object to a primitive as well. The Number is part of the java.lang package.
Given below the example of boxing and unboxing :
public class boxing{
   public static void main(String args[]){
      Integer a = 3; // boxes int to an Integer object
      a =  a + 30;   // unboxes the Integer to a int
      System.out.println(x); 
   }
}
 Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac boxing.java

C:\Program Files\Java\jdk1.6.0_18\bin>java boxing
5
Given below table contains the methods for processing numbers :
    Methods             Description         
xxxValue() Converts the value of this Number object to the xxx data type and returned it.
compareTo() Compares this Number object to the argument.
equals() Determines whether this number object is equal to the argument.
valueOf() Returns an Integer object holding the value of the specified primitive.
toString() Returns a String object representing the value of specified int or Integer.
parseInt() This method is used to get the primitive data type of a certain String.
abs() Returns the absolute value of the argument.
ceil() Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
floor() Returns the largest integer that is less than or equal to the argument. Returned as a double.
round() Returns the closest long or int, as indicated by the method's return type, to the argument.
min() Returns the smaller of the two arguments.
max() Returns the larger of the two arguments.
exp() Returns the base of the natural logarithms, e, to the power of the argument.
log() Returns the natural logarithm of the argument.
pow() Returns the value of the first argument raised to the power of the second argument.
sqrt() Returns the square root of the argument.
sin() Returns the sine of the specified double value.
cos() Returns the cosine of the specified double value.
asin() Returns the arcsine of the specified double value.
acos() Returns the arccosine of the specified double value.
atan() Returns the arctangent of the specified double value.
toDegrees() Converts the argument to degrees
toRadians() Converts the argument to radians.
random() Returns a random number.


Characters in Java

To store character data, generally, we use primitive data type char. Java uses Unicode to represent character. For example :
char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u039A'; 
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; 
Situations occurs when we have need of using objects. Character wrapper class provide us this facility for primitive data type char. You can create character objects using character constructor as follows :
Character ch = new Character('x');
In some situation, java compiler automatically create a Character object. For example , you have a method which need an object as argument and you passed an primitive char to it, it will automatically convert primitive type to object. This is called boxing .
Example :
// Here following primitive char 'a' is boxed into the Character object ch
Character ch = 'a';
// Here primitive 'x' is boxed for method test,return is unboxed to char 'c'
char c = test('x');
 
Given below the methods for Character class implementation :
      Methods                  Description         
isLetter() It checks whether the specified char value is a letter.
isDigit() It checks whether the specified char value is a digit.
isWhitespace() It checks whether the specified char value is white space.
isUpperCase() It checks whether the specified char value is uppercase.
isLowerCase() It checks whether the specified char value is lowercase.
toUpperCase() Returns the uppercase form of the specified char value.
toLowerCase() Returns the lowercase form of the specified char value.
toString() Returns a String object representing the specified character valuethat is, a one-character string.

Characters Examples

Example For charValue() method in java

In this Example, We will Introduced you about the charValue() method of the character class.  This method returns the Value of the character object. This method is used with the character object followed by .(dot) operator.
Example: CharacterValue.java
package com.devmanuals;
public class Charactervalue {

        public static void main(String[] args) {
                Character ch1 = new Character('A');
                Character ch2 = new Character('B');
                System.out.print("The character value of ch1 is= ");
                System.out.println(ch1.charValue());
                System.out.print("The character value of ch2 is= ");
                System.out.println(ch2.charValue());

        }
}
Output :
The character value of ch1 is= A
The character value of ch2 is= B

Example For getNumericValue() method in java

In this Example, We will Introduced you about the getNumericValue() method of the character class. This method returns the numeric value of the character.  If any character don't have any numeric value than it returns -1 and returns -2 if  the value is not represented as a non negative.
This method have parameter as the character to be find the numeric value as- getNumericValue('ch')
Example: GetNumericValue.java
package com.devmanuals;
public class GetNumericValue {

        public static void main(String[] args) {

                System.out.print("The Numeric value of A is= ");
                System.out.println(Character.getNumericValue('A'));
                System.out.print("The Numeric value of B is= ");
                System.out.println(Character.getNumericValue('B'));
                System.out.print("The Numeric value of G is= ");
                System.out.println(Character.getNumericValue('G'));

        }
}
 
 Output :
The Numeric value of A is= 10
The Numeric value of B is= 11
The Numeric value of G is= 16

Example for compareTo() method 

In this tutorial, We will discuss about the compareTo() method of the Java character class. This method compares two character objects according to code value and returns numerical value. This method returns positive value if the non argument character is greater than argument character, and returns negative argument character is greater than the non argument character. returns 0 if both the characters are same numerically.
Example:ChartacterCompareTo.java
package com.devmanuals;
public class CharacterCompareTo {

        public static void main(String[] args) {
                Character ch1 = new Character('a');
                Character ch2 = new Character('A');
                Character ch3 = new Character('a');
                System.out.println(ch1.compareTo(ch2));
                System.out.println(ch1.compareTo(ch3));
                System.out.println(ch2.compareTo(ch3));
        }
}
 Output :
32
0
-32

Example for isLetter() method in Java

In this example, We will inform you about the isDigit() method of the character class. This method specifies that the given character is a letter or not. This method returns the Boolean value true if the character is letter otherwise it returns false. Here is the example as .
Example:CharacterisLetter.java
package com.devmanuals;
public class CharacterIsLetter {

        public static void main(String[] args) {

                System.out.print("Is character A is letter= ");
                System.out.println(Character.isLetter('A'));
                System.out.print("Is character 9 is letter= ");
                System.out.println(Character.isLetter('9'));
                System.out.print("Is character @ is letter= ");
                System.out.println(Character.isLetter('@'));
        }
}
 Output :
Is character A is letter= true
Is character 9 is letter= false
Is character @ is letter= false

Example for isDigit() method of character class

In this Example, We will discuss about the isDigit() method of the character class. This method specifies that the given character is a digit or not and returns Boolean value true if character is digit else it returns false. The implementation of the method is given in the following example.
Example: CharacterIsDigit.java 
package com.devmanuals;
public class CharacterIsDigit {

        public static void main(String[] args) {
                System.out.print("Is character A is Digit= ");
                System.out.println(Character.isDigit('A'));
                System.out.print("Is character 9 is Digit= ");
                System.out.println(Character.isDigit('9'));
        }
}
 Output :
Is character A is Digit= false
Is character 9 is Digit= true

Example for isLowerCase() method of character class

In this tutorial, We will introduce you about the isLowerCase() method of character class. This method specifies whether the given character is Lower Case or not. This method returns true when character is in lower case and false when character is not in lower case.
Example:CharacterIsLowerCase.java
package com.devmanuals;
public class CharacterIsLowerCase {

        public static void main(String[] args) {
                System.out.print("Is character G is LowerCase= ");
                System.out.println(Character.isLowerCase('G'));
                System.out.print("Is character g is LowerCase= ");
                System.out.println(Character.isLowerCase('g'));
                System.out.print("Is character w is LowerCase= ");
                System.out.println(Character.isLowerCase('w'));

        }
}
 Output :
Is character  G  is LowerCase=  false
Is character  g  is LowerCase=  true
Is character  w  is LowerCase=  true

Example for isUpperCase() method of character class

In this tutorial, We will introduce you about the isUpperCase() method of character class. This method specifies whether the given character is Upper Case or not. This method returns true when character is in upper case and false when character is not in upper case.
Example:CharacterIsUpperCase.java
package com.devmanuals;
public class CharacterIsUpperCase {

        public static void main(String[] args) {
                System.out.print("Is character G is UpperCase= ");
                System.out.println(Character.isUpperCase('G'));
                System.out.print("Is character g is UpperCase= ");
                System.out.println(Character.isUpperCase('g'));
                System.out.print("Is character H is UpperCase= ");
                System.out.println(Character.isUpperCase('H'));
        }
}
 Output :
Is character  G  is UpperCase= true
Is character  g  is UpperCase= false
Is character  H  is UpperCase= true

Example For isSpaceCharacter() method in java

In this tutorial, We will discuss about isSpaceCharacter() method of character class. This method specified that the given character is an space character or not. This method returns true if the character is space character otherwise it returns false value. The character type value is the method parameter to be converted.
Example: IsSpaceCharacter.java
package com.devmanuals;
public class CharacterIsSpaceCharacter {

        public static void main(String[] args) {
                System.out.print("Is character is SpaceCharacter= ");
                System.out.println(Character.isSpaceChar(' '));
                System.out.print("Is character is SpaceCharacter= ");
                System.out.println(Character.isSpaceChar('\n'));
                System.out.print("Is character is SpaceCharacter= ");
                System.out.println(Character.isSpaceChar('\t'));
                System.out.print("Is character is SpaceCharacter= ");
                System.out.println(Character.isSpaceChar('\b'));

        }
}
 Output :
Is character '  '  is Space Character=  true
Is character '\n' is Space Character=  false
Is character '\t' is Space Character=  false
Is character '\b' is Space Character=  false

Example For isWhitespace() method in Java

In this tutorial, We will discuss about the isWhitespace() method of character class in java. This method specifies that the given character is white space character or not. The isWhitespace() method returns true if the character is white space character otherwise returns false.
Example: CharacterIsWhiteSpace.java
package com.devmanuals;
public class CharacterIsWhiteSpace {

        public static void main(String[] args) {
                System.out.print("Is character is WhiteSpace= ");
                System.out.println(Character.isWhitespace(' '));
                System.out.print("Is character is WhiteSpace= ");
                System.out.println(Character.isWhitespace('W'));
                System.out.print("Is character is WhiteSpace= ");
                System.out.println(Character.isWhitespace('\n'));
                System.out.print("Is character is WhiteSpace= ");
                System.out.println(Character.isWhitespace('\t'));
                System.out.print("Is character is WhiteSpace= ");
                System.out.println(Character.isWhitespace('\b'));

        }
}
 Output :
 Is character  ' ' is WhiteSpace= true
Is character 'W ' is WhiteSpace= false
Is character  '\n' is WhiteSpace= true
Is character '\t'  is WhiteSpace= true
Is character '\b '  is WhiteSpace= false

Example For toLowerCase() method in java

In this example, We will discuss about the toLowerCase() method of the character class. This method is used to convert uppercase character in to lower case. This method converts the argument to lower case using case mapping info of the Unicode data File. This method returns right value for a range of characters.
Example: CharacterToLowerCase.java
package com.devmanuals;
public class CharacterToLowerCase {

        public static void main(String[] args) {
                System.out.print("The Lower Case of R is= ");
                System.out.println(Character.toLowerCase('R'));
                System.out.print("The Lower Case of K is= ");
                System.out.println(Character.toLowerCase('K'));
                System.out.print("The Lower Case of M is= ");
                System.out.println(Character.toLowerCase('M'));

        }
}
 Output :
The Lower Case of  R  is= r
The Lower Case of  K  is= k
The Lower Case of  M  is= m

Example For toUpperCase() method in java

In this section, We will discuss about the toUpperCase() method of the character class. This method is used to convert lower case character in to Upper case. This method converts the argument to Upper case using case mapping info of the Unicode data File. This method returns right value for a range of characters.
Example: CharacterToUpperCase.java
package com.devmanuals;
public class CharacterToUpperCase {

        public static void main(String[] args) {
                System.out.print("The Upper Case of g is= ");
                System.out.println(Character.toUpperCase('g'));
                System.out.print("The Upper Case of b is= ");
                System.out.println(Character.toUpperCase('b'));
                System.out.print("The Upper Case of t is= ");
                System.out.println(Character.toUpperCase('t'));
        }
}
 Output :
The Upper Case of g is= G
The Upper Case of b is= B
The Upper Case of t is= TExampse() method in java
In this section, We will discuss about the toUpperCase() method of the character class. This method is used to convert lower case character in to Upper case. This method converts the argument to Upper case using case mapping info of the Unicode data File. This method returns right value for a range of characters.
Example: CharacterToUpperCase.java
package com.devmanuals;
public class CharacterToUpperCase {

        public static void main(String[] args) {
                System.out.print("The Upper Case of g is= ");
                System.out.println(Character.toUpperCase('g'));
                System.out.print("The Upper Case of b is= ");
                System.out.println(Character.toUpperCase('b'));
                System.out.print("The Upper Case of t is= ");
                System.out.println(Character.toUpperCase('t'));
        }
}
 Output :
The Upper Case of g is= G
The Upper Case of b is= B
The Upper Case of t is= T

Example For Finding The hashCode of a character in java

In this Example, We introduce you about the hashCode() method of the Object class. This method returns the hashCode value for the character. The hashCde() method is used with the character object followed by .(dot) operator.
Example: CharacterHashCode.java
package com.devmanuals;
public class CharacterHashCode {

        public static void main(String[] args) {

                Character ch1 = new Character('a');
                Character ch2 = new Character('A');
                System.out.print("The hash code of character a is= ");
                System.out.println(ch1.hashCode());
                System.out.print("The hash code of character A is= ");
                System.out.println(ch2.hashCode());
        }
}
Output:
The hash code of character a is= 97
The hash code of character A is= 65
In general, strings are sequence of characters but in java strings are objects. Some of the strings' common process are given below :
Creating Strings :
You can create string as follows :
String greeting = "welcome to Devmanuals";
The compiler creates a string object whenever it found the string literal in your code. Using 'new' keyword and constructor, you can create String objects as :

public class StringDev{
   public static void main(String args[]){
      String devString = new String("devArray");  
      System.out.println( devString );
   }
}
After execution, it will produce following results :
C:\Program Files\Java\jdk1.6.0_18\bin>javac StringDev.java

C:\Program Files\Java\jdk1.6.0_18\bin>java StringDev
devmanuals
Calculating String Length
You can calculate the length of the string by using length() method as :
public class CalString{
public static void main(String args[]){
String dev = "welcome to devmanuals";
int len = dev.length();
System.out.println( "Length of String is : " + len );
}
}
Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac CalString.java

C:\Program Files\Java\jdk1.6.0_18\bin>java CalString
21
Concatenating Strings:
For concatenating two strings , we have 'concat()' method in java, it van be used as :

public class StringConcat{
public static void main(String args[]){
String str = "Manuals ";
System.out.println("Dev" + str+ "website");
}
}
Output :

C:\Program Files\Java\jdk1.6.0_18\bin>javac StringConcat.java

C:\Program Files\Java\jdk1.6.0_18\bin>java StringConcat
DevManuals website
Print output with formatted numbers
You can print output with format numbers using 'printf' and 'format' methods as :

System.out.printf("value of variable:" +"%f");
Example using format method :
String dv;
dv = String.format("value of variable is " +"%f");
System.out.println(dv);
The format( ) method returns a String object rather than a PrintStream object. The format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement.

 Strings Examples

Example For Reverse a String

In this tutorial, We will discuss about the how to reverse a string in java. In this Example of  reverse a string using reverse() method of StringBuffer class. StringBuffer(String string) method, reverse the buffered string and converts this buffered string into the string by using the toString() method.

The code of the Example is as-

package com.devmanuals;
public class ReverseString {

        public static void main(String[] args) {

                String str1 = "natarazsir";
                System.out.println("The original string is" + str1);
                String str2 = new StringBuffer(str1).reverse().toString();
                System.out.println("The reverse string is" + str2);
        }
}
 
Output:
The original string is= natarazsir
The reverse string is= riszaratan

Example For Compare two Strings in java

 In this tutorial, We will discuss about the Comparison of two Strings in java. In this example we compare two Strings using  compareTo() method and  compareToIgnoreCase(). The compareTo() method returns the negative value if Unicode value of first String is less than the second String. And return positive value if first String is greater than second string. It return 0 if the string is same. The compareToIgnoreCase() method compares the strings and ignore the case of the string either it is Lower or in Upper case.
Example : StringCompare.java
 package com.devmanuals;
public class StringCompare {

        public static void main(String[] args) {
                String str1 = "NATARAZSIR.BLOGSPOT.IN";
                System.out.println("The first string is=" + str1);
                String str2 = "natarazsir.blogspot.in";
                System.out.println(str1.compareTo(str2));
                System.out.println(str1.compareToIgnoreCase(str2));
        }
}
Output:
The first string is=natarazsir.blogspot.in
-32
0


Example For Concatenation of Strings

In this tutorial, We will discuss about the concatenation of the two Strings in java. For concatenation of the two Strings we use the concat() method.
This method is used with the two String objects as given in the example.
Example: StringConcat.java
package com.devmanuals;
public class StringConcat {

        public static void main(String[] args) {
                String str1 = "natarazsir.blogspot.in";
                String str2 = "-Java Technology.";
                System.out.println("The strings for concatenation are " + str1
                                + " and " + str2);
                str2 = str1.concat(str2);
                System.out.println("The string after concatenation=");
                System.out.println(str2);

        }
}
Output:
The strings for concatenation are natarazsir.blogspot.in and -Java Technology.
The string after concatenation=
natarazsir.blogspot.in-Java Technology.

Example For Replace a String in java

In this Example, We will introduced you about the Replacement of words or in the given string using methods of String class. In this Example we replace sub string from the given string using replace() method.
The Syntax of the replace() method is as:
  replace(oldString , new String) Example: StringReplace.java
package com.devmanuals;
public class StringReplace {

        public static void main(String[] args) {
                String str1 = "JAVA Technology";
                System.out.println("The main string is = " + str1);
                String str2 = str1.replace("JAVA", "Spring");
                str2 = str2.replace("Technology", "Framework");
                System.out.println("The replaced string is = " + str2);
        }
}
 
Output:
 The main string is = JAVA Technology The replaced string is = Spring Framework

Example For Finding The Sub String in The given String

In This tutorial, We will discuss about to find the sub string in the given string. We can find the sub string by the indexes of the string . The example is as follows.
Example: Substring.java
package com.devmanuals;
public class SubString {

        public static void main(String[] args) {
                String str1 = "We work on java technology";
                System.out.println("The main string is=" + str1);
                String str2 = str1.substring(10);
                System.out.println("The sub string from index 10 is= " + str2);
                str2 = str1.substring(2, 15);
                System.out.println("The sub string between indexes (2,15) is= " + str2);
        }
}
Output:

The main string is=We work on java technology
The sub string from index 10 is= java technology
The sub string between indexes (2,15) is= work on java

Example For Convert  String to Uppercase

In this Example, We will introduce you about the converting a String from lower case letters to upper case letters. For converting the  letter case of the String in java we use the toUpperCase() method of String class. this method is used with the String object followed by .(dot) operator as in the example.
Example: StringtoUpperCase.java
package com.devmanuals;
public class stringToUpperCase {

        public static void main(String[] args) {
                String str1 = "natarazsir.blogspot.in";
                System.out.println("The main string is=" + str1);
                System.out.println("The changed string is=" + str1.toUpperCase());
        }
}
Output:
The main string is=natarazsir.blogspot.in
The changed string is=NATARAZSIR.BLOGSPOT.IN

Example For Convert  String to LowerCase

In this Example, We will introduce you about the converting a String from upper case letters to lower case letters. For converting the  letter case of the String in java we use the toLowerCase() method of String class. this method is used with the String object followed by .(dot) operator as in the example.
Example: StringToLowerCase.java
package com.devmanuals;
public class StringToLower {

        public static void main(String[] args) {
                String str1 = "NATARAZSIR.BLOGSPOT.IN";
                System.out.println("The main string is=" + str1);
                System.out.println("The changed string is=" + str1.toLowerCase());

        }
}
Output:
The main string is=NATARAZSIR.BLOGSPOT.IN
The changed string is=natarazsir.blogspot.in

Example For Trim a String in java

In this tutorial, We will discuss about the trim() method of  string class in java. This method remove the Leading and Tailing Escape characters from the strings. The trim() method is used by String object followed by .(dot) operator as in the example.
Example: StringTrim.java
package com.devmanuals;
public class StringTrim {
        public static void main(String[] args) {
                String str1 = "    We work on java technology      ";
                System.out.println("The main string is=" + str1);
                String str2 = str1.trim();
                System.out.println("The sub string after trim is= " + str2);
        }
}
Output:
The main string is=        We work on java technology
The sub string after trim is= We work on java technology

Example For Split a String 

In this Example, We will discuss about The Split a String. The String can be Spilt in two ways, first we can split according to words wise and secondly character wise. The example is as follows.
This example is for split the string  words wise.
Example: SplitString.java.
package com.devmanuals;
public class StringSplit {
        public static void main(String[] args) {
                String str1 = "We work on java technology";
                System.out.println("The string before split is=" + str1);
                String[] str2 = str1.split(" ");
                System.out.println("The string after spilt is =");
                for (int i = 0; i <= str1.length(); i++) {
                        System.out.println(str2[i]);

                }
        }
}
Output:
The string before split is=We work on java technology
The string after spilt is =
We
work
on
java
technology

Example For String EndsWith() Method

In this example, We will discuss about implementation of endswith() method on the string. This methos is used for finding the string which is ends with the given sub string. This method is implemented as given in the example.
Example: StringendsWith.java
package com.devmanuals;
public class StringEndsWith {

        public static void main(String[] args) {
                String str1 = "We work on java technology";
                System.out.println("The main string is=" + str1);
                if (str1.endsWith("java")) {
                        System.out.println("The string ends with java");
                } else {
                        System.out.println("The string not ends with java");
                }
                if (str1.endsWith("technology"))
{
                System.out.println("The string '" + str1 + "' ends with technology");
                }
        }
} 
Output:
The main string is=We work on java technology
The string not ends with java
The string 'We work on java technology' ends with technology

Example For String startsWith() Method

In this example, We will discuss about implementation of startswith() method on the string. This methos is used for finding the string which is starts with the given sub string. This method is implemented as given in the example.
Example: StringStartsWith.java
package com.devmanuals;
public class StringStartwith {

        public static void main(String[] args) {
                String str1 = "We work on java technology";
                System.out.println("The main string is=" + str1);
                if (str1.startsWith("java")) {
                        System.out.println("string started with java");
                } else {
                        System.out.println("string not start with java");
                }
                if (str1.startsWith("We")) {
                        System.out.println("The string  '" + str1 + "'  start with We");
                }

        }
}
Output:
The main string is=We work on java technology
string not start with java
The string 'We work on java technology' start with We

Example For String Length

In this tutorial, We will discuss about how to know length of the Strings in java. In this Program we use the length() method to know the length of the string.
Example: StringLength.java
package com.devmanuals;
public class StringLength {

        public static void main(String[] args) {

        String str1 = "Devmanuals";
        System.out.println("The String is= " + str1);
        int length = str1.length();
        System.out.println("The Length of the string is= " + length);
        }
}
Output:
The String is= Devmanuals
The Length of the string is= 10
 

Example For String hashCode() method in java

In this tutorial, We will discuss about the hashCode() method of the string class. This method returns the hash Code value of the string. The hash code is the unique reference number of a object in the JVM. The implementation of the method is as follows. The hash code is calculating according to following series as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Where s[i] represent the ith character of string and n is the length of the string.
Example: String hashCode.java
package com.devmanuals;
public class StringhashCode {

        public static void main(String[] args) {
                String str1 = "devmanuals";
                System.out.println("The hash code for the string is= "
                                + str1.hashCode());
        }
}
Output:
The hash code for the string is= -11748424



Date and Time in Java


The 'java.util' package contains date class which contains current date and time.

Getting current Date and Time

For getting current date and time , you need to first initialize the object of class date. After creating it's object you can print it using 'tostring( )' method.
Example :

import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date.toString());
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DateDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java DateDemo
Tue Sep 28 17:52:01 IST 2010

Date Formatting using SimpleDateFormat

The SimpleDateFormat is a class for format and parse date in a locale-sensitive manner. Any user can use it's predefine character codes to create it's own pattern for formatting date-time as follows :
Example :
import java.util.*;
import java.text.*;
class DateDemo {
   public static void main(String args[]) {

       Date dNow = new Date( );
       SimpleDateFormat ft = 
       new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

       System.out.println("Current Date: " + ft.format(dNow));
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DateDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java DateDemo
Sun 2010.09.28 at 06:14:09 PM PDT
In this code :
'E' means - Day in week
'y', 'm' & 'd' means - year, month & date respectively.
'h', 'm', 's' means - hour, minutes & second respectively.
'a' means -  A.M./P.M. marker.
'z' means - Time zone.

Date Formatting using printf :

We can also format date and time using printf. In this approach, we are using a two letter format starting with t and ending in one of the letters of the table given below. For example :
import java.util.Date;
class DateDemoBasic {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%tc", "Current Time : ", date);
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DateDemoBasic.java

C:\Program Files\Java\jdk1.6.0_18\bin>java DateDemoBasic
 Due date: September 29, 2010
For formatting separate parts, it also has separate two letter codes which is also given below table. Given below the program for separate formatting :

import java.util.Date;
class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DateDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java DateDemo
Due date: September 29, 2010

Date and Time Conversion Characters :

Character Description Example
c Complete date and time Mon May 04 09:51:52 CDT 2009
F ISO 8601 date 2004-02-09
D U.S. formatted date (month/day/year) 02/09/2004
T 24-hour time 18:05:19
r 12-hour time 06:05:19 pm
R 24-hour time, no seconds 18:05
Y Four-digit year (with leading zeroes) 2004
y Last two digits of the year (with leading zeroes) 04
C First two digits of the year (with leading zeroes) 20
B Full month name February
b Abbreviated month name Feb
n Two-digit month (with leading zeroes) 02
d Two-digit day (with leading zeroes) 03
e Two-digit day (without leading zeroes) 9
A Full weekday name Monday
a Abbreviated weekday name Mon
j Three-digit day of year (with leading zeroes) 069
H Two-digit hour (with leading zeroes), between 00 and 23 18
k Two-digit hour (without leading zeroes), between 0 and 23 18
I Two-digit hour (with leading zeroes), between 01 and 12 06
l Two-digit hour (without leading zeroes), between 1 and 12 6
M Two-digit minutes (with leading zeroes) 05
S Two-digit seconds (with leading zeroes) 19
L Three-digit milliseconds (with leading zeroes) 047
N Nine-digit nanoseconds (with leading zeroes) 047000000
P Uppercase morning or afternoon marker PM
p Lowercase morning or afternoon marker pm
z RFC 822 numeric offset from GMT -0800
Z Time zone PST
s Seconds since 1970-01-01 00:00:00 GMT 1078884319
Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047
There are other useful classes related to Date and time. For more detail you can refer to Java Standard documentation.

Regular Expression in Java

For matching pattern in java , we are using regular expression. For this, we are using 'java.util.regex' package. It is very similar to Perl programming language. The regular expression is used to define pattern, which is used to find string or set of strings. They can be used to search, edit, or manipulate text and data.
The 'java.util.regex' package primarily consists of the following three classes:
  • Pattern Class: A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.
  • Matcher Class: A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object.
  • PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.

Capturing Groups :

For  treating multiple characters as single unit we use Capturing groups. For example, the regular expression (dev) creates a single group containing the letters "d", "e", and "v".
Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((X)(Y(Z))), for example, there are four such groups:

1.((X)(Y(Z)))


2.(X)


3.(Y(Z))


4.(Z)

By using 'groupCount' method you can find the number of groups present in an expression. There is also a special group, group 0, which always represents the entire expression. This group is not included in the total count returned by groupCount.
Example :

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static void main(String args[]) {
// String to be scanned to find the pattern.
String line = "This order was places for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
} else {
System.out.println("NO MATCH");
}
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac RegexMatches .java

C:\Program Files\Java\jdk1.6.0_18\bin>java RegexMatches
Found value: This order was places for QT3000! OK?
Found value: This order was places for QT300
Found value: 0

Regular Expression Syntax :

Here is the table listing down all the regular expression metacharacter syntax available in Java :
Subexpression Matches
^ Matches beginning of line.
$ Matches end of line.
. Matches any single character except newline.
Using m option allows it to match newline as well.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
\A Beginning of entire string
\z End of entire string
\Z End of entire string except allowable final line terminator.
re* Matches 0 or more occurrences of preceding expression.
re+ Matches 1 or more of the previous thing
re? Matches 0 or 1 occurrence of preceding expression.
re{ n} Matches exactly n number of occurrences of preceding
expression.
re{ n,} Matches n or more occurrences of preceding expression.
re{ n, m} Matches at least n and at most m occurrences of preceding
expression.
a| b Matches either a or b.
(re) Groups regular expressions and remembers matched text.
(?: re) Groups regular expressions without remembering matched
text.
(?> re) Matches independent pattern without backtracking.
\w Matches word characters.
\W Matches nonword characters.
\s Matches whitespace. Equivalent to [\t\n\r\f].
\S Matches nonwhitespace.
\d Matches digits. Equivalent to [0-9].
\D Matches nondigits.
\A Matches beginning of string.
\Z Matches end of string. If a newline exists, it matches just
 before newline.
\z Matches end of string.
\G Matches point where last match finished.
\n Back-reference to capture group number "n"
\b Matches word boundaries when outside brackets. Matches
backspace (0x08) when inside brackets.
\B Matches nonword boundaries.
\n, \t, etc. Matches newlines, carriage returns, tabs, etc.
\Q Escape (quote) all characters up to \E
\E Ends quoting begun with \Q





Methods in Java

A method is a set of statements gathered together to carry out some operation.

Making a Method :

Given below the general syntax of a method :
modifier returnType methodName(parameters) {
//body;
}
Example :
This example returns the number which has maximum value :
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result; }
Method Calling :
The methods which returns value can be used to pass value to variables :
If the method return type is void then it van be used as statement. For example, the method println returns void. The following call is a statement :
System.out.println("Welcome to Devmanuals!");
Example :
public class TestMethod {
   
   public static void main(String[] args) {
      int a = 5;
      int b = 2;
      int c = max(a, b);
      System.out.println("The maximum between " + a +
                    " and " + b + " is " + c);
}
/** Return the max between two numbers */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac TestMethod .java

C:\Program Files\Java\jdk1.6.0_18\bin>java TestMethod
The maximum between 5 and 2 is 5

Method Overloading :

In java, it is possible that two methods have same name, but their parameter declaration must be different . This is called method overloading.
Example 
public class DemoOverload {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a:" + a);
}
// Overload test for two integer parameters
void test(int a, int b) {
System.out.println("a and b :" + a + " " + b);
}
}
class overload {
public static void main(String args[]) {
DemoOverload d = new DemoOverload();
d.test();
d.test(10);
d.test(10, 20);
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac Overload.java

C:\Program Files\Java\jdk1.6.0_18\bin>java Overload
No parameters
a:10
a and b :10 20

Constructor overloading :

The constructor can be overloaded in java, which is helpful in initializing variables and methods(constructors).
Example :

public class ConstructorOverloading {

   public static void main(String args[]) {
        Rectangle rectangle1 = new Rectangle(2, 4);
        int areaInFirstConstructor = rectangle1.first();
        System.out.println(" The area of a rectangle in first constructor is :"+ areaInFirstConstructor);
        Rectangle rectangle2 = new Rectangle(5);
        int areaInSecondConstructor = rectangle2.second();
        System.out.println(" The area of a rectangle in first constructor is :"+ areaInSecondConstructor);
        Rectangle rectangle3 = new Rectangle(2.0f);
        float areaInThirdConstructor = rectangle3.third();
        System.out.println(" The area of a rectangle in first constructor is :"+ areaInThirdConstructor);
        Rectangle rectangle4 = new Rectangle(3.0f, 2.0f);
        float areaInFourthConstructor = rectangle4.fourth();
        System.out.println(" The area of a rectangle in first constructor is :"+ areaInFourthConstructor);
        }
}
class Rectangle {
        int l, b;
        float p, q;

        public Rectangle(int x, int y) {
                l = x;
                b = y;
        }
   public int first() {
                return (l * b);
        }
   public Rectangle(int x) {
                l = x;
                b = x;
        }
   public int second() {
                return (l * b);
        }
   public Rectangle(float x) {
                p = x;
                q = x;
        }
   public float third() {
                return (p * q);
        }
   public Rectangle(float x, float y) {
                p = x;
                q = y;
        }
   public float fourth() {
                return (p * q);

        }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac ConstructorOverloading .java

C:\Program Files\Java\jdk1.6.0_18\bin>java ConstructorOverloading
The area of a rectangle in first constructor is : 8
The area of a rectangle in first constructor is : 25
The area of a rectangle in first constructor is : 4.0
The area of a rectangle in first constructor is : 6.0

Passing var-args to methods :

Variable length arguments are known as var-args. The method which takes variable number of arguments is called varargs method . Given below method "vaTest( )" excepts variable length arguments. In the below example it  accepts -1, 3, and 0 arguments. See below example to understand it clearly :
Example :

public class ClassVarargs {
static void vaTest(int v[]) {
System.out.println("Number of args :" + v.length + " 
Contents :");
for (int x : v)
System.out.println(x + " ");
System.out.println();
}


public static void main(String args[]) {
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = {};



vaTest(n1); // one args

vaTest(n2); // two args

vaTest(n3); // three args
}
}
 Example :
C:\Program Files\Java\jdk1.6.0_18\bin>javac ClassVarargs .java

C:\Program Files\Java\jdk1.6.0_18\bin>java ClassVarargs
 Number of args :1 Contents :
10

Number of args :3 Contents :
1
2
3

Number of args :0 Contents :





Arrays in Java

An array is the set of similar type of elements which is stored under a common name. An array can acquire any type and can have one or more dimensions. The element in array can be accessed by it's index. For storing related information under the same roof , we use arrays.

Declaring one dimension array 

type var-name[ ];
For example :
int[] Dev ;

or , you can also declare it as follows :

int Dev[];
If an array is declared as : int Dev[3], it means it has 4 element from Dev[0] to Dev[3].

Allocating memory to arrays :

var-name = new type[size];  
Example :
Dev = new int[12];

Assigning and accessing value from array

You can assign value directly, like this :
Dev[0] = 12; // this will assign value to first element.
Dev[1] = 30  // this will assign value to second element.
Array can also be assigned when they are declared as :
int Dev[] = {3, 12, 21, 30, 39, 48};
You can access array element like this :
System.out.println(Dev[3]);   // This will print 4th element of array.
Example :
public class DevArray {
public static void main(String[] args) {
double[] devList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: devList) {
System.out.println(element);
}
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac DevArray .java

C:\Program Files\Java\jdk1.6.0_18\bin>java DevArray
1.9
2.9
3.4
3.5

Multidimensional array :

In java, multidimensional arrays are actually arrays of arrays. For example, you can declare a two dimensional array as :
int twoD[][]=new int [4][5];
You can also declare a three dimensional array as :
int threeD[][][]= new int [3][4][5];
Example :
Class TwoDmatrix{
  public static void main(String args[]) {
    int twoDm[][]= new int[4][5];
    int i,j,k=0;

    for(i=0;i<4;i++)
      for(j=0;j<5;j++) {
         twoDm[i][j]=k;
         k++;
      }
    for(i=0;i<4;i++)
      for(j=0;j<5;j++) {
         System.out.println(twoDm[i][j]+"")
         System.out.println();
      }
   }
 }
 
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac TwoDmatrix .java

C:\Program Files\Java\jdk1.6.0_18\bin>java TwoDmatrix
0  1  2  3  4
5  6  7  8  9
10 11 12 13 14
15 16 17 18 19


Files and I/O

The every class which you need to perform input and output (I/O) is contained by java.io package.
A sequence of data can be defined as a stream. To read data from a source we used InputStream and to write data to destination, we need OutputStream.

Reading Console Input

Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. Here is most common syntax to obtain BufferedReader :
BufferedReader br = new BufferedReader(new 
                      InputStreamReader(System.in));
Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.
Example of Reading Characters
import java.io.*;
class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new 
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // read characters
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac BRRead.java

C:\Program Files\Java\jdk1.6.0_18\bin>java BRRead
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
Example of Reading Strings
import java.io.*;
class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac BRReadLines.java

C:\Program Files\Java\jdk1.6.0_18\bin>java BRReadLines
Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

Writing Console Output

Using print( ) and println( ), you can easily write to console.The PrintStream class has definition of these method. These objects are referenced by "System.out". Even though System.out is a byte stream, using it for simple program output is still acceptable.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console.
Example :
import java.io.*;

class WriteDemo {
   public static void main(String args[]) {
      int b; 
      b = 'A';
      System.out.write(b);
      System.out.write('\n');
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac BRReadLines.java

C:\Program Files\Java\jdk1.6.0_18\bin>java BRReadLines
A

Reading & Writing File

A sequence of data can be defined as stream. To read data from Source, we use InputStream. To write data to target we use OutputStream.
Here is a hierarchy of classes to deal with Input and Output streams :

FileInputStream

FileInputStream is used to read data from the files. Objects can be created using the keyword new.
Following constructor takes a file name as a string to create an input stream object to read the file :
InputStream f = new FileInputStream("C:/java/hello");
But before this you need to create a file object using "File()" method as follows :
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

FileOutputStream

For creating a file and writing data to it , we use FileoutputStream. Following constructor takes a file object to create an output stream object to write the file. First we create a file object using File() method as follows :
File f = new File("C:/java/hello");
FileOutputStream fop = new FileOutputStream(f);
Example :
The below code would create file test.txt and would write given numbers in binary format :
import java.io.*;
public class fileStreamDemo {
public static void main(String[] args) throws IOException {
File f = new File("C:/textfile1.txt");
FileOutputStream fop = new FileOutputStream(f);
if (f.exists()) {
String str = "This data is written through the 
program";
fop.write(str.getBytes());

fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not exist");
try {
InputStream is = new FileInputStream("C:/textfile1.txt");
int size = is.available();
for (int i = 0; i < size; i++) {
System.out.print((char) is.read());
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac fileStreamDemo.java

C:\Program Files\Java\jdk1.6.0_18\bin>java fileStreamDemo
The data has been written
This data is written through the program

Java File Reading Example

java.io package provides a numbers of classes to access the file. You use a combination of  IO classes to access a file. The following is an example to read a file.
FileExample.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileExample {
        public static void main(String[] args) {
                try {
                        File file = new File("D:\\test-file.txt");
                        FileInputStream fileInputStream = new FileInputStream(file);
                        DataInputStream dataInputStream = new DataInputStream(
                                        fileInputStream);
                        BufferedReader bufferedReader = new BufferedReader(
                                        new InputStreamReader(dataInputStream));
                        String fileData = "";
                        while ((fileData = bufferedReader.readLine()) != null) {
                                System.out.println(fileData);
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}


When you run this application it will display message as shown below:


Teating a Java File

Date 29 March 2012

Java File Writing Example

To Write a file in Java, at first create a File reference variable and pass its references to FileWriter class as.
File file = new File("D:\\test-file.txt");
FileWriter fileWriter = new FileWriter(file, true);

Here true indicates that the file will append. If we make it false then
Make a PrintWriter reference variable by passing the FileWriter references to its constructor and call the print() method to write data to a file and finally close the objects.
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println("Write Something to File");
fileWriter.close();

The Following is an example to write data to a file
JavaFileWritingExample.java
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class JavaFileWritingExample {
        public static void main(String[] args) {
                try {
                        File file = new File("D:\\test-file.txt");
                        FileWriter fileWriter = new FileWriter(file, true);
                        PrintWriter printWriter = new PrintWriter(fileWriter);
                        printWriter.println("Write Something to File");
                        fileWriter.close();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

Copy File from One Location to Another

To Copy a file from one location to another location open a FileInputStream and FileOutputStream reference variable from the source and desination file respecivly.
FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

Make an Array of byte and read from one stream to a buffer and write to another stream
int bufferSize;
byte[] bufffer = new byte[512];
   while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
   fileOutputStream.write(bufffer, 0, bufferSize);
}

The Following is a complete code to Copy file from one location to another location
CopyFileExample.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFileExample {
        public static void main(String[] args) {
                try {
                        File sourceFile = new File("D:\\registration.jsp");
                        File destinationFile = new File("F:\\" + sourceFile.getName());
                        CopyFileExample copyFileExample = new CopyFileExample();
                        copyFileExample.copyFile(sourceFile, destinationFile);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        public void copyFile(File sourceFile, File destinationFile) {
                try {
                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
                        FileOutputStream fileOutputStream = new FileOutputStream(
                                        destinationFile);

                        int bufferSize;
                        byte[] bufffer = new byte[512];
                        while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
                                fileOutputStream.write(bufffer, 0, bufferSize);
                        }
                        fileInputStream.close();
                        fileOutputStream.close();
                } catch (Exception e) {
                        e.printStackTrace();
                } 
 

Exceptions in Java

In java , exception is an object that describe an erroneous condition that has occurred in as piece of code. Java exception handling is managed through five keywords : try, catch , throw, throws and finally.
In try block, we put the code which you want to monitor for exception. You can handle the exception thrown by the code using catch block. To throw exception manually, use keyword throw. Any exception that is thrown out of a method must be specified as such by throws clause. The code which must be executed, before a method returns value, should be placed in finally block .

try and catch example :


public class TryCatch {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed" + a);
} catch (ArithmeticException e) {
System.out.println("Divided by zero");
}
System.out.println("After catch statement");
}
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac TryCatch .java

C:\Program Files\Java\jdk1.6.0_18\bin>java TryCatch
Divided by zero
After catch statement

Throw :

You can throw exception explicitly as follows :
throw ThrowableInstance ;
ThrowableInstance must be an object of type 'Throwable' or a subclass of 'Throwable'.
Example :

public class ThrowDemo {

        static void DevProc() {
                try {
                        throw new NullPointerException("demo");
                } catch (NullPointerException e) {
                        System.out.println("Caught inside Devproc.");
                        throw e;
                }
        }

        public static void main(String args[]) {
                try {
                        DevProc();
                } catch (NullPointerException e) {
                        System.out.println("Recaught :" + e);
                }

        }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac ThrowDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java ThrowDemo
Caught inside Devproc.
Recaught :java.lang.NullPointerException: demo

throws :

If a method is capable of causing exception but it is not using 'catch' to handle this. The 'throws' specify this behaviour so that callers of the method can guard themselves from that exception.
Example :

public class ThrowsDemo {
        static void throwone() throws IllegalAccessException {
                System.out.println("Inside throwone");
                throw new IllegalAccessException("demo");
        }

        public static void main(String args[]) {
                try {
                        throwone();
                } catch (IllegalAccessException e) {
                        System.out.println("Caught " + e);
                }
        }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac ThrowDemo .java

C:\Program Files\Java\jdk1.6.0_18\bin>java ThrowDemo
Caught inside Devproc.
Recaught :java.lang.NullPointerException: demo

finally

finally creates a block of code that will be executed after a try/catch block, and it will execute whether or not an exception is thrown. This can be useful for closing file handles and freeing up any other resources that might have been allocated.
Note :- The finally clause is optional . However each try block need at least one catch or a finally clause.
Example :
public class FinallyDemo{

   public static void main(String args[]){
      int x[] = new int[2];
      try{
         System.out.println("Element three :" + x[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      finally{
         x[0] = 6;
         System.out.println("First element: " +x[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac FinallyDemo.java

C:\Program Files\Java\jdk1.6.0_18\bin>java FinallyDemo
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed



Java exception handling example.

This is a simple exception handling example. An exception is a abnormal condition. There is two classes in our program SimpleExceptionDemo and ExceptionDemo. The ExceptionDemo class has a method name    division(). There is some lines of code that generates exception. These lines are presents in try block and the exception generated through this code must be handled by catch block.
Code:
SimpleExceptionDemo.java

package devmanuals.com;
class ExceptionDemo {
        public void division() {
        try {
                int num = 5;
                int n = num / 0;
                System.out.println(n);
        } catch (Exception e) {
                System.out.println("Exception : " + e.getMessage());
            }
        }
 }
public class SimpleExceptionDemo {
public static void main(String[] args) {
        ExceptionDemo eDemo = new ExceptionDemo();
        eDemo.division();
        }
}
Output:
Exception : / by zero

Multiple catch blocks java.

In this example, you will see the use of more than one catch block in a single try block. We can use multiple catch block for single try block. And every catch block will be handle only one type exception.
In this java code, there is two catch block for exception handling one is ArrayIndexOutOfBoundsException and ArithmaticException. When this code is executed, there will be a Arithmetic exception arise. So the first catch block will be skip and second will be executed.
Code:
MultipleCatchBlock.java

package devmanuals.com;
class CatchBlock {
        public void multipleCatch() {
        int a[] = { 2, 3, 4, 5 };
        int n = 220, n1 = 0;
        int div = 0;
        try {
                div = n / n1;
                System.out.println("Division of two number : " + div);
                for (int i = 0; i <= 4; i++) {
                        a[i] = i;
                }
        } catch (ArrayIndexOutOfBoundsException are) {
                System.out.println(are);
        } catch (ArithmeticException ae) {
                System.out.println(ae);
        }
    }
 }
public class MultipleCatchBlock {
public static void main(String[] args) {
        CatchBlock obCatchBlock = new CatchBlock();
        obCatchBlock.multipleCatch();
        }
}
Output:
  java.lang.ArithmeticException: / by zero   

Example of nested try block in java.

In this java code, you will see how to implements nested try catch block in java.
In this code, there is a inner try block it is handle the ArrayIndexOutOfBoundsException. When you compile this program and passed a file name as command line argument. If this file is not present at working directory, then it will generate a FileNotFoumdException.
Code:
NestedTryCatchDemo.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class NestedTryCatchDemo {

        public static void main(String[] args) {
                try {
                        int a[] = { 2, 3, 4, 5 };
                        FileInputStream inputStream = new FileInputStream(args[0]);
                        try {
                                for (int i = 0; i <= 4; i++) {
                                        a[i] = i;
                                }
                        } catch (ArrayIndexOutOfBoundsException are) {
                                System.out.println(are);
                        }
                } catch (FileNotFoundException ae) {
                        System.out.println(ae);
                }
        }
}
Output:
C:\>java NestedTryCatchDemo TestFile.txt
java.io.FileNotFoundException: TestFile.txt (The system cannot find the file specified)
Again if particular file present, then inner try block will be execute and generate a exception called ArrayIndexOutOfBoundsException.  
Output:
C:\>java NestedTryCatchDemo NestedTryCatchDemo.java java.lang.ArrayIndexOutOfBoundsException: 4


List All Files And Direcories In A Direcoty

In the application given below you will listFiles() method is used to list all the file and direcories in the given directories. This method returns the ArrayList of File object
We have used isFile() and isDirectory() methods of File class that returns the boolean value. It is generally used befor any operation on file or dirctory.
Please consider the example given below
SearchFileAndDirectories.java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class SearchFileAndDirectories {
        public static void main(String[] args) {

                String path = "";
                System.out.println("Please Enter the path");
                try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(
                                        System.in));
                        path = br.readLine();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                String fileName, directoryName;

                File searchInDirectory = new File(path);
                File[] listOfFiles = searchInDirectory.listFiles();
                File[] listOfDirectories = searchInDirectory.listFiles();

                System.out.println("********************************************");
                System.out.println("List Of All File in " + path);
                System.out.println("********************************************\n");
                for (File file : listOfFiles) {
                        if (file.isFile()) {
                                fileName = file.getName();
                                System.out.println(fileName);
                        }
                }

                System.out.println("********************************************");
                System.out.println("List Of All Directory in " + path);
                System.out.println("********************************************\n");
                for (File file : listOfFiles) {
                        if (file.isDirectory()) {
                                fileName = file.getName();
                                System.out.println(fileName);
                        }
                }
        }
}


When you run this application it will display message as shown below:


Please Enter the path
C:\Java\jdk1.6.0_14
********************************************
List Of All File in C:\Java\jdk1.6.0_14
********************************************

COPYRIGHT
LICENSE
LICENSE.rtf
README.html
README_ja.html
README_zh_CN.html
register.html
register_ja.html
register_zh_CN.html
src.zip
THIRDPARTYLICENSEREADME.txt
********************************************
List Of All Directory in C:\Java\jdk1.6.0_14
********************************************

bin
demo
include
jre
lib
sample


0 comments:

Post a Comment