Learning Java in just 5 weeks !

Week One Tutorial
Week One Quiz
Week Two Tutorial
Week Two Quiz
Week Three Tutorial
Week Three QUIZ
Week Four Tutorial
Week Four Quiz
Week Five Tutorial
Week Five Quiz
Java Overview
Getting Started Goto Week Two Tutorial→ Goto Week Three Tutorial→
Naming Conventions
Data Type
Operators
Control Statements
Inputs & Output
Arrays

1. Java Overview.

Java Programming formally appeard in 1995 designed by Sun Microsystems. Java generally refers to a combination of three things: the Java programming language (a high-level, object-oriented programming language); the Java Virtual Machine (a high-performance virtual machine that executes bytecodes on a specific computing platform, typically abbreviated JVM); and the Java platform, a JVM running compiled Java bytecodes, usually calling on a set of standard libraries such as those provided by Java Standard Edition (SE) or Enterprise Edition (EE). Java is a simple programming language. Rather than saying that this is the feature of Java, we can say that this is the design aim of Java. When Java is developed, they wanted it to be simple because it has to work on electronic devices, where less memory is available. Now, the question is how Java is made simple? First of all, the difficult concepts of C and C++ have been omitted in Java. For example, the concept of pointers-which is very difficult for both learners and programmers, has been completely eliminated from Java. Next, JavaSoft (the team who developed Java is called with this name) people maintained the same syntax of C and C++ in Java, so that a programmer who knows C or C++ will find Java already familiar.

Note: Pointers have been eliminated from Java because it can crash a program easily in a case like adding two pointers, or forgetting to free memory allotted to variable and pointers can break security Java is an object -oriented programming language. Java programs use objects and classes. What is an object? An object is anything that really exists in the world and can be distinguished from others. Everything that we see physically will come into this definition, for example, every human being, a book, a tree etc.

Java History
In 1990, Sun Microsystems Inc. has conceived a project to develop software for consumer electronic devices that could be controlled by a remote. This project was called Stealth Project but later its name was changed to Green Project. In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patric Naughton, and several others met in Aspen, Colorado to discuss this project. Mike Sheradin was to focus on business development; Patrick Naughton was to begin work on the graphics system; and James Gosling was to identify the proper programming language for the project. Gosling thought C and C++ could be used to develop the project. But the problem he faced with them is that they were system dependent languages and hence could not be used on various processors, which the electronic devices might use. So he started developing a new language. This language was called Oak which was registered by some other company, later it was changed to Java. Why the name Java? James Gosling and his team members were consuming a lot of tea while developing this language.

They felt that they were able to develop a better language because of the good quality tea they had consumed. So the tea also had its own role in developing this language and hence, they fixed the name for the language as Java. Thus, the symbol of Java is tea cup and saucer. By September of 1994, Naughton and Jonathan Payne started writing WebRunner-1 Java-based Web browser, which was later renamed as HotJava. By October 1994, HotJava was stable and was demonstrated to Sun executives. HotJava was the first browser, having the capabilities of executing applets, which are programs designed to run dynamically on Internet. This time, Java's potential in the context of the World Wide Web was recognized. Sun formally announced Java and HotJava at SunWorld conference in 1995. Soon after, Netscape Inc. announced that it would incorporate Java support in its browser Netscape Navigator. Latter, Microsoft also announced that they would support Java in their Internet Explorer Web browser, further solidifying Java's role in the World Wide Web. On January 23rd 1996, JDK 1.0 version was released. Today more than 4 million developers use Java and more than 1.75 billion devices run Java.javaSansar
Learn Java in just 5 Weeks

2. Getting started with JAVA.
You will need JavaScript enabled on your browser. We'll be compiling and running Java programs, so you'll need a Java development environment, such as the Java SDK. You can download SDK for free from Sun Microsystems website and a simple text editor, such as Notepad in Windows or vi in a UNIX environment. This tutorial will walks you through step by step procedure and gives you tools you need to start learning Java Programming and creating your first java program. Have the following lists ready before starting to program in java.

a) How to Download Java SE? Click Here
-Make sure you grab "Java SE Development Kit (JDK)" from the above link.
-Verify that JDK is installed in your computer. Go to DOS command line.
-Start>Run, type cmd in the 'Run window'
-Change directory to C:\Program Files\java (default folder)
-Type dir command.
-Installed JDK will appear in the list such as:
Jdk1.0.6_03
Jre1.5.0_04

b) How to set the Environment Path Variables?
It is more convenient to set the path variables to run the JDK executables (javac.exe, java.exe, javadoc.exe, etc.). If you don't set the PATH variable, you need to specify the full path to the executable every time you run it. Now you have successfully installed JDK in your computer and its time to set the environment path variables. to set the PATH permanently, add the full path of the jdk1.6.0_\bin directory to the PATH variable. -Click Start > Control Panel > System on Windows XP
-Click Advanced > Environment Variables.
-Click New and provide name and value.
-Name = JAVAPath
-Value = C:\Program Files\Java\jdk1.6.0_10\bin
The new path takes effect in each new command window you open after setting the PATH variable.

c) How to get a text Editor?
Obviously, depending on your choice, you can use any word processing editors. There are many text editors available out there. Most of the OSs comes with the notepad included in the system. Now let's use a simple Notepad editor in our tutorial. First step towards our goal is:

  • writing code (creating source file".java")
  • compiling it into bytecode (.class file) and
  • running the bytecode
-Open a Notepad and type the following:
public class MyFirstProgram {
         public static void main(String args[]) {
                 System.out.println("My First Java Program");
          }//End of main method
     }//End of the class 
-Now save the file in the C drive
-When you save the file, make sure to give the same exact filename as the class name of your program i.e. myFirstProgram.java. Please do not forget to give dot java (.java) extension after the filename.
-Open DOS Command
-Navigate to the folder where you had saved the program file (C:\java)
-Type "javac MyFirstProgram.java" and Hit Enter.
If you do not get an exception error, that means you have just compiled your source code to .class file
-Type "java MyFirstProgram" (no extension please) and hit Enter
If you see "My First Java Program" printed out in the command line, then congratulations. You've just written your first java program successfully.
javac: Java Compiler converts java code into byte code
java: Java Interpreter executes java bytecode from class file

3. Naming Conventions in Java.
Naming Convention is the rules followed by java programmers while writing the names of packages, classes, methods etc.
NamesCaseExamples
packageslowercasemydomain.com
fileslowercase.java
classesCapitalizedWithInternalWordsAlsoCapitalizedMyClass
Exception classClassNameEndsWithExceptionClassNotFoundException
InterfaceInterfaceNameEndsWithIfcmydomain.com
constantsUPPER_CASE_WITH_UNDERSCORES DAYS_IN_WEEK
private/protectedfirstWordLowerCaseButInternalWordsCapitalizedmyVar
local variablesfirstWordLowerCaseButInternalWordsCapitalizedmyVar
methodsfirstWordLowerCaseButInternalWordsCapitalizedeatFast


4. Data Type in Java.
Java comes with its standard data types which represents data such as integer numbers. We need variables to store the data. A variable represents a memory location which holds data. Following table represents all the data types available in java programming.
Data TypeMemory Size & Values
byte1 bytes, signed (two's complement), Covers values from -128 to 127
short2 signed byte (two's complement). Covers values from -32,768 to 32,767
int4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647
long8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
float4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative)
double8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative)
char2 bytes, unsigned, Unicode, 0 to 65,535
Apart from above data type, java also has special data type such as String, Boolean and literals. A String represents a group of characters such as 123abc or New York. Boolean expresses only two values true and false such as boolean result=false. A literal represents a value which is stored into a variable directly in the program. For an example: char sex='F';
5. Operators in Java.
Operators are very important part of java programming. If a programmer needs to add two numbers, then he would use addition '+' sign. Such symbols or signs are call operators. Operators are used to manipulate data types. Operators work based on the operator precedence order, the higher the precedence will be evaluated first such as multiplication and division is evaluated first than addition or subtraction.
OperatorMeaningExamplsResult
+Additionx+y15
-Subtractionx-y7
*Multiplicationx*y49
/Divisionx/y2.5
%Modulusx%y2
Java Operators fall into different categories such as follows:
Operator TypeSymbols
Assignment Operator=
Arithmetic Operator+, -, *, /, ++, --, %
Relation Operator<, >, <=, >=, ==, !=
Logical Operator&&, ||, &, |, !, ^
Bitwise Operator&, |, ^, > >, > > >
Compound Asssignment Operator+=, -=, *=, /=, %=
Conditional Operator?:

6. Control Statements in Java.
In Java programming, Sequential statements and Control statement are very popular. Sequential statements are executed one by one whereas Control Statements executed randomly and repeatedly. The following statement is what we call sequential statements.
   System.out.println("My Java Program");
   a=b+c;
   System.out.println(a);
