Monday, November 1, 2010

Core Java


To compile and run a java program we need to install java platform. JDK (Java Development Kit). JDK is the basic set of tools required to compile and run java programs. This section enables you to download JDK and teaches you the steps to install it.
Download and Install JDK (Java Development Kit)
The latest version of jdk is 6 (update 1) at the time of writing the tutorial. You can download the latest version of jdk from http://java.sun.com/javase/downloads/index.jsp. Once you download the exe file you can now install it. Just follow as mentioned:
To install the jdk, double click on the downloaded exe file (jdk-6u1-windows-i586-p.exe) 
Step 1. Double Click the icon of downloaded exe.

You will see jdk 6 update 1 window as shown below.



Step 2: Now a "License Agreement" window opens. Just read the agreement and click "Accept" button to accept and go further.

Step 3: Now a "Custom Setup" window  opens. 

Step 4: Click on "Change" button to choose the installation directory. Here it is "C:\Program Files\ Java\jdk1.6.0_01". Now click on "OK" button.

Clicking the "OK" button starts the installation. It is shown in the following figure.



Step 5: Next window asks to install Runtime Environment

Click the "Change" button to choose the installation directory of Runtime Environment. We prefer not to change it. So click "OK" button.

Step 6: Click "OK"  button starts the installation.

Step 7: Now "Complete" window appears indicating that installation of jdk 1.6 has completed successfully. Click "Finish" button to exit from  the installation process.

Step 8: The above installation will create two folders "jdk1.6.0_01" and "jre1.6.0_01" in "C:\ Program Files\ java" folder.

Step 9: To make available Java Compiler and Runtime Environment for compiling and running java programs , we set the system environment variables. 
First of all select "My Computer" icon and right click the mouse button. Now click on "system Properties" option. It provides the "System Properties" window , click the 'Advanced' tab. Then Click the "Environment Variables" button. It provides "Environment Variables" window. Now select the path in System variables and click 'Edit' button. The"Edit System Variable" window will open. Add "c:\Program Files\Java\jdk1.6.0_01\bin" to 'variable value' and click 'Ok', 'Ok' and 'Ok' buttons. 

Step 10: Now set the JAVA_HOME variable and set its value to " C:\Program Files\Java\jdk1.6.0_01 ". If this variable has not been declared earlier then create a new system variable by clicking on "New" button and give variable name as "JAVA_HOME" and variable value as " C:\Program Files\Java\jdk1.6.0_01 ". Now click "OK". This variable is used by other applications to find  jdk  installation directory. For example, Tomcat server needs "JAVA_HOME" variable to find the installation directory of jdk.

Step 11: Now this is the final step to check that you have installed jdk successfully and it is working fine. Just go to the command prompt and type javac and hit enter key you will get the screen as shown below :

Now you can create, compile and run java programs.


In this section, you will learn to write a simple Java program. For developing a java program you just need  a simple text editor like "notepad". 
Open the notepad and write your program. 
Let's create a class createfirstprogram that will print a message "Welcome to RoseIndia.net" on the console. 



Here is the code of createfirstprogram.java file:
class createfirstprogram{
  public static void main(String[] args) {
    System.out.println("Welcome to RoseIndia.net");
  }
}
Download this example.
Save this program in the specified directory ("C:\Vinod" in this example) with name createfirstprogram.java.  
This class contains  public, static and void java keywords (these are pre-defined words in java which carries specific meaning).
public keyword specifies the accessibility issues of a class. Here, It specifies that method can be accessed from anywhere.
static keyword  indicates that this method can be invoked simply by using the name of the class without creating any class-object.
void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First of all JVM calls the main method of a class and start execution .  JVM (Java Virtual Machine) is responsible for running java programs.
args is a string array that takes values from java command line. It's index starts from '0'. We can access values by writing args[0], args[1] etc.
println() function prints the output to the standard output stream (monitor).
out
represents the standard output stream (monitor).

Now, you are ready to compile and run this program. Open the command prompt and go to the directory ("C:\vinod" in this example) where your program is saved.
Java uses the "javac" command to compile your program (Type javac createfirstprogram.java) . After compiling successfully, you can run it. Java uses the "java" command to execute your program (Type java createfirstprogram). It will print  "Welcome to RoseIndia.net".
Output of program:
C:\vinod>javac createfirstprogram.java

