You are on page 1of 28

UNIT II

DERIVED SYNTACTICAL CONSTRUCTS IN JAVA

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)
{

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 1


Test t=new Test();
t.good();
}
}

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();
}
}

User defined constructors:


When user defines constructor in a class, it is called as user defined constructor.
Zero argument constructor: user defined constructor which doesn’t accept any parameter.
Syntax:
class <clsname>
{
clsname () //default constructor
{
Block of statements;
………………………………;
………………………………;
}
………………………;
………………………;
};
Example:
class Test public static void main(String[] args)
{ {
Test() Test t=new Test();
{ }
System.out.println("0-arg cons by user "); }
}

Parameterized constructor: user defined constructorwhich takes some parameters.


Syntax:

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 2


class <clsname>
{
…………………………;
…………………………;
<clsname> (list of parameters) //parameterized constructor
{
Block of statements (s);
}
…………………………;
…………………………;
}
Example:
class Score System.out.println("Excellent");
{ }
Score(int i) public static void main(String[] args)
{ {
System.out.println(i); Score t=new Score(10);
} t.Remark();
void Remark() }
{ }.

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");

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 3


c1.Const_Overloading();
}
}
}

JAVA METHODS (BEHAVIORS)


Methods are used to write the business logics of the project.
Coding convention: method name starts with lower case letter and every inner word starts with
uppercase letter(mixed case).
Example: post() , charAt() , toUpperCase() , compareToIgnoreCase()……etc
Every method contains three parts.
1. Method declaration
2. Method implementation (logic)
3. Method calling
Example:
void m1() ------> method declaration
{
Body (Business logic); -----> method implementation
}
Test t = new Test();
t.m1(); ------> method calling
Method Syntax:-
[modifiers-list] return-Type Method-name (parameters list) throws Exception
Modifiers-list ------ represent access permissions. ---- [optional]
Return-type ------ functionality return value ---- [mandatory]
Method name ------ functionality name ----- [mandatory]
Parameter-list ------ input to functionality ---- [optional]
Throws Exception ------ representing exception handling --- [optional]
Example:
public void m1()
{
logics…
}

Types of methods in java


1. Instance method
2. Static method

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:

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 4


Objectname.instancemethod( ); //calling instance method
Example:
Test t = new Test();
t.m1( );

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;

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 5


void setdata(int rollno,int marks)
{
this.rollno=rollno;
this.marks=marks;
}
void display()
{
System.out.println("rollno:"+rollno);
System.out.println("marks:"+marks);
}
}
class ThisKeyword
{
public static void main(String args[])
{
Student s1=new Student();
s1.setdata(1,65);
s1.display();
}
}

COMMAND LINE ARGUMENTS


The arguments which are passed from command prompt to application at runtime are called command
line arguments.
The command line argument separator is space.
In single command line argument it is possible to provide space by declaring that command line
argument in double quotes.
Example:
public class CommandLineArg
{
public static void main(String[] args)
{
int sum = 0;
for (int i = 0; i <args.length; i++)
{
sum = sum + Integer.parseInt(args[i]);
}
System.out.println("The sum of the arguments passed is " + sum);
}
}

VARARGS:VARIABLE LENGTH ARGUMENTS


It allows the methods to take any number of parameters to particular method.
Syntax:
Returntypemethodname( datatype…variablename)
Example:
Void m1(int… a)// (only 3 dots)
{------

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 6


}
The above m1() method will allow any number of parameters.(0 or 1 or 2 or 3………..n)
Inside the method it is possible to declare only one variable-argument and that must be last argument
otherwise the compiler will generate compilation error.
void m1
void m2(int... a,charch) --->invalid
void m3(int... a,boolean... b) --->invalid
void m4(double d,int... a) --->valid
void m5(char ch ,double d,int... a) --->valid
void m6(char ch ,int... a,boolean... b) --->invalid
Example:- normal-arguments vs variable-argument
Program:
class VarLenArg
{
void m1(char ch, int... a)
{
System.out.println(ch);
for (int a1:a)
{
System.out.print(a1+"\t");
}
}
public static void main(String[] args)
{
VarLenArg t=new VarLenArg();
t.m1('a');
t.m1('b',10);
t.m1('c',10,20);
t.m1('d',10,20,30,40);
}
}

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();

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 7


