Java - Classes & Objects & Methods

DEFINE : CLASS
- a class is a user defined data type from which the objects can be created.
- the data or variable defined within a class are called as instance variables.
- each object of the class contains it's own seperate copy of variables.
- a class is declared by the keyword "class".

SYNTAX : CLASS

class classname
{
    datatype instancevariable_1;
    datatype instancevariable_2;
    datatype instancevariable_N;
    datatype methodname_1(parameters)
    {
        // body of the methodname_1.
    }
    datatype methodname_2(parameters)
    {
        // body of the methodname_2.
    }
    datatype methodname_N(parameters)
    {
        // body of the methodname_N.
    }
}

DEFINE : OBJECT

- an object is also defined as the instance of the class.
- the state or the behavior of an object can be defined by it's class.
- objects are created using the "new" operator. This "new" operator creates an object of the specified class and also returns the reference of that object.

EXAMPLE : OBJECT

- Country india; // Declaration of the object "india"
- india = new Country(); // Instantiation of the object "india"

PROGRAM : CLASSES & OBJECT

import java.lang.*;
class Money
{
    int collegefees = 100;
    int tuitionfees = 100;
}
class Kaju extends Money
{
    public static void main(String args[])
    {
        Kaju k = new Kaju();
        System.out.println("College Fees Of Kaju : " + k.collegefees);
        System.out.println("Tuition Fees Of Kaju : " + k.tuitionfees);
    }
}

Ouput:
College Fees Of Kaju : 100
Tuition Fees Of Kaju : 100

DEFINE : ARRAY OF OBJECTS / ARRAY

- an array in java is a group of variables with the same data type that are referred to a common name.
- it is the collection of objects of the same data type.
- thus, al the elements in the array have the same data type.
- in java, arrays can also be known as objects.
- syntax: (below)

SYNTAX : ARRAY OF OBJECTS

- Classname variablename[] = new Classname[size];
- Kaju k[] = new Kaju[3];

PROGRAM : DEFINE A CLASS EMPLOYEE WITH DATA MEMBERS AND ACCEPT 5 EMPLOYEES

import java.lang.*;
import java.util.scanner;
class Employee
{
    int empid;
    float salary;
    string name;
    void input()
    {
        Scanner S = new Scanner(System.S)
        System.out.println("Enter ID : ");
        empid = S.nextInt();
        System.out.println("Enter Salary : ");
        empid = S.nextFloat();
        System.out.println("Enter Name: ");
        empid = S.nextString();
    }
    void show()
    {
        System.out.println("ID : " + empid);
        System.out.println("Salary : " + salary);
        System.out.println("Name : " + name);
    }
    Class demo()
    {
        public static void main (String args[])
        {
            int i;
            Employee e[] = new Employee[5];
            for(i=0;i<=5;i++)
            {
                e[i] = new Employee();
                e[i].input();
                e[i].show();
            }
        }
    }
}

EXPLAIN : CONSTRUCTOR

- java allows the objects to initialize themselves when they are created.
- this automatic initialization can be performed by using "constructor" feature.
- constructors has the same name as the class name.
- a constructor does not have a return type
- constructors can be / may be private, public or protected.
- multiple constructors can exist, but they should have different signatures.

PROGRAM : CONSTRUCTOR

class Bike
{
    Bike()
    {
        System.out.println("This Is A Bike");
    }
    public static void main (String args[])
    {
        Bike b = new Bike();
    }
}

Output:
This is A Bike

EXPLAIN : PARAMTERIZED CONSTRUCTOR

- The constructor that has parameters / arguments is known as the parameterized constructor.
- Parameterized constructors provide different values to the objects.
- It is possible to create object with different data sets of values at the time of their creation.

PROGRAM : PARAMTERIZED CONSTRUCTOR

class Student
{
    int id;
    String name;
    Student(int i, String n)
    {
        id = i;
        name = n;
    }
    void display()
    {
        System.out.println(id + "  " + name);
    }
    public static void main (String args[])
    {
        Studentname s1 = new Studentname(21, "Saurabh");
        Studentname s2 = new Studentname(23, "Ashiish");
        s1.display();
        s2.display();
    }
}