Today the following control statements are available in Java programming;
   if …else statement
   do …while loop
   while loop
   for loop
   for-each loop
   switch statement
   break statement
   continue statement
   return statement
If…Else Statement
If …else statement is used to perform if given condition is true or false. For example let's take a look into following snippet.
public class MyClassOne{
    public static void main(String args[]){
            int num=3;
            if(num==0) //condition1
             {
                System.out.println("This is 0"); //statement1
             }
           else if(num>0) //condition2
             {
                 System.out.println("The correct number is: "+num); //statement2
             }
          else
             {
                 System.out.println("You entered wrong number");
             }
          }
      }
Here if condition1 is true then statement1 will be executed and if condition1 is not true then condition2 is tested. If condition2 is true then statement2 is executed.
Do…While Loop
If we need to repeatedly execute a group of statements, then we use do…while loop. If the condition is not true, the repetition will be stoped. Let's say we want to write a program to print numbers from 1 to 10. Here is the snippet.
   public class MyProgram{
       public static void main(String args[]){
      int a;
      a=1; //beginning number is 1
         do{
         System.out.println(a);
         a++;
         }while(a<=10);
      }
   }
Output of the above snippet will be numbers displaying 1 to 10.
While Loop
while loop works just like do…while loop. The only difference is that 'do…while' loop executes statement first and condition is tested later
   public class MyProgram{
       public static void main(String args[]){
          Int a;
          a=1; //beginning number is 1
             while(a<=10){
            System.out.println(a);
            a++;
            }
      }
   }
For Loop
for loop works just like 'while loop' or 'do…while' loop but for loop repeats for the specified number of time and while loop repeats as long as certain condition is true.
    public class MyProgram{
      public static void main(String args[]){
           for(int a=1; a<=10; x++);
           System.out.println(x);  
       }
   }
For-Each Loop
'for-each' loop is designed to handle the elements of a collection. Collection represents a group of elements. For example java.util package can be considered as a collection. 'for-each' loop repeatedly executes a group of statements for each element of the collection. It executes as many times as there are number of elements in the collection.
Switch Statement
When there are several options and we have to choose only one options from the available ones, we can use switch statement.
   public class MyProgram{
       public static void main(String args[]){
      char color = 'g'; //color is set to 'g'
         switch(color)
         {
         case 'r': System.out.println("Red");
         break;
         case 'g': System.out.println("Green");
         break;
         case 'b': System.out.println("Blue");
         break;
          case 'w': System.out.println("White");
         break;
         default: System.out.println("No Color"); 
         }
     }
   }
Return Statement
'return' statement is used in the method. A method is executed when called from another method. The first method that is executed in a Java program by JVM is main() method and hence if we want to execute any other method we should call it from main(). 'return' statement is used in a method to come out of it to the main() method. Suppose if we want to call a method by the name of myMethod() from the main method. If return is used inside myMethod(), we can also return some value to the main() method. return 1; //returns 1 to calling method main()
return x; //returns x value to calling method main()
return -5; //returns -5
We will write a program that will return a value from a method
   public class MyProgram{
       public static void main(String args[]){
          //call myMethod() and catch the result into sum.
          //since myMethod() is static, we can call int using classname.methodname()
          int sum = MyProgram.myMethod(10);
          //display the result now
          System.out.println("Result: "+sum);
      }
      //this method caluculates square value and returns it to main()
      static int myMethod(int num){
      return num*num;//return square value to main method
      }
   }


7. Inputs & Output in Java.
Input and Output both are often data but only difference is Input represent data given to a program and output represents data displayed as a result of a prgram execution. Let us take following example:
int a=10;
   int b=12;
   int c=a+b;
   System.out.println(c);
   
In the above code snippet, what we see is inputs given are only 10 and 12. when you execute it, it will display only the sum of a+b. What if we want to accept these numbers from keyboard and a stream is required to accept input from keyboard. There are two type of streams input stream and output stream. stream carries data from one place to another. All streams are represented by classes in "java.io" package. System class is available in java.lang package and System class has following fields:
a) System.in: This represents InputStream object which by default represents standard input device i.e. keyboard
b) System.out: This represents PrintStream object, which by default represents standard output device, i.e. monitor
c) System.err: This field also represents PrintStream object, which by default represents monitor and is used to display error message. Now, its time to enter input from keyboard and display output in the monitor. Let us see the following code snippet:
import java.io.*;
public class Accept{
    public static void main(String arg[]) throws IOException
    {
       //create a BufferedReader object to accept data from keyboard
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       //Ask for char and read it
       System.out.print("Enter a character: ");
       char ch = (char)br.read();

       //display the character
       System.out.println("You have entered: " +ch);
    }
}
8. Arrays in Java.
An array represents group of elements of same data type. It can store a group of elements such that we can store a group of int values in the array. What we need to understand is that using arrays will simplify the programming by replacing a lot of statements by just one or two statements. There are two types of arrays:

a) Single Dimensional Arrays (1D Array)
Single dimensional array represents a single row or column of elements. For instance grades obtained by a student in 5 different subjects. To represent one dimensional array, we use single squar braket"[]". There is two ways to create one dimentional array int grades[] = {55, 65, 75, 85, 95}; //declare grades[] and initialize with 5 elements or

int grades[] = new int[5];
  grades[0]=55;
  grades[0]=65;
  grades[0]=75;
  grades[0]=85;
  grades[0]=95;
Let us create a code snippet for one dimensional array using first method
   public class MyArray
   {
       public static void main(String args[])
      {
           int grades[] = {55, 65, 75, 85, 95};
          for(int i=0; i<5; i++)
          {
               System.out.println(grades[i]);
          }
      }
   }    
b) Multi Dimensional Arrays (2D, 3D etc. Arrays)
Multi Dimensional Arrays represents 2D, 3D,...arrays which are combinations of several arrays. For instance, a two dimensional array is a combination of two or more 1D arrays whereas 3D arrays are combination of two or more dimensional arrays. Let us write a code snippet for grades obtained by a student previously in 5 different subjects. Now we will have 3 students and 5 different courses for each in two dimensional arrays.
 public class MyArrayOneD
 {
     public static void main(String args[])
    {
         int grades[] []= {{55, 65, 75, 85, 95}, {56, 66, 76, 86, 96}, {57, 67, 77, 87, 97}};
         for(int i=0; i<3; i++)//rows
        {
             for(int j=0; j<5; j++)//columns
            {
                 System.out.print(grades[i][j]+"\t");
            }
                 System.out.println();//next line
        }
     }
  }
Ok now let us have snippet with second method but giving you the same output as in preceding instance.
public class MyArrayOneD{
         public static void main(String args[]){
        int grades[] [];
       grades= new int[3][5];
       grades[0][0]=55;
       grades[0][1]=65;
       grades[0][2]=75;
       grades[0][3]=85;
       grades[0][4]=95;
       grades[1][0]=56;
       grades[1][1]=66;
       grades[1][2]=76;
       grades[1][3]=86;
       grades[1][4]=96;
       grades[2][0]=57;
       grades[2][1]=67;
       grades[2][2]=77;
       grades[2][3]=87;
       grades[2][4]=97;

        for(int i=0; i<3; i++)//rows
       {
            for(int j=0; j<5; j++)//columns
           {
                System.out.print(grades[i][j]+"\t");
           }
                System.out.println();//next line
       }
    }
   }

Week One Quiz

Learning java in just 5 weeks...


Please answer the following questions to proceed to week two tutorial

Q.1: What is the reason that pointer was eliminated from JAVA?

a) If forgotten to free the memory allotted to a variable it may crash.
b) Using pointers was a potential threat to security as pointer break security.
c) Pointers are used to built program such as computer viruses and hacking program.
d) All of the above.
Check the correct answer

Q.2: What is the right method to print the contents to display in monitor?

a) print ("My First Java Program");
b) printstream obj.print("My First Java Program");
c) System.out.println("My First Java Program");
d) None of the above.
Check the correct answer

Q.3: What is the main difference between print() and println()?

a) Both are not used in Java programming.
b) Both are used to print text but print () method prints text and retains cursor in the same line.
c) Both are used to print text but println () method prints text and kicks the cursor to the next line.
d) Both a & b are correct.
Check the correct answer

Q.4: Constants represent fixed values which should be written in the following naming convention?

a) Constants should be written by using all capital letters
b) The first word starts with a small letter and second word onwards start with a capital letter.
c) The first word and other consecutive words all start with capital letter.
d) All keywords should be written by using all small letter.
Check the correct answer

Q.5: what does 0.01 number represent in java data type category?

a) short
b) int and float
c) double and float
d) double
Check the correct answer

Q.6: The following code snippet falls into what operators category?
System.out.println("x>y : "+(x>y));

a) Arithmetic Operator
b) Relational Operator
c) Logical Operator
d) Bitwise Operator
Check the correct answer