C:\vinod>java createfirstprogram
Welcome to RoseIndia.net

C:\vinod>_
In this section, you will learn about Java variables. A variable refers to the memory location that holds values like: numbers, texts etc. in the computer memory. A variable is a name of location where the data is stored when a program executes.
The Java contains the following types of variables:
  1. Instance Variables (Non-static fields): In object oriented programming, objects store their individual states in the "non-static fields" that is declared without the static keyword. Each object of the class has its own set of values for these non-static variables so we can say that these are related to objects (instances of the class).Hence these variables are also known as instance variables. These variables take default values if not initialized.    
  2. Class Variables (Static fields): These are collectively related to a class and none of the object can claim them  its sole-proprietor . The variables defined with static keyword are shared by all objects. Here Objects do not store an individual value but they are forced to share it among themselves. These variables are declared as "static fields" using the static keyword. Always the same set of values is shared among different objects of the same class. So these variables are like global variables which are same for all objects of the class. These variables take default values if not initialized.          
  3. Local Variables: The variables defined in a method or block of code is called local variables. These variables can be accessed within a method or block of code only. These variables don't take default values if not initialized. These values are required to be initialized before using them.
  4. Parameters: Parameters or arguments are variables used in method declarations. 
Declaring variables
Before using variables you must declare the variables  name and type. See the following example for variables declaration:
int num;            //represents that num is a variable that can store value of int type.
String name;     //represents that name is a variable that can store string value.
boolean bol;    //represents that bol is a variable that can take boolean value (true/false);

You can assign a value to a variable at the declaration time by using an assignment operator ( = ).
int num = 1000;       // This line declares num as an int variable which holds value "1000".
boolean bol = true;      // This line declares bol as boolean variable which is set to the value "true".                                          

Data type: The type of value that a variable can hold is called data type. When we declare a variable we need to specify the  type of value it will hold along with the name of the variable. This tells the compiler that the particular variable will hold certain amount of memory to store values. For example, in the lines of code above num is int type and takes two bytes to hold the integer value, bol is a boolean type and takes one bit to hold a boolean value .
Some common types of data types are used in the programming languages called as the primitive types like characters, integers,  floating point numbers etc. These primitive data types are given below where size represents the memory size it takes, For example, boolean takes a value "true"/"false" in 1 bit memory. It takes value "false" if not initialized (in the case of non-local variables)

Java Primitive Data Types

Data Type
Description
Size
Default Value
boolean
true or false
1-bit
false
char
Unicode Character
16-bit
\u0000
byte
Signed Integer
8-bit
(byte) 0
short
Signed Integer
16-bit
(short) 0
int
Signed Integer
32-bit
0
long
Signed Integer
64-bit
0L
float
Real number
32-bit
0.0f
double
Real number
64-bit
0.0d
In this section, we will discuss about java classes and its structure. First of all learn:  what is a class in java and then move on to its structural details. 
Class: In the object oriented approach, a class defines a set of properties (variables) and methods. Through methods certain functionality is achieved. Methods act upon the variables and generate different outputs corresponding  to the change in variables.
Structure for constructing  java program:
package package_name;

//import necessary packages

import
package_name.*;

Access Modifier
class class_name{
member variables;
member methods;
public static void main(String[] args) {
         ...
         ...
.

       }
}
package: In the java source file you generally use the package statement at header of a java program. We use package generally to group the related classes i.e. classes of same category or related functionality. You have to save your java files in the folder matching the package name as mentioned  in java program.
import : Import keyword is used at the beginning of a source file but after the package statement. You may need some classes, intefaces defined in a particular package to be used while programming so you would have to use import statement. This specifies classes or entire Java packages which can be referred to later without including their package names in the reference. For example, if you have imported util package (import java.util.*;) then you need not to mention the package name while using any class of util package.
Access Modifiers : Access modifiers are used to specify the visibility and accessibility of a class, member variables and methods. Java provides some access modifiers like: public, private etc.. These can also be used with the member variables and methods to specify their accessibility. 
  1. public keyword specifies that the public class, the public  fields and the public methods can be accessed from anywhere.
  2. private: This keyword provides the accessibility only within a  class i.e. private fields and methods can be accessed only within the same class.
  3. protected: This modifier makes a member of the class available to all classes in the same package and all sub classes of the class. 
  4. default : Its not a keyword. When we don't write any access modifier then default is considered. It allows the class, fields and methods accessible within the package only.