EXPLAIN : CONSTRUCTOR OVERLOADING

- Constructor overloading in java is perfomed when there are more than one constructors having different parameters / parameter list.
- They are arranged in a way that each constructor performs a different task.

PROGRAM : CONSTRUCTOR OVERLOADING

class Student
{
    int id;
    String name;
    int age;
    Student(int i, String n)
    {
        id = i;
        name = n;
    }
    Student(int i, String n, int a)
    {
        id = i;
        name = n;
        age = a;
    }
    void display()
    {
        System.out.println(id + " " + name + " " + age);
    }
    public static void main (String args[])
    {
        Student s1 = new Student(21, Saurabh);
        Student s2 = new Student(234, Ashiish);
        s1.display();
        s2.display();
    }
}

EXPLAIN : THIS KEYWORD

- In java, The THIS keyword is used as the reference variable that refers to the current object.
- THIS can be used to refer the current class instance variable.
- THIS can be used to invoke the current class method.
- THIS can be passed as an argument in the method & constructor call.
- THIS can be used to return the current class instance from the method.

PROGRAM : THIS KEYWORD

class Box
{
    int height;
    int depth;
    int length;
    Box(int height, int depth, int length)
    {
        this.height = height;
        this.depth = depth;
        this.length = length;
    }
    class Demo
    {
        public static void main (String args[])
        {
            Box b = new Box(10, 20, 30)
        }
    }
}

EXPLAIN : METHOD OVERLOADING

- The process of defining multiple methods within the same class having different number & types of arguments is known as method overloading.
- When a overloaded method is called, It simply executes the version of method whose parameters match with the arguments.
- overloaded methods can have different return types.

PROGRAM : METHOD OVERLOADING

class Math
{
    int cal;
    int val;
    int add(int x, int y)
    {
        cal = x + y;
        return(cal);
    }
    int add(int z)
    {
        cal = z + 10;
        return(cal)
    }
    float add(float x, float y)
    {
        val = x + y;
        return(val);
    }
}
class Overloading
{
    public static void main (String args[])
    {
        Maths m = new Maths();
        System.out.println("10 + 10 : " + m.add(10, 10));
        System.out.println("20 + 20 : " + m.add(20. 20));
        System.out.println("30 + 30 : " + m.add(30, 30));
    }
}

EXPLAIN : METHOD OVERRIDING

- In a class hierarchy, When a method has in the subclass has the same name, Same arguments and the same return type as of the mtod in the super class, Then the method in the subclass is known to be overridden.
- When an overridden method is called, It will always refer to the version of that method defined in the subclass.

PROGRAM : METHOD OVERRIDING

class Maths
{
    int var1, var2, var3;
    Maths(int x, int y)
    {
        var1 = x;
        var2 = y;
    }
    void calculate()
    {
        var3 = var1 + var2;
        System.out.println("Addition : " + var3);
    }
    class Overriding
    {
        public static void main (String args[])
        {
            Arithmetic a = new Arithmetic(30,15)
            a.calculate()
        }
    }
    class Arithmetic extends Maths
    {
        Arithmetic(int x, int y)
        {
            super(x, y);
        }
        void calculate()
        {
            var3 = var1 - var2
        }
        System.out.println("Subtraction ; " + var3);
    }
}

COMPARE : METHOD OVERLOADING & METHOD OVERRIDING

- Overloading happens at compile time. / Overriding happens at the run time.
- Method overloading is perfomed within the class. / method overriding is perfomed within classes that have inheritance.
- Parameters must be different. / Parameters must be the same.
- Static method can be overloaded. / Static method cannot be overriden.
- Overloading gives better performance. / Performance is poor compared to Overloading.
- Argument list should be different while calling. / Argument list can be same while calling.

EXPLAIN : GARBAGE COLLECTOR IN JAVA

- In java, The garbage is reffered to the un-referenced objects.
- Garbage collection is a process of reclaiming the runtime unused memory automatically.
- It is simply a way to destroy the un-used obejcts.
- free() function or the delete() function is used in C++ for garbaje colection. But in Java, This operation is performed automatically.
- It makes the java memory efficient because the garbage collector removes the un-used obejcts from the memory.