Q.7: Look at the following code snippet and find out the right answers?

  public class MyProgram{
      public static void main(String args[]){
         int x;
         x=1; //beginning number is 1
         do{
         System.out.println(x);
         ++x;
         }while(x<=10);       }    } 
a) The first number will display 1 as value of x is already 1.
b) x++ will increment the value of x by 1 hence the value of x becomes 2.
c) As long as x value does not exceed 10, the loop repeats and number displays from 1 to 10.
d) None of the above.
e) a, b, and c all are correct.
Check the correct answer

Q.8 Find out incorrect answer from the following list?

a) System.exit(0)does not exist in Java
b)return statement is used inside a method to come out of it.
c) System.exit(0)is used in any method to come out of the program.
d) System.exit(0) terminates the program normally whereas
System.exit(1) terminates the program because of the some program error encountered.
Check the correct answer

Q.9 Arrays are stored on what memory?

a) Arrays are stored in Static Memory.
b)Static Memory is used to store arrys as well as variable, object etc. in Java.
c) Arrays are stored in Dynamic memory by JVM.
d) Arrays are stored in Dynamic Memory and variable or object are stored in Static Memory.
Check the correct answer

Q.10 Write a code that puts 45 into row 2 column 3 ?

------Column 0Column 1Column 2Column 3Column 4
Row 05565758595
Row 15666768696
Row 25767778797
grades[0][0], grades[0][1], grades[0][2], grades[0][3], grades[0][4];
grades[1][0], grades[1][1], grades[1][2], grades[1][3], grades[1][4];
grades[2][0], grades[2][1], grades[2][2], grades[2][3], grades[2][4];
a) grades[3][2]=45;
b) grades[2][3]=45;
c) grades[3][1]=45;
d) grades[0][2]=45;
Check the correct answer

Answers of the Week One tutorial questions



Q.1. Correct answer is d.



Q.2. Correct answer is c.



Q.3. Correct answer is d.



Q.4. Correct answer is a.



Q.5. Correct answer is d.



Q.6. Correct answer is b.



Q.7. Correct answer is e.



Q.8. Correct answer is a.



Q.9. Correct answer is c.



Q.10. Correct answer is b.



Week Two Tutorial

Strings in Java
StringBuffer & StringBuilder ← Back Week One Tutorial Goto Week Three Tutorial→
OOPS in Java
Classes & Objects
Methods in Java
Inheritance in Java
Strings in Java

A group of characters are called 'Strings'. For example, in a bank, there are credit card numbers, names, and addresses etc. which all are strings. String is an object of String class from the java.lang package. There are three ways to create strings in Java Programming: We can assign a group of characters to a string type variable. Here JVM creates an object and stores string "David" into that object.

String name="David";
We can use 'new' operator to create an object to String class and store String 'David' into that object as follows:
String name= new String("David");
Third way of creating strings is converting characters arrays into strings as follows:
char ch[]={'D', 'a', 'v', 'i', 'd'}
String name= new String(ch);
Now the String object ch contains the string 'David' Java comes with some standard class Methods. Such as follows:
String concat(String s)
int length();
char charAt(int i)
boolean equals(String s)
int indexOf(String s)
Let us have a code snippet which covers few of the above method including how to create strings.

public class MyString{
          Public static void main(String args[]){
          String n1="David"; 
          String n2= new String("MacCain");
          System.out.println("My First Name is:"+n1);//display first string
          System.out.println("My Last Name is: "+n2);//display second string
    
          System.out.println("Length of first name is:" +n1.length());
          System.out.println("My full name is:" +n1.concat(n2));//concatenate two string
      }
  }

We have been able to create two string objects, measure the length of characters and we were able to concatenate two strings in one line in the example above. Result of the above code will look like this:
My First Name is: David
My Last Name is: MacCain
Length of first name: 5
My full name is: David MacCain
Let us do some String Comparison here. If we want to compare two strings, we will not be able to use relational operators like <, >, == etc. We can use method like compareTo(), equals() to compare two strings. Here is an instance of code to expose the string comparison.

public class MyString{
         Public static void main(String args[]){
         String n1="David"; 
         String n2= new String("David");
         if(n1==n2){
         System.out.println("Both are same");
         }
         else{
         System.out.println("Both are not same");
         }
     }
   }
When you run above code, can you guess what would be the output? Output will be: Both are not same. Because we can not use equal sign '==' to compare two strings. If we use a compare method equals() replacing '==' sign, it might solve our problem. Let us replace if(n1==n2) with the if(n1.equals(n2)) and run the code. Yes this time we get the output: Both are same.

StringBuffer and StringBuilder in Java

StringBuffer class is used to represent character that can be modified. It means StringBuffer class objects are mutable unlike Strings that we studied in previous chapter. Mostly StringBuffer is used for concatenation or manipulation of the strings. A StringBuffer implements the mutable sequence of the characters. We can create StringBuffer objects in two ways.
By using 'new' operator and passing the string to the object such as:

StirngBuffer strb = new StringBuffer("My Java");
and By allotting memory to the StringBuffer object using 'new' operator and later storing it into it such as:
StirngBuffer strb = new StringBuffer();
Here we are creating a StringBuffer empty object but not passing any string to it. StringBuffer will be created with 16 characters with default values.
StringBuffer strb = new StringBuffer(30);

What above code explains is that StringBuffer is created with 30 characters capacity. Now, is it possible to store more than 30 characters? Yes because StringBuffer has mutability feature, it can be modified. We can use append(), or insert() method to do it.

Let us have a code snippet to reflect preceding chapters.

import java.io.*;
public class MyStringBuffer{
    public static void main(String args[]) throws IOException
    {
       StringBuffer strb= new StringBuffer();//creates empty stringbuffer object
      BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); //input from keyboard

      System.out.print("What is you First Name: ");
      String fn = br.readLine();

      System.out.print("What is your middle name:");
      String mn = br.readLine();

      System.out.print("What is your last name:");
      String ln = br.readLine();
      //append first name and lastname
      strb.append(fn);
      strb.append(ln);
      //display only first name and last name upto this point
      //System.out.println("My name is: " + strb);

      //lets insert middle name
      int n = fn.length(); //n represent no. of characters
      strb.insert(n, mn);//insert middle name after n characters
      System.out.println("My full name is:"+ strb);//display full name now 
   }
} 

We have tried to append first name and last name and we were able to print out the results displaying first and last name in the monitor. Then, we realized that we'd missed the middle name. How do we append middle name, then? By using insert() method, we can append middle name as in above example code.

StringBuilder Class.
We have had StringBuilder Class only after JDK1.5 which contains same sort of features as StringBuffer Class does. StringBuilder Class is also mutable and modifiable as StringBuffer.

StringBuilder strb = new StringBuilder ("David");
StringBuilder strb = new StringBuilder ();
StringBuilder strb = new StringBuilder (30);

Only difference between these two classes are StringBuffer is synchronized by default while StringBuilder is not.

Learn Java

OOPs in Java

Programmers have firmly followed Procedural oriented approach for several decades and there is sudden shift in the software industry for new approach, called OOPs (Object Oriented Programming). Fortran, Pascal, C etc. languages were procedural because these language use procedural or functions to perform a task. Languages like C++, Java are called Object Oriented Programming.

In procedural method, programmers write set of functions to achieve one task, and whenever he wants to perform new task, then he would be writing a new set functions hence there will be no reusability. If programmers can write the new modules with the help existing old modules, that would be more easy and quick. Due to these reason, a new approach of object oriented programming emerged in the computer software market.

Features of Object Oriented Programming

Class & Object in Java
Infact, whole concept of OOPs is derived from the single notion called object. An object could be anything that exists in the world and can be distinguished from others such that a person, a ball, or a dog etc. All the existing objects have their properties and they can perform some actions such as walking, rolling, barking etc. Let us take an example as an object 'David' person. David is an object and David exists physically and he's got properties like name, sex, color and David can perform actions such as talking, eating etc. Let us put it in the code snippet

String name
Char sex;
int age;

So, above properties can be similar to other objects such as Mohan who have the same characters (properties) as David. Now what we can think of is they both fall into one class called 'Person' and share the same properties. Now we can say person do not exists but David and Mohan do exist. Another example can be an Animal class and a dog, a tiger, a lion all objects from class Animal. Let us draw a code snippet for creating a class called 'Animal'.

public class Animal
{
    //properties of an Animal class & variables
    String name;
    int size;
    //Action done by Animal class & method
    void eat()
    {  }
    void sleep()
    {  }
}

Now a class model has been built with two variables (name, size) and two methods eat(), sleep(). Let us create an object out of above class Animal.

 Animal Dave = new Animal();

