CLASSES, OBJECTS, METHODS,
CONSTRUCTORS, ARRAY, STRING & VECTOR
Presented By: SHIVAM
Reg Id:11701112
MCA 2nd
Semester
Department of Computer Science and Applications
D.A.V. University , Jalandhar
1
CONTENTS
1. Introduction to objects
2. Introduction to classes
2.1 Instance of a class
1. Creating objects
3.1 Dot operator
1. Methods
4.1 Method overloading
1. Constructors
5.1 Constructor overloading
1. Array
6.1 Declaration, Initialization &allocation of array
6.2 Two dimentional array
1. Strings
7.1 operations of strings
7.2 String buffer classes
1. vectors
2
3
Introduction
Java is a true OO language and therefore the
underlying structure of all Java programs is classes.
Anything we wish to represent in Java must be
encapsulated in a class that defines the “state” and
“behaviour” of the basic program components known as
objects.
Classes create objects and objects use methods to
communicate between them. They provide a
convenient method for packaging a group of logically
related data items and functions that work on them.
A class essentially serves as a template for an object
and behaves like a basic data type “int”. It is therefore
important to understand how the fields and methods are
defined in a class and how they are used to build a
Java program that incorporates the basic OO concepts
such as encapsulation, inheritance, and polymorphism.
Classes
Defines a new DATA TYPE.
This new type can be used to create
objects of that type.
So a class is a template for an object and
an object is an instance of a class
5
6
Instance of Classes
A class provide a blueprint from which individual
objects are created.
Each object has some components which categorizes it
into a class.
Example:-
class smartphone
{
String manufacturer;
String model;
Double storage;
Double screensize;
}
Feilds
}
Only template is created. Now we can have different types of smartphones
Creating an object
smartphone samsung=new smartphone();
Each object has its own set of instance variable
7
samsung
Refrence
variable
ManufracturerManufracturer
ModelModel
StorageStorage
Screeen sizeScreeen size
ManufracturerManufracturer
ModelModel
StorageStorage
Screeen sizeScreeen size
feilds
OBJECT REFFERING TO
Dot operator .
Object variables & methods can be
accessed using the dot operator
Example :-
smartphone samsung = new smartphone();
samsung.model = galaxyprime;
8
Methods
Classes need to contain data and behaviour.
Methods represent the behaviour of a class.
Example :-
class smartphone
{
double storage; // Feild
Void clickpicture() // Adding method to class smartphone
{
storage = storage-2; // behaviour or interaction
}
}
9
Method Overloading
Methods of same name but different signatures
Example
class smartphone{
int Storage=1000;
int astorage(int ram) // Method 1
{
int WithRAM=storage+ram;
return withRAM ;
}
int astorage(int ram, int sd) // Method 2
{
int withSD=storage+ram+sd
return withSD;
}
}
10
Example cntd.
Class methodoverloading
{
public static void main(string args[])
{
Overloading total=new overloading();
int withRam=total.astorage(512); // invokes method 1
int withSD=total.astorage(512,1024); // invokes method 2
System.out.println(“Storage With RAM ”+withRAM);
System.out.println(“Storage with SD ”+withSD);
}
}
Output
Storage with RAM 1512
Storage with SD 2536
11
Constructor in Java
Constructor is a special method which will be
called automatically when we create an object
of any class.
The main purpose of using constructor is to
initialize an object.
Properties of constructor:-
Constructor name must be same as class name
Constructor will be called automatically
Constructor can’t return any value even void.
12
Constructor eliminate default values
Class A
{
int a;
float b;
char ch;
string str;
boolean bl;
a()
{
a=10;
b=20.0;
ch=’m’;
str=“java”;
bl=true;
}
}
13
Default values
0
0.0
null
null
false
integer
float
character
string
boolean
0 10
0.0 20.0
m
Null java
False true
CONSTRUCTOR OVERLOADING
Constructor overloading in java allow us to have more
than one constructor in one class
Similar to Method overloading, in constructor
overloading we have multiple constructor with different
signature the only difference is constructor doesn’t have
a return type
14
Example
class volume
{
double pi=3.14;
volume(double radius) // Constructor 1
{
double sphere=4.0/3*pi*radius*radius*radius;
System.out.println(“volume of sphere”=+sphere);
}
volume(double radius,double height) // Constructor 2
{
double cylinder=pi*radius*radius*height;
System.out.println(“volume of cylinder”=+cylinder);
}
}
Class multipleconstructor // Main classs
{
public static void main(String args[])
{
volume sphere=new volume(2.0); // Invokes constructor 1
volume cylinder=new volume(3.5,7.0); // Invokes constructor 2
}
}
15
OUTPUT
volume of sphere 33.49
volume of cylinder 269.255
Array
An array is a container object .That holds a fixed number of values
of a single type.
Each item in an array is called an element
Element can be accessed through index number
16
Array Declaration,Allocation & Initialization
Array Declaration
Datatype arrayname[];
int[] arr; //int is a data type of array “arr” is the name of Array “[]” is for index.
Array Allocation means size of array
Array can be allocated as:
int arr[]=new int[10];
New allocate memory for Array
Array Initialization
• Array can be initialized by individual index
•arr[0]=1;
•arr[1]=2;
• Array can be declare , allocate and initialize in single statement as
•Int arr[ ]={1,2,3,4,5,6,7,9,10};
17
Two Dimensional Array in java
Declaration of Two dimentional Array
int[][] arr=new int[3][3]; //3 row and 3 column
Example
class Testarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing array
for(int i=0;i<3;i++) //printing array
{
for(int j=0;j<3;j++)
{
System.out.print(“”+arr[i][j]);
}
System.out.println(); // After displaying one row move cursor to next line
}
}
}
18
Strings
A sequence of characters
Java platform provides the String class to create
and manipulate strings.
How to create String object?
There are two ways to create String object:
By string literal
For Example:
String s="welcome";
By new keyword
For Example:
String s=new String("Welcome");
20
Some important operations of strings
String Concatenation
String Comparison
Substring
Length of String etc.
22
Concatenating String()
Concatenate two or more string.
string str = “mca";
string str1 = “class";
string str2 = str + str1;
string st = “mca"+“class";
String Comparison()
It compares the content of the strings. It will return true if string
matches, else returns false.
String s1 = "Java";
String s2 = "Java";
String s3 = new string (“ABC");
test(s1 == s2) //true
test(s1 == s3) //false
23
substring()
substring() method returns a part of the string.
String str = "0123456789";
System.out.println(str.substring(4));
Output:
456789
System.out.println(str.substring(4,7));
Output:
456
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output:
8
24
Some more string class methods
The java.lang.String class provides a lot of methods to work on string. By the help
of these methods, we can perform operations on strings.
Here are some other methods :
1. charAt() :-returns a char value at the given index number. The index number
starts from 0.
2. contains():- . It returns true if sequence of char values are found in this string
otherwise returns false.
3. getChars() :-copies the content of this string into specified char array
4. indexOf() :-returns index of given character value or substring.
5. replace() :-returns a string replacing all the old char or CharSequence to new char
25
StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string.
Important Constructors of StringBuffer class:
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
26
Important methods of StringBuffer class
append(String s): is used to append the specified string with this string.
insert(int offset, String s): is used to insert the specified string with this
string at the specified position.
replace(int startIndex, int endIndex, String str): is used to replace the
string from specified startIndex and endIndex.
delete(int startIndex, int endIndex): is used to delete the string from
specified startIndex and endIndex.
reverse(): is used to reverse the string.
capacity(): is used to return the current capacity.
27
Example of using StringBuffer & StringBuilder class
28
Append()
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
insert()
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);
replace()
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
capacity()
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
30
Vector
The Vector class implements a growable array of
objects.
Like an array, accessed using an integer index.
Vector can grow or shrink as needed to accommodate
adding and removing items.
In Java this is supported by Vector class contained in
java.util package. Can hold objects of any type or any
number. The objects do not have to be homogeneous.
Like arrays, Vectors are created as follows:
Vector list = new Vector(); // declaring without size
Vector list = new Vector(3); // declaring with size
31
Vector properties
Vectors posses a number of advantages over
arrays:
It is convenient to use vectors to store objects.
A vector can be used to store list of objects that may
vary in size.
We can add and delete objects from the list as an
when required.
But vectors cannot be used to store basic data
types (int, float, etc.); we can only store objects.
To store basic data type items, we need
convert them to objects using “wrapper classes”
32
Important Methods in Vector class
addElement(Object item)
insertElementAt(Object item, int index)
elementAt(int index) – get element at index
removeElementAt(int index)
size()
clone() - Returns a clone of this vector.
clear() - Removes all of the elements from this Vector.
get(int index) - Returns the element at the specified
position in this Vector.
copyInto(array) – copy all items from vector to array.
33
Vector – Example
import java.util.*;
public class VectorOne{
public static void main(String[] args) {
Vector circleVector = new Vector();
System.out.println("Vector Length = “ +circleVector.size()); // 0
for ( int i=0; i < 5; i++) {
circleVector.addElement( new Circle(i) );
// radius of the Circles 0,1,2,3,4
}
System.out.println("Vector Length = " + circleVector.size());// 5
}
}
34
Summary
Classes, objects, and methods are the basic
components used in Java programming.
We have discussed:
How to define a class
How to create objects
How to add methods to classes
How to add constructor
Array , string, and vector
REFERENCES
RAJAN MANRO & SUNITA M. 2014
JAVA & WEB DESIGNING KALYANI PUBLISHERS
ABHIJEET SINGH. 2016 CONCEPT OF STRING AND SRING BUFFER
www.studytonight.com
Sonoo Jaiswal 2015 Array and vector
www.javatpoint.com
35