t.m1(10);
}
}
>java Test
normal argument=10

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;

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 8


t2=null;
System.gc();
}
}

THE OBJECT CLASS


Object class is a special class in Java. All the other classes are subclassesof Object.This means that a
reference variable of type Object can refer to an object of any other class.
The Object class defines the following methods :
Method Purpose
Object clone() Creates a new object that isthe same as the object beingcloned
boolean Equals(Object object) Determines whether oneobject is equal to another
void finalize() called before an unusualobject is recycled
Class getClass() Obtains the class of an objectat run time
int hashCode() Returns the hash code associated with the invokingobject
void notify() Resumes execution of athread waiting on the invokingobject
void noifyAll() Resumes execution of allthreads waiting on theinvoking object
String toString() Returns a string thatdescribes the object
void wait() Waits on another thread ofexecution

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

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 9


STRING CLASS
String is a sequence of charactersbut it’s not a primitive type.
When we create a string in java, it actually creates an object of type String.
String is an immutable class and once instantiated its value never changes.

Ways to create String object:


1. By string literal
2. By new keyword

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

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 10


By new keyword:
String s=new String("Welcome”);
JVM will create a new String objectin normal (nonpool) Heap memory and the literal"Welcome" will be
placed in the string constantpool. The variable s will refer to the object inHeap(nonpool).

Constructor of String class

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 (String strObj)


It constructs a String object which is initialized to same character sequence as that of the string
referenced by strObj.
String s2 = new String(s);

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

String (char [] chArr, int startlndex, int count)


It constructs a new String object whose contents are the same as the character array, chArr, starting from
index startlndexupto a maximum of count characters.
char[] str = {'W','e','l','c','o','m','e'};
String s3 = new String(str,5,2};
On execution, the string reference variable s3 will refer to a string object containing a character sequence
me in it.

String (byte [] bytes)

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 11


It constructs a new String object by converting the bytes array into characters using the default charset.
byte[] ascii ={65,66,67,68,70,71,73};
String s4 = new string (ascii};
On execution, the string reference variable s4 will refer to a String object containing the character
equivalent to the one in the bytes array.

String (byte [] bytes, int startlndex, int count)


It constructs a new String object by converting the bytes array starting from index startlndexupto a
maximum of count bytes into characters using the default charSet. For example: On executing the
statement,
String s5 = new String(ascii,2,3};
The string reference variable s5, will refer to a String object containing character sequence
CDE.

String (byte [] bytes, String charsetName)


It constructs a new String object by converting bytes array into characters using the specified charset.

String(byte[] bytes, int startlndex, int count, String charsetName)


It constructs a new String object by converting the bytes array starting from index startlndexupto a
maximum of count bytes into characters using the specified charset.

String (StringBuffer buffer)


It constructs anew String object from a StringBuffer object.

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";

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 12


System.out.println("str : "+ str);
}
}

String Class Method:

int length(): Returns the number of characters in the String.


String s1=new String("mumbai");
System.out.println(s1.length()); // returns 6

Char charAt(int i): Returns the character at ith index.


String s1=new String("mumbai");
System.out.println(s1.charAt(3)); // returns ‘b’

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);

booleanequalsIgnoreCase (String anotherString): Compares string to another string, ignoring case


considerations.
Boolean b3= "Thakur".equalsIgnoreCase("Thakur"); // returns true
System.out.println(b3);

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 13


Boolean b4 = "Thakur".equalsIgnoreCase("thakur"); // returns true
System.out.println(b4);

int compareTo( String anotherString): Compares two string lexicographically.


String s4="HellooOO";
String s5="Helloo";
System.out.println(s4.compareTo(s5)); // 2 This returns difference s1-s2.

int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring


case considerations.This returns difference s1-s2.
String s4="HellooOO";
String s5="Helloo";
System.out.println(s4.compareToIgnoreCase(s5)); //2

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"

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 14