static keyword  indicates that this method can be invoked simply by using the name of the class without creating any class-object.
void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First of all JVM calls the main method of a class and start execution .  JVM (Java Virtual Machine) is responsible for running java programs.
args is a string array that takes values from java command line. It's index starts from '0'. We can access values by writing args[0], args[1] etc.
println() function prints the output to the standard output stream (monitor).
out
represents the standard output stream (monitor).

In this section, you will learn to work with command prompt arguments provided by the user. We will access these arguments and print the addition of those numbers. In this example, args is an array of String objects that takes values provided in command prompt. These passed arguments are of String types so these can't be added as numbers. So to add, you have to convert these Strings in numeric type (int, in this example). Integer.parseInt helps you to convert the String type value into integer type. Now you can add these values into a sum variable and print it on the console by println() function.
Here is the code of program:
public class AddNumbers{
  public static void main(String[] args) {
    System.out.println("Addition of two numbers!");
    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    int sum = a + b;
    System.out.println("Sum: " + sum);
  }
}
Download this example.
Output of program:
C:\vinod>javac AddNumbers.java

C:\vinod>java AddNumbers 12 20
Addition of two numbers!

Sum: 32
In this section, we are going to discuss the control statements. Different types of control statements: the decision making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and branching statements (break, continue and return).
Control Statements   
The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements 

Selection statements:
  1. If Statement:
    This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .

        Syntax:
           
    if(conditional_expression){
                <statements>;
                ...;
                ...;
    }

    Example:
    If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2 = = 0){
     System.out.println("This is even number");
}
2.       
  1. If-else Statement:
    The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates  to "false" i.e. else block is executed if "if" statement is false.

        Syntax:
          
    if(conditional_expression){
                <statements>;
                ...;
                ...;
            }
           else{
                <statements>;
                ....;
                ....;
           } 

    Example:
    If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
     System.out.println("This is even number");
}
else{
     System.out.println("This is not even number");
}
4.       
  1. Switch Statement:
    This is an easier implementation to the if-else statements. The keyword "switch" is  followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.

    Syntax:
       
    switch(control_expression){
            case expression 1:
                <statement>;
            case expression 2:
                <statement>;
               ...
               ...
            case expression n:
                <statement>;
            default:
                <statement>;
        }//end switch

    Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
       case 1:
            System.out.println("Monday");
            break;
       case 2:
           System.out.println("Tuesday");
           break;
      case 3:
          System.out.println("Wednesday");
          break;
      case 4:
          System.out.println("Thrusday");
          break;
      case 5:
         System.out.println("Friday");
         break;
      case 6:
         System.out.println("Saturday");
         break;
      case 7:
          System.out.println("Sunday");
          break;
      default:
           System.out.println("Invalid entry");
           break;
}

Repetition Statements:
  1. while loop statements:
    This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.

    Syntax:
      
    while(expression){
            <statement>;
            ...;
            ...;
        }

    Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
    System.out.println("Num " + i);
    i++;
}
  1.  
  2. do-while loop statements:
    This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.

    Syntax:
       
    do{
            <statement>;
                ...;
                ...;
        }while (expression);

    Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.
int i = 1;
do{
    System.out.println("Num: " + i);
     i++;
}while(i <= 10);
4.       
  1. for loop statements:
    This is also a loop statement that provides a compact way to iterate over a range of values. From a  user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .

    Syntax:
       
         for (initialization; condition; increment or decrement){
                <statement>;
                ...;
                ...;
            }
    initialization: The loop is started  with the value specified.
    condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
    increment or decrement: After each iteration, value increments or decrements.

    Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){
      System.out.println("Num: " + num);
}
Branching Statements:
  1. Break statements:
    The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.

    Syntax:
           
    break;    // breaks the innermost loop or switch statement.
            break label;   // breaks the outermost loop in a series of nested loops.

    Example: When if statement evaluates to true it prints "data is found" and  comes out of the loop and executes the statements just following the loop.

  2. Continue statements:
    This is a branching statement that are used in the looping statements (while, do-while and for) to skip the  current iteration of the loop and  resume the next iteration .

    Syntax:
           
    continue;

    Example:

  3. Return statements:
    It is a special branching statement that  transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of  method.

    Syntax:
           
    return;
            return values;

    return;                     //This returns nothing. So this can be used when method is declared with void return type.
    return expression;           //It returns the value evaluated from the expression.

    Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.

