Object in Java

 

Object in Java


1. What is OOPS?

Object-Oriented Programming System is the programming technique to write programs based on the real world objects. The states and behaviors of an object are represented as the member variables and methods. In OOPS programming programs are organized around objects and data rather than actions and logic.

2. Difference between Procedural programming and OOPS

  • A procedural language is based on functions object-oriented language is based on real-world objects.
  • Procedural language gives importance to the sequence of function execution but object-oriented language gives importance on states and behaviors of the objects.
  • Procedural language exposes the data to the entire program but object-oriented language encapsulates the data.
  • Procedural language follows a top-down programming paradigm but object-oriented language follows a bottom-up programming paradigm.
  • A procedural language is complex in nature so it is difficult to modify, extend and maintain but an object-oriented language is less complex in nature so it is easier to modify, extend and maintain.
  • Procedural language provides less scope of code reuse but object-oriented language provides more scope of code reuse.

3. What is an Object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword in Java Programming language.
A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Various Object Definitions:
1. An object is a real-world entity.
2. An object is a runtime entity.
3. The object is an entity which has state and behavior.
4. The object is an instance of a class.

Real-world examples

  • Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Chair, Bike, Marker, Pen, Table, Car, Book, Apple, Bag etc. It can be physical or logical (tangible and intangible).

4. What are the advantages of using Software Objects

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.


How to Declare, Create and Initialize an Object in Java
A class is a blueprint for Object, you can create an object from a class. Let's take Student class and try to create Java object for it.

Let's create a simple Student class which has name and college fields. Let's write a program to create declare, create and initialize a Student object in Java.
public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public static void main(String[] args) {

        Student student = new Student("Ramesh", "BVB");
        Student student2 = new Student("Prakash", "GEC");
        Student student3 = new Student("Pramod", "IIT");
    }
}
The Student objects are:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
Each of these statements has three parts (discussed in detail below):
Declaration: The code Student student; declarations that associate a variable name with an object type. 
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

5. Declaring a Variable to Refer to an Object

General syntax:
type name;
This notifies the compiler that you will use a name to refer to data whose type is a type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.
From the above program, we can declare variables to refer to an object as:
Student student;
Student student2;
Student student3;

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
For example:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
Note that we have used a new keyword to create Student objects.

Initializing an Object

The new keyword is followed by a call to a constructor, which initializes the new object. For example:
Student student = new Student("Ramesh", "BVB");
Student student2 = new Student("Prakash", "GEC");
Student student3 = new Student("Pramod", "IIT");
From above code will call below constructor in Student class.
public class Student {
    private String name;
    private String college;

    public Student(String name, String college) {
         super();
         this.name = name;
         this.college = college;
    }
}