//String substring (int i, int j): Returns the substring from i to j-1 index.
System.out.println(s1.substring(2, 5)); // returns “mba”
//String concat( String str): Concatenates specified string to the end of this string.
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.
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.
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);
//booleanequalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.
Boolean b3= "Thakur".equalsIgnoreCase("Thakur"); // returns true
System.out.println(b3);
Boolean b4 = "Thakur".equalsIgnoreCase("thakur"); // returns true
System.out.println(b4);
// int compareTo( String anotherString): Compares two string lexicographically.
String s4="HellooOO";
String s5="Helloo";
System.out.println(s4.compareTo(s5)); // 2 This returns difference s1-s2.
//int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case
considerations.This returns difference s1-s2.
System.out.println(s4.compareToIgnoreCase(s5)); //2
//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);
}
}

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 15


STRINGBUFFER CLASS
The StringBuffer class is used to created mutable(modifiable) string.
The StringBuffer class issame as String except it is mutable i.e. it can bechanged.
Note: StringBuffer class is thread-safe i.e.multiple threads cannot access itsimultaneously
Syntax:
StringBuffervariablename = new StringBuffer(“String”);
Example:
StringBuffersb = new StringBuffer(“ThakurPolytechnic”);
StringBuffer object can be created using new operator only.

Constructors of StringBuffer class:


StringBuffer()
creates an empty StringBuffer with the initial capacity of 16 reserved characters by default.
StringBuffersb = new StringBuffer();
StringBuffer(String str)
creates a StringBuffer with the passed String as the initial content of the buffer.
StringBuffersb = new StringBuffer("Hello World!");
StringBuffer(int capacity)
creates an empty StringBuffer with the specified capacity as length.
StringBuffersb = new StringBuffer(20);

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

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 16


replace(int startIndex, int endIndex, String str): first two are starting and ending index of the existing
String Buffer. The character sequence between startIndex and endIndex–1 are removed. Then the String
passed as third argument is inserted at startIndex
Program:
public class StringBufferExample
{
public static void main(String[] args)
{
StringBuffersb = new StringBuffer("ThakurPolytechnic");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is " + sbLength);
System.out.println("Capacity of " + sb + " is " + sbCapacity);
sb.append(",Mumbai,");
sb.append(101);
System.out.println(sb);
sb.insert(6, " ");
sb.insert(sb.length(), " Maharastra");
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(sb.reverse());
System.out.println(sb.delete(11,17));
System.out.println(sb.deleteCharAt(11));
System.out.println(sb.replace(0,11," TP"));
}
}

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.

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 17


Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array

Syntax to Declare Single Dimensional Array in Java


An array declaration has two components: the type and the name. type declares the element type of the
array. Like array of int type, we can also create an array of other primitive data types like char, float,
double etc or user defined data type(objects of a class).Thus, the element type for the array determines
what type of data the array will hold.
Syntax:
dataType[] varname; (or)
dataType []varname; (or)
dataTypevarname[];
Example:
int intArray[];
byte byteArray[];
MyClassmyClassArray[];
// an array of references to objects ofthe class MyClass (a class created byuser)

Instantiation of an Array in Java


When an array is declared, only a reference of array is created. To actually create or give memory to
array, new keyword is used.
Syntax:
var-name = new datatype [size];
datatype specifies the type of data being allocated, size specifies the number of elements in the array, and
var-name is the name of array variable that is linked to the array.
Example:
intArray = new int[20]; // allocating memory to array

Declaration and Instantiation in single statement


int[] arr = new int[20];

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).

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 18


Array Literal
In a situation, where the size of the array and variables of array are already known, array literals can be
used.
int[] arr = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

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

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 19


//Display array element using for each loop
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 (double element: myList)
{
System.out.println(element);
}
}
}

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)
{

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 20


roll_no = r;
name = n;
}
}
// Elements of array are objects of a class Student.
public class Array1d
{
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
arr[0] = new Student(1,"hi");
arr[1] = new Student(2,"hello");
arr[2] = new Student(3,"bye");
arr[3] = new Student(4,"tc");
arr[4] = new Student(5,"sd");
//accessing the elements of the specified array
for (int i = 0; i <arr.length; i++)
System.out.println("Element at " + i + " : " + arr[i].roll_no +" "+ arr[i].name);
}
}

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.

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 21


class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}
Output:
279
361
742

////////Displaying 2d array element using length method