Introduction:  In this section, we will discuss the OOPs concepts along with  fundamentals  used to develop the java applications and programs.
OOP means Object Oriented Programming. This is a technique used to create programs around the real world entities. In OOPs programming model, programs are developed around objects and data rather than actions and logics. In OOPs, every real life object has properties and behavior. This feature is achieved in java through the class and object creation. They contains properties (variables of some type) and behavior (methods). OOPs provides better flexibility and compatibility for developing large applications.
Class: A class defines the properties and behavior (variables and methods) that is shared by all its objects. It is a blue print for the creation of  objects.
Object:  Object is the basic entity of object oriented programming language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class. 
Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been described below :
Encapsulation: Encapsulation is the process of binding together the methods and data variables as a  single entity. This keeps both the  data and functionality code safe  from the outside world. It hides the data within the class and makes it available only through  the methods. Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside. For example, we can create a class "Check" which has a variable "amount" to store the current amount. Now to manipulate  this variable we can create methods. For example to set the value of amount create setAmount() method and to get the value of amount create getAmount() method . Here is the code for "Check" class :
class Check{
  private int amount=0;

  public int getAmount(){
     return amount;
  }
  public void setAmount(int amt){
     amount=amt;
  } 
}
public class Mainclass{
  public static void main(String[] args){
     int amt=0;
     Check obj= new Check();
     obj.setAmount(200);
     amt=obj.getAmount(); 
     System.out.println("Your current amount is :"+amt);

     }
}

Here the data variable "amount" and methods setAmount() and  getAmount() are enclosed together with in a single entity called the "Check" class. These two methods are used to manipulate  this variable i.e. set and get the current value of amount.
Inheritance: Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class(superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.
class A{
  public void fun1(int x){
     System.out.println("int in A");
  }
  
}

class extends A{
  public void fun2(int x,int y){
     fun1(6);  // prints "int in A" 

     System.out.println("int in B");  
  }
}
public class C{
  public static void main(String[] args){
     B obj= new B();
     obj.fun2(2); 
     }
}

In the above example,  class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.
Polymorphism : Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows a object to accept different requests of a client (it then properly interprets the request like choosing appropriate method) and responds  according to the current state of the runtime system, all without bothering the user. 
There are two types of polymorphism :
  1. Compile-time polymorphism
  2. Runtime Polymorphism
In compiletime Polymorphism, method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept in java. 
Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).
class A{
  public void fun1(int x){
    System.out.println("int");
  }
  public void fun1(int x,int y){
    System.out.println("int and int");
  }
}
public class B{
  public static void main(String[] args){
    A obj= A();
           
// Here compiler decides that fun1(int)
 is to be called and "int" will be printed.

    obj.fun1(2);   
// Here compiler decides that fun1(int,int)
 is to be called and "int and int" will be printed.
 
      obj.fun1(2,3);       
  }
}

In rumtime polymorphism, the method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.
class A{
  public void fun1(int x){
     System.out.println("int in A");
  }
  public void fun1(int x,int y){
     System.out.println("int and int");
  }
}

class extends A{
  public void fun1(int x){
     System.out.println("int in C");
  }
}

public class D{
  public static void main(String[] args){
     A obj;
     
     obj= 
new A(); // line 1
     obj.fun1(2);  // line 2 (prints "int in A")
     
     obj=
new C();  // line 3
     obj.fun1(2);  // line 4 (prints "int in C")
  }
}
In the above program, obj has been declared as A type. In line 1, object of class A is assigned. Now in the next line, fun1(int) of class A will be called. In line 3, obj has been assigned the object of class C so fun1(int) of class C will be invoked in line 4. Now we can understand that same name of the method invokes different functions, defined in different classes, according to the current type of variable "obj". This binding of  method code to the method call is decided at run time.