Encapsulation in Java:
Encapsulation (Hiding Information) is one of the important features of OOPs concepts. Booch says: "Encapsulation is the process of hiding all of the details of an object that do not contribute to its essential characteristics". Data (variables), Code (methods) in the class are binded together. Variables and methods are called 'members' of the class. If variables are declared by using java keyword 'private', this indicates that variables are only accessible within a class not outside of the class. If a method for a class is declared by using java keyword 'public', it means it is accessible from inside and out of the class. To use those private variables, only way is to go through method and outsiders will not know what is declared in the variables. Outsiders can only use and get results. Hence Encapsulation is the protective mechanism for the members of a class that helps protect sensitive data and code of the software programs.

We will declare variables as 'private'. 'private' is called access specifier which makes the members of a class not to be accessible outside the Animal Class. To access these variables we use methods which generally declared as public. Let us have a code snippet which reflects encapsulation in java. Here we build a class 'Animal' and declare its variable as private.

public class Animal
  {
     //properties of an Animal class & variables
    private String name;
    private int size;
    //Action done by Animal class & method
    public void talk()
    {
     System.out.println("I am a:" + name);  
     System.out.println("My size is: "+ size);
    }
  }

Only talk() method can access to those private variables and by calling talk() method using Animal class object, we can make Animal talk for us.

Abstraction in Java
One of the most significant features of Java is 'Abstraction'. It is a technique of choosing common features of objects and methods. There might be too much data in the class and which a user do not require all of them. So using abstraction technique, we can hide unnecessary data and retrieve only the essentials data. Let us take an example of an accountant in a bank. An accountant can view/update its customer informations such as customer name, account number, balance etc. but he/she may not be able to view/update bank's annual profit, or loss amount which is only be available to bank's managers. So these unnecessary data for an accountant are abstracted from him.

public class Bank
    {
        //properties of a Bank class & variables
       private String name;
       private int acct;
       private double balance;
       private double profit;
       private double loss;

       public void viewAccountant()
       {
           System.out.println("Customer Name:" + name);  
          System.out.println("Customer Account Number: "+ acct);
          System.out.println("Customer Account Balance: "+ balance);

       }
    }

In the above code snippet we have been able to abstract unnecessary data and made it available only necessary data to an accountant. Obviously he can not access to bank's annual profit and loss data.

Inheritance in Java
We inherit some of the physical characteristics from our parent. Some thing like that in Java programming, new class can be created by inheriting from an existing class. Newly created class is called derived class or sub-class and original class is called base class or super class. Let us have a code snippet to understand Inheritance in more details.

 public class A
   {
       String name;
      int acct;
      public void method1()
      {  }
   }
 public class B extends A
         {
         double salary;
     }
      public void method2()
     {  }
    }

We can derive all the qualities of the members of class A to members of class B as well as we are able to define new variable for class B. Java keyword 'extends' is used to inherit Class A's characteristics to Class B. if we create an object from class B, it inherits all the members of Class A as well as of class B. Inheritance is a significant feature of java programming as it makes easy to manage code, conveniently we can create another class from existing class.

Polymorphism in Java
'Poly' meaning 'many' and 'Morphos' meaning 'forms', 'Many Forms', comes from Greek language which describes an ability to generate different many forms. Moreover, it is a technique to redefine methods for derived classes. Such as given a super class shape polymorphism allow redefining different area methods for any number of derived classes, such as circle, rectangle, and triangles. So programmer can use same method call to perform different operations.

public class AnimalTest
    {
        public static void main(String args[])
           {
               Animal animal = new Animal( "tiger");
              animal.talk( );
              Animal animal = new Animal( "Lion");
              animal.talk( );
              Animal animal = new Animal( "Elephant");
              animal.talk( );

          }
    }

In Polymorphism, a single variable can be used with different objects of related classes. We can use variable with dot (.) notation with the method() to invoke the method. Such as:

 variable.method()
mentioned in the above example.

Classes & Objects in Java

We discussed about classes and object little bit in previous chapter. Now we will discuss more about them. An object is the instance of the class as an object is created/instantiated from a class. That is why class is called a model for objects. All the variables and methods created in the class can be inherited to the instance of the class.

class Animal
{
   //instance variables
   String name;
   int size;
   //actions or methods
   void talk()
   {
       System.out.println("Animal has names");
      System.out.println("Animal has size");
   }
}

We observe above that java keyword 'class' is used to create a class following with the class name. We declare instance variable and methods for the class. Since the method has void java keyword, it means no result is returned and it does not take any data from us also. Now we will create an object out of the above class.

Animal animal1 = new Animal();

Animal is the class and animal1 is object name. so 'animal1' is reference of Animal object. 'new' operator is used to create object. When object is created, it is stored in 'Heap' memory. Once object is stored, JVM creates a unique reference number called
hash code number
for the object (animal1) below. Let us create a class 'Animal' and an object 'Lion' to an Animal class. and we will make it hash code display as well.

class Animal
{
   //instance variables
   String name;
   int size;
   //actions or methods
   void talk()
    {
       System.out.println("Animal has:" + name);
      System.out.println("Animal has:" + size");
    }
} 
class DemoClass
{
  public static void main(String args[])
    {
     Animal animal1 = new Animal();
     animal1.talk();
     //finding hash code of the object
     System.out.println("Hash Code is: " +animal1.hashCode());
    }
}

Output of the above code snippet would be as follows:

Animal has: null (we got null value because we did not initialize instance variables)
Animal has:0 (we got null value because we did not initialize instance variables )
Hash Code is: 25669322

Using reference variables, we can refer to the instance variables and methods such as:

 animal1.name;
animal1.talk(); 

How to Initialize Instance variables in Java

public class DemoInitialize
{
    public static void main(String args[])
    {
       Animal animal1 = new Animal(); //create Animal class object
      animal1.size = 200; //initialize variables using object reference (animal1)
      animal1.talk();
    }
}

Access Specifiers
Let us see how data can be overwritten if access Specifiers is not defined. We will have following code snippet:

class Animal
{
   String name = "Lion"; //instance variables
   int size = 150; //instance variables
   void makeNoise() {
      System.out.println("It is a :" + name);
      System.out.println("It weighs :" + size);
   }
} 
class DemoSpecifier
{
   public static void main(String args[])
   {
      Animal animal1 = new Animal();
     animal1.name = "Tiger";
     animal1.size = 200;
     animal1.makeNoise(); //calling animal makeNoise() method
   }
}

As we clearly see that we did not initialize Animal class with 'private keyword', as a result DemoSpecifier class can access these instance variables and overwrite the value. To protect from overwriting or accessing data from outsider, we use java keyword 'private'. Here is how we can declare instance variables by using 'private' key.

private String name = "Lion";
private in size = 150;

Access Specifier is the keyword that specifies how to access to the variables and methods of the class. There are four types of access specifiers in Java.
public: public access specifier cab be used from inside and outside of the class.
private: private access specifier is only accessible within same class by the methods but not accessible from outside the class from other programs.
protected: protected members of a class is accessible from inside and outside of the class but only within the same directory.
default: If no access specifier is defined, then Java will provide a default specifier which is accessible inside and outside of the class but within the same directory.

Constructor: Constructor is like method in java which is used to initialize instance variables. This is third possible ways of initializing instance variables. The only goal of constructor is to initialize instance variables.

Constructor's name should be similar to Class's name
Constructor's name should end with opening & closing braces
such as:
Animal( )
{   
}
Constructor may have variables in it which is called constructor's parameters. Constructor's parameters are used to receive data from outside into the constructor. Constructor does not return value and do not use 'void'. During the creation of object, if nothing is passed to the object, the default constructor is called executed. If some values are passed to the object, then parameterized constructor is called. A Constructor is called once per object. Such as if an object is created, and constructor is called. If we create second constructor, again constructor is called. Constructor is called concurrently when an object is created. Here is a simple code snippet for constructor.
Animal(String s, int k)
{
}
 
Animal tiger = new Animal();//default constructor is called
Animal tiger = new Animal("Tiger", 150);
//Parameterized constructor will receive "Tiger" and size =150

Let us have code snippet with constructor.

public class Animal {
    private String name;//instance variables
    private int size; //instance variables
    //default constructor
    Animal(){
    name = "Tiger";
      size = 150;
    }
    void makeNoise() //actions or methods
    {
       System.out.println("It is a :" + name);
      System.out.println("It weighs :" + size);
    }
}
public class DemoAnimal 
{
    public static void main(String args[])
    {
       Animal tiger = new Animal();//create a Animal object = tiger
      tiger.makeNoise();//calling makeNoise()method.
   
      Animal lion = new Animal();//creating another object = lion
      lion.makeNoise();//calling makeNoise() method.
    }
}

Output would be:
It is a :Tiger
It weighs :150
It is a :Tiger
It weighs :150
As we noticed above that both the objects tiger and lion have same output Tiger and 150 respectively. We will resolve this problem by using parameterized constructor which takes data from outside and initialize instance variables with that data.

public class Animal 
{
    private String name;//instance variables
    private int size; //instance variables
 