Array Basics in Java

     Array Basics in Java


    1. Array Overview

    Array in java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. 

    • An array is a container object that holds a fixed number of values of a single type.
    • The length of an array is established when the array is created. After creation, its length is fixed.
    • As we know Array is a data structure where we store similar elements and Array a starts from index 0.
    • Each item in an array is called an element, and each element is accessed by its numerical index.
    • Since arrays are objects in Java, we can find their length using member length.
    • A Java array variable can also be declared like other variables with [] after the data type.
    • The variables in the array are ordered and each has an index beginning from 0.
    • Java array can be also be used as a static field, a local variable or a method parameter.
    • The size of an array must be specified by an int value and not long or short

    2. Declaring a Variable to Refer to an Array

    // declares an array of integers
    int[] anArray;
    Ex:
    byte[] anArrayOfBytes;
    short[] anArrayOfShorts;
    long[] anArrayOfLongs;
    float[] anArrayOfFloats;
    double[] anArrayOfDoubles;
    boolean[] anArrayOfBooleans;
    char[] anArrayOfChars;
    String[] anArrayOfStrings;
    Employee[] anArrayOfEmployees;
    Student[] anArrayOfStudent;
    Object[] anArrayOfObjects;
    Can also place the brackets after the array's name:
    // this form is discouraged
    float anArrayOfFloats[];
    An array declaration has two components: the array's type and the array's name.
    1. An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).
    2. A variable like from above program anArray is variable, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

    3. Creating an Array

    One way to create an array is with the new operator.
    // create an array of integers
    int[] anArray = new int[10];
    Examples to create an Array:
    String[] anArrayOfStrings = new String[10];
    Object[] anArrayOfObjects = new Object[10];

    4. Initializing Array with Elements

        4.1 Initialize Integer Array Example
        Let's create and initialize integer Array with few integer elements
    // initialize primitive one dimensional array
    int[] anArray = new int[5];
    
    anArray[0] = 10; // initialize first element
    anArray[1] = 20; // initialize second element
    anArray[2] = 30; // and so forth
    anArray[3] = 40;
    anArray[4] = 50;
        4.2 Initialize String Array Example
        Let's create and initialize String Array with few String elements.
    // initialize Object one dimensional array
    String[] anArrayOfStrings = new String[5];
    anArrayOfStrings[0] = "abc"; // initialize first element
    anArrayOfStrings[1] = "xyz"; // initialize second element
    anArrayOfStrings[2] = "name"; // and so forth
    anArrayOfStrings[3] = "address";
    anArrayOfStrings[4] = "id";

    5. Accessing an Array

        5.1 Accessing Integer Array Example
    // initialize primitive one dimensional array
    int[] anArray = new int[5];
    
    anArray[0] = 10; // initialize first element
    anArray[1] = 20; // initialize second element
    anArray[2] = 30; // and so forth
    anArray[3] = 40;
    anArray[4] = 50;
    
    // Each array element is accessed by its numerical index:
    System.out.println("Element 1 at index 0: " + anArray[0]);
    System.out.println("Element 2 at index 1: " + anArray[1]);
    System.out.println("Element 3 at index 2: " + anArray[2]);
    System.out.println("Element 4 at index 3: " + anArray[3]);
    System.out.println("Element 5 at index 4: " + anArray[4]);
    Output:
    Element 1 at index 0: 10
    Element 2 at index 1: 20
    Element 3 at index 2: 30
    Element 4 at index 3: 40
    Element 5 at index 4: 50
    
        5.2 Accessing String Array Example
        Let's create String Array, initialize with few elements and access String Array with indexing.
    // initialize Object one dimensional array
    String[] anArrayOfStrings = new String[5];
    anArrayOfStrings[0] = "abc"; // initialize first element
    anArrayOfStrings[1] = "xyz"; // initialize second element
    anArrayOfStrings[2] = "name"; // and so forth
    anArrayOfStrings[3] = "address";
    anArrayOfStrings[4] = "id";
    
    // Each array element is accessed by its numerical index:
    System.out.println("Element 1 at index 0: " + anArrayOfStrings[0]);
    System.out.println("Element 2 at index 1: " + anArrayOfStrings[1]);
    System.out.println("Element 3 at index 2: " + anArrayOfStrings[2]);
    System.out.println("Element 4 at index 3: " + anArrayOfStrings[3]);
    System.out.println("Element 5 at index 4: " + anArrayOfStrings[4]);
    Output:
    Element 1 at index 0: abc
    Element 2 at index 1: xyz
    Element 3 at index 2: name
    Element 4 at index 3: address
    Element 5 at index 4: id

    Do while loop in Java

       Do while loop in Java

      1. Syntax and flow of the while loop

      do {
      // body of a loop
      } while (condition);
      Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, a condition must be a Boolean expression.

      do-while loop example

      public class DoWhileLoopExample {
          public static void main(String args[]) {
              int n = 10;
              do {
                  System.out.println("tick " + n);
                  n--;
              } while (n > 0);
          }
      }
      Output:
      tick 10
      tick 9
      tick 8
      tick 7
      tick 6
      tick 5
      tick 4
      tick 3
      tick 2
      tick 1

      do-while loop with Menu Selection example

      The do-while loop is especially useful when you process a menu selection because you will usually want the body of a menu loop to execute at least once.
      Consider the following program, which implements a very simple help system for Java’s selection and iteration statements:
      public class DoWhileMenuExample {
          public static void main(String args[]) throws java.io.IOException {
              char choice;
              do {
                  System.out.println("Help on: ");
                  System.out.println(" 1. if");
                  System.out.println(" 2. switch");
                  System.out.println(" 3. while");
                  System.out.println(" 4. do-while");
                  System.out.println(" 5. for\n");
                  System.out.println("Choose one:");
                  choice = (char) System.in.read();
              } while (choice < '1' || choice > '5');
              System.out.println("\n");
              switch (choice) {
                  case '1':
                      System.out.println("The if:\n");
                      System.out.println("if(condition) statement;");
                      System.out.println("else statement;");
                      break;
                  case '2':
                      System.out.println("The switch:\n");
                      System.out.println("switch(expression) {");
                      System.out.println(" case constant:");
                      System.out.println(" statement sequence");
                      System.out.println(" break;");
                      System.out.println(" //...");
                      System.out.println("}");
                      break;
                  case '3':
                      System.out.println("The while:\n");
                      System.out.println("while(condition) statement;");
                      break;
                  case '4':
                      System.out.println("The do-while:\n");
                      System.out.println("do {");
                      System.out.println(" statement;");
                      System.out.println("} while (condition);");
                      break;
                  case '5':
                      System.out.println("The for:\n");
                      System.out.print("for(init; condition; iteration)");
                      System.out.println(" statement;");
                      break;
              }
          }
      }
      Result:
      Help on:
      1. if
      2. switch
      3. while
      4. do-while
      5. for
      Choose one:
      4
      The do-while:
      do {
      statement;
      } while (condition);


      While loop in Java

         While loop in Java

        1. Syntax and flow of the while loop

        while(condition) {
        // body of a loop
        }

        The condition can be any boolean expression. The body of the loop will be executed as long as the conditional expression is true. When the condition becomes false, control passes to the next line of code immediately following the loop. 


        In a while loop, a condition is evaluated first, and if it returns true then the statements inside while loop execute. When the condition returns false, the control comes out of a loop and jumps to the next statement after a while loop.


        Example while loop

        Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
        public class WhileLoopExample {
            public static void main(String args[]) {
                int n = 10;
                while (n > 0) {
                    System.out.println("tick " + n);
                    n--;
                }
            }
        }
        Output:
        tick 10
        tick 9
        tick 8
        tick 7
        tick 6
        tick 5
        tick 4
        tick 3
        tick 2
        tick 1

        2. The while Loop with No Body

        The body of the while (or any other of Java’s loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java. For example, consider the following program:
        public class WhileLoopNoBody {
            public static void main(String args[]) {
                int i, j;
                i = 100;
                j = 200;
                // find midpoint between i and j
                while (++i < --j)
                ; // no body in this loop
                System.out.println("Midpoint is " + i);
            }
        }
        Output:
        Midpoint is 150

        3. Infinite while Loop

        If you pass true in the while loop, it will be an infinite while loop.
        Syntax:
        while(true){  
        //code to be executed  
        } 
        Example:
        public class WhileExample {
            public static void main(String[] args) {
                while (true) {
                    System.out.println("infinitive while loop");
                }
            }
        }
        Output:
        infinitive while loop
        infinitive while loop
        infinitive while loop
        infinitive while loop
        infinitive while loop