To compile and run a java program we need to install java platform. JDK (Java Development Kit). JDK is the basic set of tools required to compile and run java programs. This section enables you to download JDK and teaches you the steps to install it.
Download and Install JDK (Java Development Kit)
The latest version of jdk is 6 (update 1) at the time of writing the tutorial. You can download the latest version of jdk from http://java.sun.com/javase/downloads/index.jsp. Once you download the exe file you can now install it. Just follow as mentioned:
To install the jdk, double click on the downloaded exe file (jdk-6u1-windows-i586-p.exe) 
Step 1. Double Click the icon of downloaded exe.

You will see jdk 6 update 1 window as shown below.



Step 2: Now a "License Agreement" window opens. Just read the agreement and click "Accept" button to accept and go further.

Step 3: Now a "Custom Setup" window  opens. 

Step 4: Click on "Change" button to choose the installation directory. Here it is "C:\Program Files\ Java\jdk1.6.0_01". Now click on "OK" button.

Clicking the "OK" button starts the installation. It is shown in the following figure.



Step 5: Next window asks to install Runtime Environment

Click the "Change" button to choose the installation directory of Runtime Environment. We prefer not to change it. So click "OK" button.

Step 6: Click "OK"  button starts the installation.

Step 7: Now "Complete" window appears indicating that installation of jdk 1.6 has completed successfully. Click "Finish" button to exit from  the installation process.

Step 8: The above installation will create two folders "jdk1.6.0_01" and "jre1.6.0_01" in "C:\ Program Files\ java" folder.

Step 9: To make available Java Compiler and Runtime Environment for compiling and running java programs , we set the system environment variables. 
First of all select "My Computer" icon and right click the mouse button. Now click on "system Properties" option. It provides the "System Properties" window , click the 'Advanced' tab. Then Click the "Environment Variables" button. It provides "Environment Variables" window. Now select the path in System variables and click 'Edit' button. The"Edit System Variable" window will open. Add "c:\Program Files\Java\jdk1.6.0_01\bin" to 'variable value' and click 'Ok', 'Ok' and 'Ok' buttons. 

Step 10: Now set the JAVA_HOME variable and set its value to " C:\Program Files\Java\jdk1.6.0_01 ". If this variable has not been declared earlier then create a new system variable by clicking on "New" button and give variable name as "JAVA_HOME" and variable value as " C:\Program Files\Java\jdk1.6.0_01 ". Now click "OK". This variable is used by other applications to find  jdk  installation directory. For example, Tomcat server needs "JAVA_HOME" variable to find the installation directory of jdk.

Step 11: Now this is the final step to check that you have installed jdk successfully and it is working fine. Just go to the command prompt and type javac and hit enter key you will get the screen as shown below :

Now you can create, compile and run java programs.


In this section, you will learn to write a simple Java program. For developing a java program you just need  a simple text editor like "notepad". 
Open the notepad and write your program. 
Let's create a class createfirstprogram that will print a message "Welcome to RoseIndia.net" on the console. 



Here is the code of createfirstprogram.java file:
class createfirstprogram{
  public static void main(String[] args) {
    System.out.println("Welcome to RoseIndia.net");
  }
}
Download this example.
Save this program in the specified directory ("C:\Vinod" in this example) with name createfirstprogram.java.  
This class contains  public, static and void java keywords (these are pre-defined words in java which carries specific meaning).
public keyword specifies the accessibility issues of a class. Here, It specifies that method can be accessed from anywhere.
static keyword  indicates that this method can be invoked simply by using the name of the class without creating any class-object.
void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First of all JVM calls the main method of a class and start execution .  JVM (Java Virtual Machine) is responsible for running java programs.
args is a string array that takes values from java command line. It's index starts from '0'. We can access values by writing args[0], args[1] etc.
println() function prints the output to the standard output stream (monitor).
out
represents the standard output stream (monitor).

Now, you are ready to compile and run this program. Open the command prompt and go to the directory ("C:\vinod" in this example) where your program is saved.
Java uses the "javac" command to compile your program (Type javac createfirstprogram.java) . After compiling successfully, you can run it. Java uses the "java" command to execute your program (Type java createfirstprogram). It will print  "Welcome to RoseIndia.net".
Output of program:
C:\vinod>javac createfirstprogram.java