    Animal()//default constructor
    {
       name = "Tiger";
        size = 150;
    }

    Animal(String s, int k)//parameterize constructor
    {
       name = s;
        size = k;
    }
    void makeNoise() //actions or methods
    {
        System.out.println("It is a :" + name);
       System.out.println("It weighs :" + size);
    }
}
public class DemoAnimal 
{
   public static void main(String args[])
   {
        Animal tiger = new Animal();//default constructor is called.
       tiger.makeNoise();//calling makeNoise()method.
   
       Animal lion = new Animal("Lion", 180);//parameterized constructor is called
       lion.makeNoise();//calling makeNoise() method.
   }
}

Output would be:
It is a :Tiger
It weighs :150
It is a :Lion
It weighs :180

So, what we understand from above code that we have parameterized constructor String s; and int k; and these parameter receive data from outside as from DemoAnimal class such as:

Animal lion = new Animal("Lion", 180);
. Now 'Lion' is copied into parameter s, and 180 pound is copied to parameter k and from there, these values are copied to original instance variables: name, and size. If we do not pass any values while creating a new object, then default constructor is called which is:
Animal tiger = new Animal();

Methods in Java

Method performs an action in Java which is a set of statements. Action is i.e. calculation, processing data etc. Method name begins with lower case i.e. sqrt() method which calculates square root value. Method contains method name, parameters, method return data type, and method body. This should look as follows.

returndatatype methodName(parm1, parm2,…)
int sqrt(int num)
When Return data type is 'void', it does not return any value and do not accept data from outside and void method comes with the pair of empty braces '()'and method never returns more than one value such as:
return x, y; 
is invalid statement
void methodName()
Method body looks as follows:
{
Statements;
}
 
{
int i=a+b;
System.out.println("Total sum is:" +i);
}
If we want to return value then we will have statement look as follows:
{
int i = a+b;
return i;
}
Let us create a code snippet that explains methods in detail.

public class Calc1 
{
    private double num1, num2;//instance variables
    Calc1(double a, double b)//parameterized constructor
    {
        num1 = a;
         num2 = b;
    }
    double sum() //actions or methods
    {
        double tot = num1+num2;
       return tot;
    }
}
public class DemoCalc1 
{
    public static void main(String args[])
    {
        Calc1 c = new Calc1(12, 12.6);//new object is created and pass values to constructor
       double x = c.sum();//calling sum()method and storing total of num1+num2 into x  
    }
}

In the above example, sum() method returns the total sum and store the sum into x. and above method is called instance method as it is acting on the instance variables. Method that is not acting on the instance variables is called static method and can not access to instance variable but if variable is declared as 'static', then static method can access to static variables. Static variable is also called 'class variable' and static method is also called 'class method'.

Similarly, local variable or parameters declared inside the method can not be accessed outside the methods such as:

   //instance variable 
   private int x;
   void testMethod(int x):
   {
   x=x;
   }
In the above code, the local variable is x and only accessible within methods. Now notice that we can see above that the instance variable and local variable are conflicting as both of them are holding the same variable. How do we deal in this kind of situation? Java keyword
'this'
is used to handle this problem. 'this' keyword refers to the object of the classes where it has been used. Members of the class, instance variable, constructors, methods are referenced by 'this'.

public class Test
{
    private x;//instance variables
    Test()//default constructor
    {
       this(10) //calling present class's default para constructor and pass value 10
      this.sum(); //call present class's method
    }

    Test(int x)//parameterized constructor
    {
       this.x = x; //present class's instance variable
    }
    void sum() //actions or methods
    {
       System.out.println("Sum is: " +x);
     }
}
public class DemoThis 
{ 
    public static void main(String args[])
    {
       Test T = new Test();//new object is created and pass values to constructor 
    }
}

OUTPUT will be:
Sum is: 10
An object 'T' is created. Default constructor Test is executed passing value 10 to the instance variable x. Hence, present class's this.x=x; instance variable is initialized and executed giving the result = 10.

Setter & Getter Methods
Methods that work on the instance variables are called Instance Methods. Instance methods are called from the object using

objectName.methodName()
and they can access instance variable as well as static variables. There are two types of Instance methods:
a) Getter or Accessor Method
b) Setter or Mutator Method
Getter or Accessor Method can only access or read instance variable whereas Setter or Mutator method can access and modify instance variable.
Let us write a code snippet to reflect setter and getter methods

public class TestSetterGetter 
{
     private String name;//instance variables
    private char sex;

    void setName(String name)//Setter method to store data
    {
       this.name = name; 
    }
    void setSex(char sex)//Setter method
    {
       this.sex = sex; 
    }
    String getName() //Getter methods to access or read only
    {
       return name; 
    }
    char getSex() //Getter methods to access or read only
    {
       return sex; 
    }
 }
}
public class DemoThis
    {
     public static void main(String args[])
    {
         TestSetterGetter sg= new TestSetterGetter();//new object is created 
        sg.setName("David"); //store data
        sg.setSex('M'); //storing data

        System.out.println("Name:" +sg.getName()); //access data from object
        System.out.println("Gender:" +sg.getSex());
    }
}

OUTPUT will be:
Name: David
Gender: M

How to pass primitive data to Methods?
Primitive data types such as byte, int, short, long etc can store only single value, and they can be passed to methods by values. And only a copy of those data will be passed. Which means any changes taken place inside the method will not impact to the values outside the methods.

public class TestPassValue
{
    int x; //instance variables
    void sum(int x)
    {
       this.x=x+1;
    
}
public class DemoThis
{
    public static void main(String args[])
    {
       int x =12;//primitive data
      TestPassValue pv= new TestPassValue();//new object is created 
      pv.sum(x); //call sum method and pass primitive data
      System.out.println("Sum is:" + x); //display data
    }
}

OUTPUT will be:
Sum is: 12

How to pass objects to Methods?
The Class's object can also be passed to methods and return objects from the methods. Reference of the class is declared as parameter to pass object to method. As an example, let us say:

Person theMethod(Person obj1)
{
 statements;
 return obj1;
}
Here theMethod() takes Person class object and Person class is declared in parameter of the method and method returns obj1. Similarly we can pass an array to methods and return arrays from the methods. Let us see how it works:
String[] myMethod(String arr[ ])
In the above code snippet, single dimensional array of String type 'arr' is passed to method 'myMethod.

Inheritance in Java

What is Inheritance in Java? Inheritance simply means to inherit the characteristics from the original class. New classes/objects can be created by inheriting few or all the members of the original class allowing the newly created class to perform exactly what the base class can perform. So Inheritance relationship is considered as transitive. 'extends' java keyword or clause is used to inherit characteristics from base class or super class to subclass or derived class.

public class Animal 
{
    String name;//instance variables
    int size; //
 