EXPLAIN : FINALIZE() METHOD

- This method is called / invoked by the garbage collector when it determines that there are no more references to that object or no more un-referenced objects.
- Declaration : void finalize()
- This method does not have parameters or return value.

SYNTAX : FINALIZE METHOD

protected void finalize() throws Throwable
{
    // Keep some resource closing operations here
}

EXPLAIN : STRING CLASS

- In Java, The string is basically an object that represents sequence of character values. An array of characters works the same as the Java String.
- Java String is immutable & final.
- Java provides 2 utility classes (StringBuffer) & (StringBuilder)

CHARACTER EXTRACTION:-


EXPLAIN & SYNTAX : charAt()

- It returns the character at the specified index.
- Syntax: public char charAt(int index)

EXPLAIN & SYNTAX : toCharArray()

- It returns an array of characters after converting a string into sequence of characters.
- Syntax: public char tocharArray()

EXPLAIN & SYNTAX : GETCHARS()

- It copies the characters from the string to the destination character array.
- Syntax: public void getChars()

EXPLAIN & SYNTAX : GETBYTES()

- This method converts a given string into a sequence of bytes.
- Syntax: public byte[] getBytes(String charsetName)

STRING COMPARISON:-


EXPLAIN & SYNTAX : EQUALS()

- It compares the string to the specified object, The result is TRUE if the string object represents the same sequence of characters as the invoking object, Here it is case sensitive.
- Syntax: boolean equals(Object str)

EXPLAIN & SYNTAX : EQUALSIGNORECASE()

- It compares the string to the specified obejct, The result is TRUE if the string object represents the same sequence of characters with the same case as the invoking object, Thus, it is not case sensitive.
- Syntax: boolean equals(Object str)


EXPLAIN & SYNTAX : COMPARETO()

- It is used to compare two strings, Each character of both the strings is converted into unicode value for comparison of the characters. If it is true, It returns 0 or else 1.
- Syntax: int compareTo(String str)

EXPLAIN & SYNTAX : STRING SEARCH (INDEXOF() & LASTINDEXOF())

- This method returns index position of the given character value. If it is not found, The index counter starts from zero.
- Syntax: int indexOf()

- This method returns the last index position of the given character value. If it is not found, The index counter counter starts from zero.
- Syntax: int lastIndexOf()

EXPLAIN & SYNTAX : MODIFYING SEARCH (SUBSTRING)

- This method returns a part of string. It starts returning the character from the specified start of index to the end of the index.
- Syntax: Public string subString(int startIndex, int endIndex)

EXPLAIN & SYNTAX : CONCAT()

- This method is used to concatinate / combine the specified string at the end of the string. It simply appends the other string to the end.
- Syntax: public String concat(String stringname)

EXPLAIN & SYNTAX : REPLACE()

- This method returns a string replacing all the old characters to the new specified characters.
- Syntax: public String replace(char oldCharacters, char newCharacters)

EXPLAIN & SYNTAX : TRIM()

- This method trims a part of string. It trims the characters from the specified index. And, Then it returns the omitted string.
- Syntax: public String trim()

EXPLAIN & SYNTAX : TOUPPERCASE()

- This method converts the given string into upper case characters, It returns the characters in upper case.
- Syntax: public string toUpperCase()

EXPLAIN & SYNTAX : TOLOWERCASE()

- This method converts the given string into lower case characterd, It returns the characters in lower case.
- Syntax: public string toLowerCase()

EXPLAIN & SYNTAX : STARTSWITH()

- This method checks if the string starts with the given index. It returns TRUE if this string starts with the given index, Else it returns FALSE.
- Syntax: public boolean startsWith(String index)

EXPLAIN & SYNTAX : ENDSWITH()

- This method checks if the string ends with the given index. It returns TRUE if this string ends with the given index, Else it returns FALSE.
- Syntax: oublic boolean endsWith(String index)

COMPARE : STRING V/S STRINGBUFFER W/ PARAMETERS