C:\vinod>java createfirstprogram
Welcome to RoseIndia.net

C:\vinod>_
In this section, you will learn about Java variables. A variable refers to the memory location that holds values like: numbers, texts etc. in the computer memory. A variable is a name of location where the data is stored when a program executes.
The Java contains the following types of variables:
  1. Instance Variables (Non-static fields): In object oriented programming, objects store their individual states in the "non-static fields" that is declared without the static keyword. Each object of the class has its own set of values for these non-static variables so we can say that these are related to objects (instances of the class).Hence these variables are also known as instance variables. These variables take default values if not initialized.    
  2. Class Variables (Static fields): These are collectively related to a class and none of the object can claim them  its sole-proprietor . The variables defined with static keyword are shared by all objects. Here Objects do not store an individual value but they are forced to share it among themselves. These variables are declared as "static fields" using the static keyword. Always the same set of values is shared among different objects of the same class. So these variables are like global variables which are same for all objects of the class. These variables take default values if not initialized.          
  3. Local Variables: The variables defined in a method or block of code is called local variables. These variables can be accessed within a method or block of code only. These variables don't take default values if not initialized. These values are required to be initialized before using them.
  4. Parameters: Parameters or arguments are variables used in method declarations. 
Declaring variables
Before using variables you must declare the variables  name and type. See the following example for variables declaration:
int num;            //represents that num is a variable that can store value of int type.
String name;     //represents that name is a variable that can store string value.
boolean bol;    //represents that bol is a variable that can take boolean value (true/false);

You can assign a value to a variable at the declaration time by using an assignment operator ( = ).
int num = 1000;       // This line declares num as an int variable which holds value "1000".
boolean bol = true;      // This line declares bol as boolean variable which is set to the value "true".                                          

Data type: The type of value that a variable can hold is called data type. When we declare a variable we need to specify the  type of value it will hold along with the name of the variable. This tells the compiler that the particular variable will hold certain amount of memory to store values. For example, in the lines of code above num is int type and takes two bytes to hold the integer value, bol is a boolean type and takes one bit to hold a boolean value .
Some common types of data types are used in the programming languages called as the primitive types like characters, integers,  floating point numbers etc. These primitive data types are given below where size represents the memory size it takes, For example, boolean takes a value "true"/"false" in 1 bit memory. It takes value "false" if not initialized (in the case of non-local variables)

Java Primitive Data Types

Data Type
Description
Size
Default Value
boolean
true or false
1-bit
false
char
Unicode Character
16-bit
\u0000
byte
Signed Integer
8-bit
(byte) 0
short
Signed Integer
16-bit
(short) 0
int
Signed Integer
32-bit
0
long
Signed Integer
64-bit
0L
float
Real number
32-bit
0.0f
double
Real number
64-bit
0.0d
In this section, we will discuss about java classes and its structure. First of all learn:  what is a class in java and then move on to its structural details. 
Class: In the object oriented approach, a class defines a set of properties (variables) and methods. Through methods certain functionality is achieved. Methods act upon the variables and generate different outputs corresponding  to the change in variables.
Structure for constructing  java program:
package package_name;

//import necessary packages

import
package_name.*;

Access Modifier
class class_name{
member variables;
member methods;
public static void main(String[] args) {
         ...
         ...
.

       }
}
package: In the java source file you generally use the package statement at header of a java program. We use package generally to group the related classes i.e. classes of same category or related functionality. You have to save your java files in the folder matching the package name as mentioned  in java program.
import : Import keyword is used at the beginning of a source file but after the package statement. You may need some classes, intefaces defined in a particular package to be used while programming so you would have to use import statement. This specifies classes or entire Java packages which can be referred to later without including their package names in the reference. For example, if you have imported util package (import java.util.*;) then you need not to mention the package name while using any class of util package.
Access Modifiers : Access modifiers are used to specify the visibility and accessibility of a class, member variables and methods. Java provides some access modifiers like: public, private etc.. These can also be used with the member variables and methods to specify their accessibility. 
  1. public keyword specifies that the public class, the public  fields and the public methods can be accessed from anywhere.
  2. private: This keyword provides the accessibility only within a  class i.e. private fields and methods can be accessed only within the same class.
  3. protected: This modifier makes a member of the class available to all classes in the same package and all sub classes of the class. 
  4. default : Its not a keyword. When we don't write any access modifier then default is considered. It allows the class, fields and methods accessible within the package only.