    void setName(String name)//store data
    {
       this.name = name;
    
    void setSize(int size) //actions or methods
    {
      this.size = size;
    }
    String getName(){
       return name;
    }
    int getSize(){
       return size;
    }
}
public class Tiger extends Animal 
{
  int weight;//variable for only Tiger class
  void setWeight(int weight){
     this.weight = weight;
  }
  int getWeight(){
    return weight; 
  }
}

public class TestAnimal{
   public static void main(String args[]){
       Tiger t = new Tiger();
       t.setName("Tiger");
       t.setSize(20);
       t.setWeight(200);
       System.out.println("Name:" + t.getName());
       System.out.println("Size:" + t.getSize());
       System.out.println("Weight:" + t.getWeight());
    } 
}

Super class members are always available for subclass because subclass contains a copy of super class. So the advantage of Inheritance is saving lot of space and easy to develop hence allowing to grow the productivity and efficiency. Programmer can reuse the super class's characteristics without rewriting the whole code. Java keyword 'super' is used to access to super class. If we create an object to super class, we will only be able to access super class members but not be able to access subclass object. In contrary, if an object is created to subclass, both super class members and subclass members can access to it. Super can be used to refer to super class variables as

super.variable
, super class method as
super.method()
, and super class constructor as
super(values)

public class SuperClassOne 
{
    int j = 10; //super class variables
    void display()//super class method
    {
       System.out.println("Sum is:" + j);
    }
}
public class SuperClassTwo extends SuperClassOne{
    int j = 15; 
    void display() 
    {
       System.out.println("Sum is:" +j);
      super.display();//using super to call super method
      System.out.println("Sum is:" + super.j); //to call super variable
    }
}
public class TestSuperClass {
    public static void main(String args[]){
       //creating subclass object
      SuperClassTwo sct = new SuperClassTwo();
      sct.display();
    }
}

what is 'Protected Specifier'?

When private members of the super class are restricted to sub classes. When we want to access private super class member from subclass, we can use java keyword

'protected'
(specifier). So protected is used in the super class to make members available directly to its sub classes.
public class Shape 
{
    protected double x;//protected specifier variable
    Shape(double x) //parameterized constructor
    {
       this.x=x;
    }
}
public class Square extends Shape{
    Square(double x)//calling super class Shape and send i value
    {
        super(x);
    }
    void area()
    {
        System.out.println("Square Area:" +(x*x));
    }
}
public class ShapeDemo 
{
    public static void main(String args[])
    {
    Square sq = new Square(3.5);//displaying square area
    sq.area();
    }
}

There are two types of Inheritance: 
Single and Multiple Inheritance. Simply put, one super class and many sub classes is single Inheritance where as multiple super classes and one or more sub classes is Multiple Inheritance. The concept of Multiple Inheritance is true with C++ but in Java, no more Multiple Inheritance is accepted or allowed. Multiple Inheritance creates confusions amongst programmers. To accommodate Multiple Inheritance, programmers prefer using Interface such as:
Class TestClass implements interfaceOne, interfaceTwo,…
Now, TestClass can have all the members of interfaceOne, and interfaceTwo inherited to it.

Week Two Quiz

Strings in Java
StringBuffer & StringBuilder
OOPS in Java ←Back Week One Tutorial Goto Week Three Tutorial→
Classes & Objects
Methods in Java
Inheritance in Java
Strings in Java

A group of characters are called 'Strings'. For example, in a bank, there are credit card numbers, names, and addresses etc. which all are strings. String is an object of String class from the java.lang package. There are three ways to create strings in Java Programming: We can assign a group of characters to a string type variable. Here JVM creates an object and stores string "David" into that object.

String name="David";
We can use 'new' operator to create an object to String class and store String 'David' into that object as follows:
String name= new String("David");
Third way of creating strings is converting characters arrays into strings as follows:
char ch[]={'D', 'a', 'v', 'i', 'd'}
String name= new String(ch);
Now the String object ch contains the string 'David' Java comes with some standard class Methods. Such as follows:
String concat(String s)
int length();
char charAt(int i)
boolean equals(String s)
int indexOf(String s)
Let us have a code snippet which covers few of the above method including how to create strings.

public class MyString{
          Public static void main(String args[]){
          String n1="David"; 
          String n2= new String("MacCain");
          System.out.println("My First Name is:"+n1);//display first string
          System.out.println("My Last Name is: "+n2);//display second string
    
          System.out.println("Length of first name is:" +n1.length());
          System.out.println("My full name is:" +n1.concat(n2));//concatenate two string
      }
  }

We have been able to create two string objects, measure the length of characters and we were able to concatenate two strings in one line in the example above. Result of the above code will look like this:
My First Name is: David
My Last Name is: MacCain
Length of first name: 5
My full name is: David MacCain
Let us do some String Comparison here. If we want to compare two strings, we will not be able to use relational operators like <, >, == etc. We can use method like compareTo(), equals() to compare two strings. Here is an instance of code to expose the string comparison.

public class MyString{
         Public static void main(String args[]){
         String n1="David"; 
         String n2= new String("David");
         if(n1==n2){
         System.out.println("Both are same");
         }
         else{
         System.out.println("Both are not same");
         }
     }
   }
When you run above code, can you guess what would be the output? Output will be: Both are not same. Because we can not use equal sign '==' to compare two strings. If we use a compare method equals() replacing '==' sign, it might solve our problem. Let us replace if(n1==n2) with the if(n1.equals(n2)) and run the code. Yes this time we get the output: Both are same.

StringBuffer and StringBuilder in Java

StringBuffer class is used to represent character that can be modified. It means StringBuffer class objects are mutable unlike Strings that we studied in previous chapter. Mostly StringBuffer is used for concatenation or manipulation of the strings. A StringBuffer implements the mutable sequence of the characters. We can create StringBuffer objects in two ways.
By using 'new' operator and passing the string to the object such as:

StirngBuffer strb = new StringBuffer("My Java");
and By allotting memory to the StringBuffer object using 'new' operator and later storing it into it such as:
StirngBuffer strb = new StringBuffer();
Here we are creating a StringBuffer empty object but not passing any string to it. StringBuffer will be created with 16 characters with default values.
StringBuffer strb = new StringBuffer(30);

What above code explains is that StringBuffer is created with 30 characters capacity. Now, is it possible to store more than 30 characters? Yes because StringBuffer has mutability feature, it can be modified. We can use append(), or insert() method to do it.

Let us have a code snippet to reflect preceding chapters.

import java.io.*;
public class MyStringBuffer{
    public static void main(String args[]) throws IOException
    {
       StringBuffer strb= new StringBuffer();//creates empty stringbuffer object
      BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); //input from keyboard

      System.out.print("What is you First Name: ");
      String fn = br.readLine();

      System.out.print("What is your middle name:");
      String mn = br.readLine();

      System.out.print("What is your last name:");
      String ln = br.readLine();
      //append first name and lastname
      strb.append(fn);
      strb.append(ln);
      //display only first name and last name upto this point
      //System.out.println("My name is: " + strb);

      //lets insert middle name
      int n = fn.length(); //n represent no. of characters
      strb.insert(n, mn);//insert middle name after n characters
      System.out.println("My full name is:"+ strb);//display full name now 
   }
} 

We have tried to append first name and last name and we were able to print out the results displaying first and last name in the monitor. Then, we realized that we'd missed the middle name. How do we append middle name, then? By using insert() method, we can append middle name as in above example code.

StringBuilder Class.
We have had StringBuilder Class only after JDK1.5 which contains same sort of features as StringBuffer Class does. StringBuilder Class is also mutable and modifiable as StringBuffer.

StringBuilder strb = new StringBuilder ("David");
StringBuilder strb = new StringBuilder ();
StringBuilder strb = new StringBuilder (30);

Only difference between these two classes are StringBuffer is synchronized by default while StringBuilder is not.

Learn Java

OOPs in Java

Programmers have firmly followed Procedural oriented approach for several decades and there is sudden shift in the software industry for new approach, called OOPs (Object Oriented Programming). Fortran, Pascal, C etc. languages were procedural because these language use procedural or functions to perform a task. Languages like C++, Java are called Object Oriented Programming.

In procedural method, programmers write set of functions to achieve one task, and whenever he wants to perform new task, then he would be writing a new set functions hence there will be no reusability. If programmers can write the new modules with the help existing old modules, that would be more easy and quick. Due to these reason, a new approach of object oriented programming emerged in the computer software market.

Features of Object Oriented Programming

Class & Object in Java
Infact, whole concept of OOPs is derived from the single notion called object. An object could be anything that exists in the world and can be distinguished from others such that a person, a ball, or a dog etc. All the existing objects have their properties and they can perform some actions such as walking, rolling, barking etc. Let us take an example as an object 'David' person. David is an object and David exists physically and he's got properties like name, sex, color and David can perform actions such as talking, eating etc. Let us put it in the code snippet

String name
Char sex;
int age;

So, above properties can be similar to other objects such as Mohan who have the same characters (properties) as David. Now what we can think of is they both fall into one class called 'Person' and share the same properties. Now we can say person do not exists but David and Mohan do exist. Another example can be an Animal class and a dog, a tiger, a lion all objects from class Animal. Let us draw a code snippet for creating a class called 'Animal'.

public class Animal
{
    //properties of an Animal class & variables
    String name;
    int size;
    //Action done by Animal class & method
    void eat()
    {  }
    void sleep()
    {  }
}

Now a class model has been built with two variables (name, size) and two methods eat(), sleep(). Let us create an object out of above class Animal.

 Animal Dave = new Animal();

Encapsulation in Java:
Encapsulation (Hiding Information) is one of the important features of OOPs concepts. Booch says: "Encapsulation is the process of hiding all of the details of an object that do not contribute to its essential characteristics". Data (variables), Code (methods) in the class are binded together. Variables and methods are called 'members' of the class. If variables are declared by using java keyword 'private', this indicates that variables are only accessible within a class not outside of the class. If a method for a class is declared by using java keyword 'public', it means it is accessible from inside and out of the class. To use those private variables, only way is to go through method and outsiders will not know what is declared in the variables. Outsiders can only use and get results. Hence Encapsulation is the protective mechanism for the members of a class that helps protect sensitive data and code of the software programs.

We will declare variables as 'private'. 'private' is called access specifier which makes the members of a class not to be accessible outside the Animal Class. To access these variables we use methods which generally declared as public. Let us have a code snippet which reflects encapsulation in java. Here we build a class 'Animal' and declare its variable as private.

public class Animal
  {
     //properties of an Animal class & variables
    private String name;
    private int size;
    //Action done by Animal class & method
    public void talk()
    {
     System.out.println("I am a:" + name);  
     System.out.println("My size is: "+ size);
    }
  }

Only talk() method can access to those private variables and by calling talk() method using Animal class object, we can make Animal talk for us.

Abstraction in Java
One of the most significant features of Java is 'Abstraction'. It is a technique of choosing common features of objects and methods. There might be too much data in the class and which a user do not require all of them. So using abstraction technique, we can hide unnecessary data and retrieve only the essentials data. Let us take an example of an accountant in a bank. An accountant can view/update its customer informations such as customer name, account number, balance etc. but he/she may not be able to view/update bank's annual profit, or loss amount which is only be available to bank's managers. So these unnecessary data for an accountant are abstracted from him.

public class Bank
    {
        //properties of a Bank class & variables
       private String name;
       private int acct;
       private double balance;
       private double profit;
       private double loss;