class Exp13X
{
public static void main(String[] args)
{
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
for (int i = 0; i <a.length; i++)
{

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 22


for(int j = 0; j < a[i].length; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}

Passing Arrays to Methods


Like variables, we can also pass arrays to methods.For example, below program pass array to method
sum for calculating sum of array’s values.
// Java program to demonstrate passing of array to method
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method sum
sum(arr);
}
public static void sum(int[] arr)
{
// getting sum of array values
int sum = 0;
for (int i = 0; i <arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}
Output :
sum of array values : 15

Returning Arrays from Methods


As usual, a method can also return an array. For example, below program returns an array from method
m1.
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i <arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 23


// returning array
return new int[]{1,2,3};
}
}
Output:
123

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 CLASS CONSTRUCTOR


Vector( )
Creates default vector, with initial size of 10.
Vector(int size)
Accepts size as an argument , creates vector whose initial capacity is specified by size.
Vector(int size, int incr)
creates a vector whose initial capacity is specified by size and whose increment is specified by incr.
Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

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()

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 24


Returns the current capacity of this vector.
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size by one.
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified index.
void clear()
Removes all of the elements from this vector.
Object clone()
Returns a clone of this vector.
boolean contains(Object elem)
Tests if the specified object is a component in this vector.
Object elementAt(int index)
Returns the component at the specified index.

////program to demonstrate vector methods


import java.util.*;
class VectorExample3
{
public static void main(String[] arg)
{
// create default vector
Vector v = new Vector();
v.add(2);
v.add(3);
v.add(0, 1);
v.add(3, 4);
v.add("thakur");
v.add("poly");
v.add(3);
System.out.println("Vector is " + v);
if (v.contains("poly"))
System.out.println("poly");
// get the element at index 2
System.out.println("element at indexx 2 is: " + v.get(2));
// get the index of specified element
System.out.println("index of thakur is: " + v.indexOf("thakur"));
// check whether vector is empty or not
if (v.isEmpty())
System.out.println("Vector is clear");
// first element of vector
System.out.println("first element of vector is: " + v.firstElement());
// checking initial capacity
System.out.println("Initial capacity: " + v.capacity());
v.clear();
// checking vector
System.out.println("after clearing: " + v);
// check whether vector is empty or not
if (v.isEmpty())

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 25


System.out.println("Vector is clear");
}
}

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);

Wrapper Class Method


typevalue()
This method converts object to its corresponding primitive type
Example:
int x=i.intValue();
toString()
This method converts primitive datatype to String
Example:
Str=Integer.toString(x);
Valueof()
This method converts string to objects
Example:
Integer I = Integer.valueOf("10");
System.out.println(I);
Double D = Double.valueOf("10.0");
System.out.println(D);
Parsetype()
This method converts String to primitive datatype
Example:
Iint i=Integer.parseInt(str);

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 26


/////////////Program to demonstrate Wrapper Class Method
class WrapperClass
{
public static void main(String args[])
{
int b = 10;
//wrapping around Integer object
Integer intobj = new Integer(b);
System.out.println("Integer object intobj: " + intobj);
// objects to data types (retrieving data types from objects)
int iv = intobj.intValue();
System.out.println("int value, iv: " + iv);
//wrapping primitive datatype into String
int z=80;
String str=new String();
str= Integer.toString(z);
System.out.println("String value is:"+str);
System.out.println("String length is:"+str.length());
//wrapping String to object
Integer intobj1=Integer.valueOf("100");
System.out.println("String value is:"+intobj1);
//Wrapping String into primitive datatype
b=Integer.parseInt(str);
System.out.println("value of b is:"+b);
}
}

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();

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 27


public static final Directions SOUTH = new Directions();
public static final Directions EAST = new Directions();
public static final Directions WEST = new Directions();
}
/////////////////Program to demonstrate enum and its methods
enum Branch
{
Computer,Electronics,Mechanical,Civil;
}
class EnumerationExample
{
public static void main(String[] args)
{
Branch h[] = Branch.values();
for (Branch b :h)
{
System.out.println(b+"----"+b.ordinal());
}
}
}

UNIT II: DERIVED SYNTACTICAL CONSTRUCTS IN JAVAMOBILENO: 9819421144 Page 28

You might also like