static keyword  indicates that this method can be invoked simply by using the name of the class without creating any class-object.
void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First of all JVM calls the main method of a class and start execution .  JVM (Java Virtual Machine) is responsible for running java programs.
args is a string array that takes values from java command line. It's index starts from '0'. We can access values by writing args[0], args[1] etc.
println() function prints the output to the standard output stream (monitor).
out
represents the standard output stream (monitor).

In this section, you will learn to work with command prompt arguments provided by the user. We will access these arguments and print the addition of those numbers. In this example, args is an array of String objects that takes values provided in command prompt. These passed arguments are of String types so these can't be added as numbers. So to add, you have to convert these Strings in numeric type (int, in this example). Integer.parseInt helps you to convert the String type value into integer type. Now you can add these values into a sum variable and print it on the console by println() function.
Here is the code of program:
public class AddNumbers{
  public static void main(String[] args) {
    System.out.println("Addition of two numbers!");
    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    int sum = a + b;
    System.out.println("Sum: " + sum);
  }
}
Download this example.
Output of program:
C:\vinod>javac AddNumbers.java

C:\vinod>java AddNumbers 12 20
Addition of two numbers!

Sum: 32
In this section, we are going to discuss the control statements. Different types of control statements: the decision making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and branching statements (break, continue and return).
Control Statements   
The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements 

Selection statements:
  1. If Statement:
    This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .

        Syntax:
           
    if(conditional_expression){
                <statements>;
                ...;
                ...;
    }

    Example:
    If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2 = = 0){
     System.out.println("This is even number");
}
2.       
  1. If-else Statement:
    The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates  to "false" i.e. else block is executed if "if" statement is false.

        Syntax:
          
    if(conditional_expression){
                <statements>;
                ...;
                ...;
            }
           else{
                <statements>;
                ....;
                ....;
           } 

    Example:
    If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
     System.out.println("This is even number");
}
else{
     System.out.println("This is not even number");
}
4.       
  1. Switch Statement:
    This is an easier implementation to the if-else statements. The keyword "switch" is  followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.

    Syntax:
       
    switch(control_expression){
            case expression 1:
                <statement>;
            case expression 2:
                <statement>;
               ...
               ...
            case expression n:
                <statement>;
            default:
                <statement>;
        }//end switch

    Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
       case 1:
            System.out.println("Monday");
            break;
       case 2:
           System.out.println("Tuesday");
           break;
      case 3:
          System.out.println("Wednesday");
          break;
      case 4:
          System.out.println("Thrusday");
          break;
      case 5:
         System.out.println("Friday");
         break;
      case 6:
         System.out.println("Saturday");
         break;
      case 7:
          System.out.println("Sunday");
          break;
      default:
           System.out.println("Invalid entry");
           break;
}

Repetition Statements:
  1. while loop statements:
    This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.

    Syntax:
      
    while(expression){
            <statement>;
            ...;
            ...;
        }

    Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
    System.out.println("Num " + i);
    i++;
}
  1.  
  2. do-while loop statements:
    This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.

    Syntax:
       
    do{
            <statement>;
                ...;
                ...;
        }while (expression);

    Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.
int i = 1;
do{
    System.out.println("Num: " + i);
     i++;
}while(i <= 10);
4.       
  1. for loop statements:
    This is also a loop statement that provides a compact way to iterate over a range of values. From a  user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .

    Syntax:
       
         for (initialization; condition; increment or decrement){
                <statement>;
                ...;
                ...;
            }
    initialization: The loop is started  with the value specified.
    condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
    increment or decrement: After each iteration, value increments or decrements.

    Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){
      System.out.println("Num: " + num);
}
Branching Statements:
  1. Break statements:
    The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.

    Syntax:
           
    break;    // breaks the innermost loop or switch statement.
            break label;   // breaks the outermost loop in a series of nested loops.

    Example: When if statement evaluates to true it prints "data is found" and  comes out of the loop and executes the statements just following the loop.

  2. Continue statements:
    This is a branching statement that are used in the looping statements (while, do-while and for) to skip the  current iteration of the loop and  resume the next iteration .

    Syntax:
           
    continue;

    Example:

  3. Return statements:
    It is a special branching statement that  transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of  method.

    Syntax:
           
    return;
            return values;

    return;                     //This returns nothing. So this can be used when method is declared with void return type.
    return expression;           //It returns the value evaluated from the expression.

    Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.