       public void viewAccountant()
       {
           System.out.println("Customer Name:" + name);  
          System.out.println("Customer Account Number: "+ acct);
          System.out.println("Customer Account Balance: "+ balance);

       }
    }

In the above code snippet we have been able to abstract unnecessary data and made it available only necessary data to an accountant. Obviously he can not access to bank's annual profit and loss data.

Inheritance in Java
We inherit some of the physical characteristics from our parent. Some thing like that in Java programming, new class can be created by inheriting from an existing class. Newly created class is called derived class or sub-class and original class is called base class or super class. Let us have a code snippet to understand Inheritance in more details.

 public class A
   {
       String name;
      int acct;
      public void method1()
      {  }
   }
 public class B extends A
         {
         double salary;
     }
      public void method2()
     {  }
    }

We can derive all the qualities of the members of class A to members of class B as well as we are able to define new variable for class B. Java keyword 'extends' is used to inherit Class A's characteristics to Class B. if we create an object from class B, it inherits all the members of Class A as well as of class B. Inheritance is a significant feature of java programming as it makes easy to manage code, conveniently we can create another class from existing class.

Polymorphism in Java
'Poly' meaning 'many' and 'Morphos' meaning 'forms', 'Many Forms', comes from Greek language which describes an ability to generate different many forms. Moreover, it is a technique to redefine methods for derived classes. Such as given a super class shape polymorphism allow redefining different area methods for any number of derived classes, such as circle, rectangle, and triangles. So programmer can use same method call to perform different operations.

public class AnimalTest
    {
        public static void main(String args[])
           {
               Animal animal = new Animal( "tiger");
              animal.talk( );
              Animal animal = new Animal( "Lion");
              animal.talk( );
              Animal animal = new Animal( "Elephant");
              animal.talk( );

          }
    }

In Polymorphism, a single variable can be used with different objects of related classes. We can use variable with dot (.) notation with the method() to invoke the method. Such as:

 variable.method()
mentioned in the above example.

Classes & Objects in Java

We discussed about classes and object little bit in previous chapter. Now we will discuss more about them. An object is the instance of the class as an object is created/instantiated from a class. That is why class is called a model for objects. All the variables and methods created in the class can be inherited to the instance of the class.

class Animal
{
   //instance variables
   String name;
   int size;
   //actions or methods
   void talk()
   {
       System.out.println("Animal has names");
      System.out.println("Animal has size");
   }
}

We observe above that java keyword 'class' is used to create a class following with the class name. We declare instance variable and methods for the class. Since the method has void java keyword, it means no result is returned and it does not take any data from us also. Now we will create an object out of the above class.

Animal animal1 = new Animal();

Animal is the class and animal1 is object name. so 'animal1' is reference of Animal object. 'new' operator is used to create object. When object is created, it is stored in 'Heap' memory. Once object is stored, JVM creates a unique reference number called
hash code number
for the object (animal1) below. Let us create a class 'Animal' and an object 'Lion' to an Animal class. and we will make it hash code display as well.

class Animal
{
   //instance variables
   String name;
   int size;
   //actions or methods
   void talk()
    {
       System.out.println("Animal has:" + name);
      System.out.println("Animal has:" + size");
    }
} 
class DemoClass
{
  public static void main(String args[])
    {
     Animal animal1 = new Animal();
     animal1.talk();
     //finding hash code of the object
     System.out.println("Hash Code is: " +animal1.hashCode());
    }
}

Output of the above code snippet would be as follows:

Animal has: null (we got null value because we did not initialize instance variables)
Animal has:0 (we got null value because we did not initialize instance variables )
Hash Code is: 25669322

Using reference variables, we can refer to the instance variables and methods such as:

 animal1.name;
animal1.talk(); 

How to Initialize Instance variables in Java

public class DemoInitialize
{
    public static void main(String args[])
    {
       Animal animal1 = new Animal(); //create Animal class object
      animal1.size = 200; //initialize variables using object reference (animal1)
      animal1.talk();
    }
}

Access Specifiers
Let us see how data can be overwritten if access Specifiers is not defined. We will have following code snippet:

class Animal
{
   String name = "Lion"; //instance variables
   int size = 150; //instance variables
   void makeNoise() {
      System.out.println("It is a :" + name);
      System.out.println("It weighs :" + size);
   }
} 
class DemoSpecifier
{
   public static void main(String args[])
   {
      Animal animal1 = new Animal();
     animal1.name = "Tiger";
     animal1.size = 200;
     animal1.makeNoise(); //calling animal makeNoise() method
   }
}

As we clearly see that we did not initialize Animal class with 'private keyword', as a result DemoSpecifier class can access these instance variables and overwrite the value. To protect from overwriting or accessing data from outsider, we use java keyword 'private'. Here is how we can declare instance variables by using 'private' key.

private String name = "Lion";
private in size = 150;

Access Specifier is the keyword that specifies how to access to the variables and methods of the class. There are four types of access specifiers in Java.
public: public access specifier cab be used from inside and outside of the class.
private: private access specifier is only accessible within same class by the methods but not accessible from outside the class from other programs.
protected: protected members of a class is accessible from inside and outside of the class but only within the same directory.
default: If no access specifier is defined, then Java will provide a default specifier which is accessible inside and outside of the class but within the same directory.

Constructor: Constructor is like method in java which is used to initialize instance variables. This is third possible ways of initializing instance variables. The only goal of constructor is to initialize instance variables.

Constructor's name should be similar to Class's name
Constructor's name should end with opening & closing braces
such as:
Animal( )
{   
}
Constructor may have variables in it which is called constructor's parameters. Constructor's parameters are used to receive data from outside into the constructor. Constructor does not return value and do not use 'void'. During the creation of object, if nothing is passed to the object, the default constructor is called executed. If some values are passed to the object, then parameterized constructor is called. A Constructor is called once per object. Such as if an object is created, and constructor is called. If we create second constructor, again constructor is called. Constructor is called concurrently when an object is created. Here is a simple code snippet for constructor.
Animal(String s, int k)
{
}
 
Animal tiger = new Animal();//default constructor is called
Animal tiger = new Animal("Tiger", 150);
//Parameterized constructor will receive "Tiger" and size =150

Let us have code snippet with constructor.

public class Animal {
    private String name;//instance variables
    private int size; //instance variables
    //default constructor
    Animal(){
    name = "Tiger";
      size = 150;
    }
    void makeNoise() //actions or methods
    {
       System.out.println("It is a :" + name);
      System.out.println("It weighs :" + size);
    }
}
public class DemoAnimal 
{
    public static void main(String args[])
    {
       Animal tiger = new Animal();//create a Animal object = tiger
      tiger.makeNoise();//calling makeNoise()method.
   
      Animal lion = new Animal();//creating another object = lion
      lion.makeNoise();//calling makeNoise() method.
    }
}

Output would be:
It is a :Tiger
It weighs :150
It is a :Tiger
It weighs :150
As we noticed above that both the objects tiger and lion have same output Tiger and 150 respectively. We will resolve this problem by using parameterized constructor which takes data from outside and initialize instance variables with that data.

public class Animal 
{
    private String name;//instance variables
    private int size; //instance variables
 
    Animal()//default constructor
    {
       name = "Tiger";
        size = 150;
    }