- Basic: Length of the string is fixed. / Length of the string buffer can be changed.
- Modification: String object is immutable. / StringBuffer object is mutable.
- Performance: It is slower during concatenation. / It is faster during concatenation.
- Memory: Consumes more memory. / Consumes less memory.
- Storage: String constant pool. / Heap memory.

EXPLAIN : THE VECTOR CLASS

- This class implements the dynamic array which can hold array of any type, Which can grow automatically according to the user needs.
- It does not require any fixed size for implementing an array.
- Vector is an sequence of object.

ENLIST & DEFINE & SYNTAX : CONSTRUCTORS OF VECTOR CLASS

- Vector(): It creates a default vector which has an initial size of 10 / Vector v = new Vector();
- Vector(int size): It creates a vector whose initial capacity is defined by the specified size / Vector v = new Vector(5);
- Vector(int size, int incr): It creates a vector which has initial capacity is specified by size, And whose increment is specified by "incr" / Vector = new Vector(5, 5)

ENLIST & DEFINE & SYNTAX : METHODS OF VECTOR CLASS

- elementAt(int index) : It returns the element at the location specified by the "index"
- addElement(object element) : The object specified by the element is added to the vector.
- removeElement(object element) : The object specified by the element is deleted from the vector.
- insertElementAt(object element, int index) : It adds the "element" to the vector at the specified position.

PROGRAM : VECTOR

import java.lang.*;
import java.util.*;
class VectorDemo
{
    public static void main (String args[])
    {
        Vector v = new Vector(5, 5);
        System.out.println("Initial Size : " + v.size());
        System.out.println("Initial Capacity : " + v.capacity());
        v.addElement("Ashish");
        v.addElement("APR");
        v.addElement("Ramtekkar");
        System.out.println("Current Data : ");
        v.removeElement("APR");
        System.out.println("After Removing : ");
    }
}

EXPLAIN : WRAPPER CLASS

- A wrapper class is a class whose object wraps / contains a primitive data types.
- They can convert data types into objects and vice versa.
- These classes can wrap the primitive data types within the class, All the wrapper classes are defined in package.java.lang.*;

LIST : CLASSES OF WRAPPER CLASS

Data type : Wrapper class
boolean : Boolean
char : Character
double : Double
float : Float
int : Integer
long : Long
short : Short
byte : Byte

APPLCATIONS : WRAPPER CLASS

- To convert simple data types into objects.
- To convert string into data types.

EXPLAIN : INTEGER WRAPPER CLASS
EXPLAIN : CONVERT PRIMITIVE NUMBER TO OBJECT
EXPLAIN : OBJECT NUMBER TO PRIMITIVE NUMBER
EXPLAIN : CONVERT PRIMITIVE NUMBER TO STRING
EXPLAIN : CONVERT STRING OBJECT TO NUMERIC OBJECT
EXPLAIN : CONVERT STRING TO PRIMITIVE NUMBERS

EXPLAIN : VARIABLE & SCOPE OF VARIABLE

- A java variable is a piece of memory that can contain data value.
- The scope of variable specifies the region of the source program where that variable is known, Accesible & Can be used.
- The declared variable has a definite scope.

ENLIST : TYPES OF VARIABLES

- Local variables.
- Final variables.
- Class / Static variables.

EXPLAIN : LOCAL VARIABLE

- The local variables are declared in methods, constructors or in the blocks.
- They are created when the method, constructor or the block is entered and the variable will be destroyed once it exits the method, constructors or blocks.
- Access modifiers cannot be used in local variables.

EXPLAIN : INSTANCE VARIABLE

- The instance variables are declared in the class, But outside the method, constructor or the block.
- When a space is allocated for an object in the heap memory, A slot for each instance variable is created.
- They are created by using the NEW operator and destroyed with the DELETE operator.

EXPLAIN : CLASS / STATIC VARIABLES

- Class variables are also known as the static variables, They are created with the static keyword in a class but outside the method, constructor or the block.
- There can be any one copy of each class variable per class.
- Static variables are rarely used other than being declared as constants, Thus their values are constant.
- These variables are stored in the static memory.

Popular posts from this blog

Software Engineering & Project Mangement

Software Engineering - Software Quality Assurance & Security

Data Structures & Algorithms