Introduction:  In this section, we will discuss the OOPs concepts along with  fundamentals  used to develop the java applications and programs.
OOP means Object Oriented Programming. This is a technique used to create programs around the real world entities. In OOPs programming model, programs are developed around objects and data rather than actions and logics. In OOPs, every real life object has properties and behavior. This feature is achieved in java through the class and object creation. They contains properties (variables of some type) and behavior (methods). OOPs provides better flexibility and compatibility for developing large applications.
Class: A class defines the properties and behavior (variables and methods) that is shared by all its objects. It is a blue print for the creation of  objects.
Object:  Object is the basic entity of object oriented programming language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class. 
Encapsulation, Inheritance and Polymorphism are main pillars of OOPs. These have been described below :
Encapsulation: Encapsulation is the process of binding together the methods and data variables as a  single entity. This keeps both the  data and functionality code safe  from the outside world. It hides the data within the class and makes it available only through  the methods. Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside. For example, we can create a class "Check" which has a variable "amount" to store the current amount. Now to manipulate  this variable we can create methods. For example to set the value of amount create setAmount() method and to get the value of amount create getAmount() method . Here is the code for "Check" class :
class Check{
  private int amount=0;

  public int getAmount(){
     return amount;
  }
  public void setAmount(int amt){
     amount=amt;
  } 
}
public class Mainclass{
  public static void main(String[] args){
     int amt=0;
     Check obj= new Check();
     obj.setAmount(200);
     amt=obj.getAmount(); 
     System.out.println("Your current amount is :"+amt);

     }
}

Here the data variable "amount" and methods setAmount() and  getAmount() are enclosed together with in a single entity called the "Check" class. These two methods are used to manipulate  this variable i.e. set and get the current value of amount.
Inheritance: Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class(superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.
class A{
  public void fun1(int x){
     System.out.println("int in A");
  }
  
}

class extends A{
  public void fun2(int x,int y){
     fun1(6);  // prints "int in A" 

     System.out.println("int in B");  
  }
}
public class C{
  public static void main(String[] args){
     B obj= new B();
     obj.fun2(2); 
     }
}

In the above example,  class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.
Polymorphism : Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows a object to accept different requests of a client (it then properly interprets the request like choosing appropriate method) and responds  according to the current state of the runtime system, all without bothering the user. 
There are two types of polymorphism :
  1. Compile-time polymorphism
  2. Runtime Polymorphism
In compiletime Polymorphism, method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept in java. 
Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).
class A{
  public void fun1(int x){
    System.out.println("int");
  }
  public void fun1(int x,int y){
    System.out.println("int and int");
  }
}
public class B{
  public static void main(String[] args){
    A obj= A();
           
// Here compiler decides that fun1(int)
 is to be called and "int" will be printed.

    obj.fun1(2);   
// Here compiler decides that fun1(int,int)
 is to be called and "int and int" will be printed.
 
      obj.fun1(2,3);       
  }
}

In rumtime polymorphism, the method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.
class A{
  public void fun1(int x){
     System.out.println("int in A");
  }
  public void fun1(int x,int y){
     System.out.println("int and int");
  }
}

class extends A{
  public void fun1(int x){
     System.out.println("int in C");
  }
}

public class D{
  public static void main(String[] args){
     A obj;
     
     obj= 
new A(); // line 1
     obj.fun1(2);  // line 2 (prints "int in A")
     
     obj=
new C();  // line 3
     obj.fun1(2);  // line 4 (prints "int in C")
  }
}
In the above program, obj has been declared as A type. In line 1, object of class A is assigned. Now in the next line, fun1(int) of class A will be called. In line 3, obj has been assigned the object of class C so fun1(int) of class C will be invoked in line 4. Now we can understand that same name of the method invokes different functions, defined in different classes, according to the current type of variable "obj". This binding of  method code to the method call is decided at run time.

No comments:

Post a Comment