Professional Documents
Culture Documents
CONSTRUCTOR
Definition:A constructor is a special member method called by JVM implicitly (automatically) for
initializing member variables of class with user/programmer defined values or default values.
Rules/Properties/Characteristics:
It is time consuming to initialize all of the variables in a class each time an instance is created.
Java allows objects to initialize themselves when they are created.
This automatic initialization is performed through the use of a constructor.
A constructor initializes an object as soon as it is created.
It has the same name as the name of the class in which it resides.
Constructors do not have a return type, not even void
Implicit return type of constructor is the class type itself.
Types of Constructor
There are two types of constructors
1) Default Constructor.
a. Zero argument constructor.
2) User defined Constructor
a. zero argument constructor
b. parameterized constructor
Default Constructor:
In the java programming if we are not providing any constructor in the class then compiler provides
default constructor.
Provided by the compiler at the time of compilation.
It is always zero argument constructors with empty implementation.
Default constructor is executed by the JVM at the time of execution.
Ex:- Before compilation
class Test
{
void good()
{
System.out.println(“Hello");
}
public static void main(String[] args)
{
After compilation
class Test
{
Test()
{
default constructor provided by compiler
}
void good()
{
System.out.println(“Hello");
}
public static void main(String[] args)
{
Test t=new Test();
t.good();
}
}
Constructor Overloading: More than one constructor in a class is called as Constructor Overloading.
Constructor name is similar but its signature isdifferent. Signature represents number of parameters, type
of parameters and order ofparameters. Here, at least one thing must be differentiated.
Example:
class Const_Overloading
{
Const_Overloading()
{
System.out.println("this is zero argument constructor");
}
Const_Overloading(int i)
{
System.out.println(i);
}
Const_Overloading(int i,Stringstr)
{
System.out.println(i);
System.out.println(str);
}
void Const_Overloading()
{
System.out.println("hello");
}
public static void main(String[] args)
{
Const_Overloading c1=new Const_Overloading();
Const_Overloading c2=new Const_Overloading(10);
Const_Overloading c3=new Const_Overloading(100,"Kashif");
Instance method: It requires an object of its class to be created before it can be called. For the instance
method, memory is allocated during object creation hence instance methods are accessed by using object-
name (reference-variable). These methods are stored in heap memory but the parameter(arguments
passed to them) and their local variables and the value to be returned are stored in stack.
Example:
void m1() //instance method
{
//body
}
Syntax for accessing Instance method:
Static method:It can be called without creating an object of its class. They are referenced by the class
name itself or reference to the object of that class.For the static member, memory is allocated
during .class file loading hence they are accessed by using class-name.
Example:
static void m2() //static method
{ //body //static area
}
Syntax for accessing Static method:
Classname.staticmethod( ); // call static method by using class name
Example:
Test.m2( );
NESTING OF METHODS
When a method in java calls another method by using only its name in the same class, it is called Nesting
of methods.
Example:
class NestedMethod{
public void m1()
{
m2();
}
public void m2()
{
System.out.println("sample test for Nested Method");
}
public static void main(String[] args)
{
NestedMethod t = new NestedMethod();
t.m1();
}
}
THIS KEYWORD
This is a keyword that can be used inside any method to refer to the current object
This is always a reference to the object on which the method wasinvoked.
This is useful when a method needs to refer to the object that invokedit
If instance & local variables are having same name, then to represent instance variables use this
keyword.
Example:
class Student
{
int rollno;
int marks;
Note:If the call contains both var-arg method & normal argument method then it prints normal argument
value.
Program:
class Test
{
void m1(int... a)
{
System.out.println("variable argument="+a);
}
void m1(int a)
{
System.out.println("normal argument="+a);
}
public static void main(String[] args)
{
Test t=new Test();
GARBAGE COLLECTION
Java handles memory deallocation of an object automatically. The technique which accomplishes this
task is calledgarbage collection.
A program called as garbage collector is always used tocollect unreferenced (unused) memory location.It
runs in the background at periodic interval of times along with regular JAVA program to collect
unreferenced memory locations.
gc()
Internally the garbage collector is running to destroy the useless objects.
By using gc() method we are able to call Garbage Collector explicitly by the developer.
gc() present in System class and it is a static method.
Syntax:System.gc();
Whenever garbage collector is destroying useless objects just before destroying the objects the garbage
collector is calling finalize() method on that object to perform final operation of particular object.
FINALIZE() METHOD
Finalize() method is used to specify those actions that mustbe performed before an object is destroyed.
The Java runtime mechanism callsthis method whenever it is about to reclaim the space for that object.
finalize() method is called prior to garbage collection.
finalize() method is a protected and non-static method of java.lang.Object class.
This method will be available in all objects created in java.
We can override the finalize() method to keep those operations you want to perform before an object is
destroyed.
Syntax:
protected void finalize()
{
finalization code
}
Example:
class FinalizeMethod
{
public void finalize()
{
System.out.println("all work done");
}
public static void main(String[] args)
{
FinalizeMethod t1=new FinalizeMethod();
FinalizeMethod t2=new FinalizeMethod();
System.out.println("good");
System.out.println("morning");
t1=null;
VISIBILITY CONTROL
There are four access modifiers keywords in Java and they are:
public— public member is accessible everywhere.
protected— protected member can be accessed only by classes in the same package and classes derived
from the current class—no matter which package they are in.
private— A private member can be accessed only from within the class.
Default(Package)— If none of the other access modifier keywords appear, the default applies (access
only by classes in the same package).
Easy to learn Tips:
Private:same class only
Public:everywhere
Protected:same class, same package, any subclass
(default) :same class, same package
String literal:
String literal is created by double quote.
Example:
String s="Hello";
Each time you create a string literal, the JVMchecks the string constant pool first. If the stringalready
exists in the pool, a reference to thepooled instance returns. If the string does notexist in the pool, a new
String object instantiates,
then is placed in the pool.
Example:
String s1="Welcome";
String s2="Welcome";//no new object will be created
String ()
It constructs a new String object which is initialized to an empty string (" "). For example:
String s = new String();
will create a string reference variable s that will reference an empty string.
String (charArray)
To create a string initialized by an array of characters
char[] charArray ={'H','i',' ','K','A','S','H','I','F'};
String strl = new String(chrArr);
Will create a String object strl initialized to value contained in the character array chrArr
Example:
public class StringClassConstructors
{
public static void main(String[] args)
{
char[] charArray ={'H','i',' ','K','A','S','H','I','F'};
byte[] ascii ={65,66,67,68,70,71,73};
String str = "Welcome";
String strl =new String("to College");
String str2 =new String(charArray);
String str3 =new String(charArray,3,3);
String str4 =new String(ascii);
String str5 =new String(ascii,2,3);
String str6 =new String();
String str7 =new String(str);
System.out.println("str : "+ str);
System.out.println("strl : "+ strl);
System.out.println("str2 : "+ str2);
System.out.println("str3 : "+ str3);
System.out.println("str4 : "+ str4);
System.out.println("str5 : "+ str5);
System.out.println("str6 : "+ str6);
System.out.println("str7 : "+ str7);
str += " Ahmed";
String substring (int i): Return the substring from the ith index character to end.
String s1=new String("mumbai");
System.out.println("Mumbai".substring(3)); // returns “bai ”
System.out.println(s1.substring(3));// returns "bai"
String substring (int i, int j): Returns the substring from i to j-1 index.
String s1=new String("mumbai");
System.out.println(s1.substring(2, 5)); // returns “mba”
String concat( String str): Concatenates specified string to the end of this string.
String s1=new String("mumbai");
String s2 = new String(" Maharastra");
System.out.println(s1.concat(s2)); // returns “mumbaiMaharastra”
int indexOf (String s): Returns the index within the string of the first occurrence of the specified string.
String s1=new String("mumbai");
System.out.println(s1.indexOf("ba")); // returns 3
System.out.println(s1); //mumbai
int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified
string, starting at the specified index.
String s1=new String("mumbai");
System.out.println(s1.indexOf('m',1));// returns 2
boolean equals( Object otherObj): Compares this string to the specified object.
Boolean b = "Thakur".equals("Thakur"); // returns true
System.out.println(b);
Boolean b1 = "Thakur".equals("thakur"); // returns false
System.out.println(b1);
String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = "Thakur";
System.out.println(word1.toLowerCase()); // thakur
String toUpperCase(): Converts all the characters in the String to upper case.
String word2 = "Thakur";
String word3 =word1.toUpperCase();
System.out.println(word3); // THAKUR
String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect
whitespaces in the middle.
String word4 = " Thakur Polytechnic ";
String word5 = word4.trim(); //
System.out.println(word5); //Thakur Polytechnic
String replace (char oldChar, char newChar): Returns new string by replacing all occurrences of
oldChar with newChar.
String s6 = "Thakur Polytechnic";
String s7 = "Thakur Polytechnic".replace('h' ,'H'); // THakurPolytecHnic
System.out.println(s7);
Example:
class StringClassMethods1
{
public static void main(String args[])
{
String s1=new String("mumbai");
//int length(): Returns the number of characters in the String.
System.out.println(s1.length()); // returns 6
//Char charAt(int i): Returns the character at ith index.
System.out.println(s1.charAt(3)); // returns ‘b’
//String substring (int i): Return the substring from the ith index character to end.
System.out.println("Mumbai".substring(3)); // returns “bai ”
System.out.println(s1.substring(3));// returns "bai"
StringBuffer Methods:
length(): Returns the StringBuffer object’s length.
capacity(): Returns the capacity of the StringBuffer object.
append(): appends the specified argument string representation at the end of the existing StringBuffer.
insert(index,value): the index integer value to insert a value and the value to be inserted in StringBuffer.
reverse(): Reverses the existing String or character sequence content in the buffer and returns it.
delete(int startIndex, int endIndex): The former serves as the starting delete index and latter as the
ending delete index. The character sequence between startIndex and endIndex–1 are deleted. The
remaining String content in the buffer is returned.
deleteCharAt(int index): deletes single character within the String inside the buffer. The location of the
deleted character is determined by the passed integer index
ARRAYS IN JAVA
Java array is an object which contains elements of a similar data type.
Arrays are object of a class and direct superclass of arrays is class Object
We can store only a fixed set of elements in a Java array.
In Java all arrays are dynamically allocated.
Array in java is index-based, the first element of the array is stored at the 0 index.
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.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Array can contains primitives data types as well as objects of a class depending on the definition of array.
Each item in an array is called an element, and each element is accessed by its numerical index.
Note :
The elements in the array allocated by new will automatically be initialized to zero (for numeric types),
false (for boolean), or null (for reference types).
Array Methods
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary
search algorithm.
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered
equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the
two arrays are equal.
public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints.
public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
//program to display array element, sum of array element and largest number in array
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i <myList.length; i++)
{ System.out.println(myList[i] + " ");
}
// Summing all elements double total = 0;
for (int i = 0; i <myList.length; i++)
{ total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element double max = myList[0];
for (int i = 1; i <myList.length; i++)
{ if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Program:
class Exp13XIII3
{
public static void main(String[] args)
{
String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};
//The conventional approach of using the for loop
System.out.println("Using conventional For Loop:");
for(int i=0; i<arrData.length; i++)
{
System.out.println(arrData[i]);
}
System.out.println("\nUsingForeach loop:");
//The optimized method of using the for loop - also called the foreach loop
for (String strTemp : arrData)
{
System.out.println(strTemp);
}
}
}
ARRAYS OF OBJECTS
An array of objects is created just like an array of primitive type data items in the following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of student class in which the address of
seven Student objects can be stored.The Student objects have to be instantiated using the constructor of
the Student class and their references should be assigned to the array elements in the following way.
class Student
{
public int roll_no;
public String name;
Student(int r, String n)
{
MULTIDIMENSIONAL ARRAYS
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
array. These are also known as Jagged Arrays.
A multidimensional array is created by appending one set of square brackets ([]) per dimension.
Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
int aiMdArray[][]=new int [2][];
The above statement creates an array where it has two elements pointing to null.
aiMdArray[0]=new int [2];
The above statement initializes the first element to a new array of 2 elements.
aiMdArray[0][0]=10;
The above statement initializes the first element of the first array to 10.
System.out.println();
}
}
}
Output:
279
361
742
VECTOR CLASS
Vector can hold objects of any type and any number.
Useful when size of an array is not known in advance or
we need to change the size over the lifetime of a program.
Java Vector class comes under the java.util package.
Creating a Vector is nothing but creating an object of java.util.Vector class.
Vector can only store objects.
Simple datatype can’t be directly stored in a vector and they need to be converted into objects by
using wrapper class.
It is easy to add and delete objects from vector as and when required.
Java provides number of methods to manipulate vectors.
Syntax:
Vector vectorname=new Vector();
Example:
Vector v1=new Vector();
VECTOR METHOD
void setSize(int newSize)
Sets the size of this vector.
int size()
Returns the number of components in this vector.
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
boolean add(Object o)
Appends the specified element to the end of this Vector.
booleanaddAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are
returned by the specified Collection's Iterator
booleanaddAll(int index, Collection c)
Inserts all of the elements in the specified Collection into this Vector at the specified position.
int capacity()
WRAPPER CLASS
Wrapper class wraps (encloses) around a data type and gives it an object appearance.
Wrapper classes include methods to unwrap the object and give back the data type.
Each of Java's eight primitive data types has a class dedicated to it which is called as wrapper classes
The wrapper classes are part of the java.lang package, which is imported by default into all Java
programs.
Primitive Wrapper
data type Class
boolean Boolean
byte Byte
char Character
int Integer
float Float
double Double
long Long
short Short
Wrapper Class Constructor
Constructor converts primitive datatype to its corresponding object.
Example:
Integer i= new Integer(x);
Float f=new Float(y);
ENUMERATED TYPES
Enumeration is used to declare group of named constants.
J2SE 1.5 allows us to use enumerated type in Java using enum keyword.
Compiler will generate .class file for enum.
The enum constants are by default public static final.
The main purpose of the enum is to declare the own data types.
Every enum constant contains index value & it starts from 0.
Every enum is final by default hence other classes are unable to extends.
Values() method used to retrieve all the constants at a time.
Ordinal() method is used to print the index numbers of constants & index starts from 0.
Every enum constant represents object of type enum.
Example:
public enum Directions
{
NORTH, SOUTH, EAST,WEST;
}
Internal implementation of above example:
public class Directions
{
public static final Directions NORTH = new Directions();