    Animal(String s, int k)//parameterize constructor
    {
       name = s;
        size = k;
    }
    void makeNoise() //actions or methods
    {
        System.out.println("It is a :" + name);
       System.out.println("It weighs :" + size);
    }
}
public class DemoAnimal 
{
   public static void main(String args[])
   {
        Animal tiger = new Animal();//default constructor is called.
       tiger.makeNoise();//calling makeNoise()method.
   
       Animal lion = new Animal("Lion", 180);//parameterized constructor is called
       lion.makeNoise();//calling makeNoise() method.
   }
}

Output would be:
It is a :Tiger
It weighs :150
It is a :Lion
It weighs :180

So, what we understand from above code that we have parameterized constructor String s; and int k; and these parameter receive data from outside as from DemoAnimal class such as:

Animal lion = new Animal("Lion", 180);
. Now 'Lion' is copied into parameter s, and 180 pound is copied to parameter k and from there, these values are copied to original instance variables: name, and size. If we do not pass any values while creating a new object, then default constructor is called which is:
Animal tiger = new Animal();

Methods in Java

Method performs an action in Java which is a set of statements. Action is i.e. calculation, processing data etc. Method name begins with lower case i.e. sqrt() method which calculates square root value. Method contains method name, parameters, method return data type, and method body. This should look as follows.

returndatatype methodName(parm1, parm2,…)
int sqrt(int num)
When Return data type is 'void', it does not return any value and do not accept data from outside and void method comes with the pair of empty braces '()'and method never returns more than one value such as:
return x, y; 
is invalid statement
void methodName()
Method body looks as follows:
{
Statements;
}
 
{
int i=a+b;
System.out.println("Total sum is:" +i);
}
If we want to return value then we will have statement look as follows:
{
int i = a+b;
return i;
}
Let us create a code snippet that explains methods in detail.

public class Calc1 
{
    private double num1, num2;//instance variables
    Calc1(double a, double b)//parameterized constructor
    {
        num1 = a;
         num2 = b;
    }
    double sum() //actions or methods
    {
        double tot = num1+num2;
       return tot;
    }
}
public class DemoCalc1 
{
    public static void main(String args[])
    {
        Calc1 c = new Calc1(12, 12.6);//new object is created and pass values to constructor
       double x = c.sum();//calling sum()method and storing total of num1+num2 into x  
    }
}

In the above example, sum() method returns the total sum and store the sum into x. and above method is called instance method as it is acting on the instance variables. Method that is not acting on the instance variables is called static method and can not access to instance variable but if variable is declared as 'static', then static method can access to static variables. Static variable is also called 'class variable' and static method is also called 'class method'.

Similarly, local variable or parameters declared inside the method can not be accessed outside the methods such as:

   //instance variable 
   private int x;
   void testMethod(int x):
   {
   x=x;
   }
In the above code, the local variable is x and only accessible within methods. Now notice that we can see above that the instance variable and local variable are conflicting as both of them are holding the same variable. How do we deal in this kind of situation? Java keyword
'this'
is used to handle this problem. 'this' keyword refers to the object of the classes where it has been used. Members of the class, instance variable, constructors, methods are referenced by 'this'.

public class Test
{
    private x;//instance variables
    Test()//default constructor
    {
       this(10) //calling present class's default para constructor and pass value 10
      this.sum(); //call present class's method
    }

    Test(int x)//parameterized constructor
    {
       this.x = x; //present class's instance variable
    }
    void sum() //actions or methods
    {
       System.out.println("Sum is: " +x);
     }
}
public class DemoThis 
{ 
    public static void main(String args[])
    {
       Test T = new Test();//new object is created and pass values to constructor 
    }
}

OUTPUT will be:
Sum is: 10
An object 'T' is created. Default constructor Test is executed passing value 10 to the instance variable x. Hence, present class's this.x=x; instance variable is initialized and executed giving the result = 10.

Setter & Getter Methods
Methods that work on the instance variables are called Instance Methods. Instance methods are called from the object using

objectName.methodName()
and they can access instance variable as well as static variables. There are two types of Instance methods:
a) Getter or Accessor Method
b) Setter or Mutator Method
Getter or Accessor Method can only access or read instance variable whereas Setter or Mutator method can access and modify instance variable.
Let us write a code snippet to reflect setter and getter methods

public class TestSetterGetter 
{
     private String name;//instance variables
    private char sex;

    void setName(String name)//Setter method to store data
    {
       this.name = name; 
    }
    void setSex(char sex)//Setter method
    {
       this.sex = sex; 
    }
    String getName() //Getter methods to access or read only
    {
       return name; 
    }
    char getSex() //Getter methods to access or read only
    {
       return sex; 
    }
 }
}
public class DemoThis
    {
     public static void main(String args[])
    {
         TestSetterGetter sg= new TestSetterGetter();//new object is created 
        sg.setName("David"); //store data
        sg.setSex('M'); //storing data

        System.out.println("Name:" +sg.getName()); //access data from object
        System.out.println("Gender:" +sg.getSex());
    }
}

OUTPUT will be:
Name: David
Gender: M

How to pass primitive data to Methods?
Primitive data types such as byte, int, short, long etc can store only single value, and they can be passed to methods by values. And only a copy of those data will be passed. Which means any changes taken place inside the method will not impact to the values outside the methods.

public class TestPassValue
{
    int x; //instance variables
    void sum(int x)
    {
       this.x=x+1;
    
}
public class DemoThis
{
    public static void main(String args[])
    {
       int x =12;//primitive data
      TestPassValue pv= new TestPassValue();//new object is created 
      pv.sum(x); //call sum method and pass primitive data
      System.out.println("Sum is:" + x); //display data
    }
}

OUTPUT will be:
Sum is: 12

How to pass objects to Methods?
The Class's object can also be passed to methods and return objects from the methods. Reference of the class is declared as parameter to pass object to method. As an example, let us say:

Person theMethod(Person obj1)
{
 statements;
 return obj1;
}
Here theMethod() takes Person class object and Person class is declared in parameter of the method and method returns obj1. Similarly we can pass an array to methods and return arrays from the methods. Let us see how it works:
String[] myMethod(String arr[ ])
In the above code snippet, single dimensional array of String type 'arr' is passed to method 'myMethod.

Inheritance in Java

What is Inheritance in Java? Inheritance simply means to inherit the characteristics from the original class. New classes/objects can be created by inheriting few or all the members of the original class allowing the newly created class to perform exactly what the base class can perform. So Inheritance relationship is considered as transitive. 'extends' java keyword or clause is used to inherit characteristics from base class or super class to subclass or derived class.

public class Animal 
{
    String name;//instance variables
    int size; //
 
    void setName(String name)//store data
    {
       this.name = name;
    
    void setSize(int size) //actions or methods
    {
      this.size = size;
    }
    String getName(){
       return name;
    }
    int getSize(){
       return size;
    }
}
public class Tiger extends Animal 
{
  int weight;//variable for only Tiger class
  void setWeight(int weight){
     this.weight = weight;
  }
  int getWeight(){
    return weight; 
  }
}

public class TestAnimal{
   public static void main(String args[]){
       Tiger t = new Tiger();
       t.setName("Tiger");
       t.setSize(20);
       t.setWeight(200);
       System.out.println("Name:" + t.getName());
       System.out.println("Size:" + t.getSize());
       System.out.println("Weight:" + t.getWeight());
    } 
}

Super class members are always available for subclass because subclass contains a copy of super class. So the advantage of Inheritance is saving lot of space and easy to develop hence allowing to grow the productivity and efficiency. Programmer can reuse the super class's characteristics without rewriting the whole code. Java keyword 'super' is used to access to super class. If we create an object to super class, we will only be able to access super class members but not be able to access subclass object. In contrary, if an object is created to subclass, both super class members and subclass members can access to it. Super can be used to refer to super class variables as

super.variable
, super class method as
super.method()
, and super class constructor as
super(values)

public class SuperClassOne 
{
    int j = 10; //super class variables
    void display()//super class method
    {
       System.out.println("Sum is:" + j);
    }
}
public class SuperClassTwo extends SuperClassOne{
    int j = 15; 
    void display() 
    {
       System.out.println("Sum is:" +j);
      super.display();//using super to call super method
      System.out.println("Sum is:" + super.j); //to call super variable
    }
}
public class TestSuperClass {
    public static void main(String args[]){
       //creating subclass object
      SuperClassTwo sct = new SuperClassTwo();
      sct.display();
    }
}

what is 'Protected Specifier'?

When private members of the super class are restricted to sub classes. When we want to access private super class member from subclass, we can use java keyword

'protected'
(specifier). So protected is used in the super class to make members available directly to its sub classes.
public class Shape 
{
    protected double x;//protected specifier variable
    Shape(double x) //parameterized constructor
    {
       this.x=x;
    }
}
public class Square extends Shape{
    Square(double x)//calling super class Shape and send i value
    {
        super(x);
    }
    void area()
    {
        System.out.println("Square Area:" +(x*x));
    }
}
public class ShapeDemo 
{
    public static void main(String args[])
    {
    Square sq = new Square(3.5);//displaying square area
    sq.area();
    }
}

There are two types of Inheritance: 
Single and Multiple Inheritance. Simply put, one super class and many sub classes is single Inheritance where as multiple super classes and one or more sub classes is Multiple Inheritance. The concept of Multiple Inheritance is true with C++ but in Java, no more Multiple Inheritance is accepted or allowed. Multiple Inheritance creates confusions amongst programmers. To accommodate Multiple Inheritance, programmers prefer using Interface such as:
Class TestClass implements interfaceOne, interfaceTwo,…
Now, TestClass can have all the members of interfaceOne, and interfaceTwo inherited to it.

OTN Discussion Forums: Message List - Database - General

Ask Tom HOT ARTICLES

 
© Copyright 2008 - 2011. All rights reserved to dba-sansar.blogspot.com.
All other blogs, posts and entries are the property of their respective authors.
Please email us for your comments and suggessions Click Here