Professional Documents
Culture Documents
• Types of Constructor:
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
• Constructor without parameter is known as default
constructor.
• Constructor with parameter is known as
parameterized constructor
• Constructor with object as parameter is known as
copy constructor.
Constructors
• For example:
class Student
{
int rollno;
String name;
Student () //default constructor
{
rollno =10;
name =“xyz”;
}
}
Parameterized Constructors
• Constructor which takes some arguments then it
is called as parameterized constructor.
• For example:
class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
}
Copy Constructors
• Constructor which takes object as parameter.
• It is special form of parameterized constructor.
• For example:
class Student
{
int rollno;
String name;
Student (int r, String n) //parameterized constructor
{
rollno =r;
name =n;
}
Student (Student s) //copy constructor
{
rollno =s.rollno;
name =s.name;
}
}
Constructor Overloading
• Overloading refers to the • For example:
use of same name for class Student
different purposes. {
int rollno;
String name;
• A class can have more
Student (int r, String n) //parameterized
than one constructor but {
with different rollno =r;
parameters. This is name =n;
known as constructor }
overloading. Student (Student s) //copy
{
rollno =s.rollno;
name =s.name;
}
}
• For example:
Nesting of Methods class NestMethod
{ int len,bre;
• When a NestMethod(int l, int b)
{
method calls len=l;
another bre=b;
}
method in the void display()
same class, it {
System.out.println(“Length:"+len);
is called System.out.println(“Breadth:"+bre);
}
Nesting of void perimeter()
methods. {
display(); //nested call
int pr = 2 * (len+ bre);
System.out.println("Perimeter:"+pr);
}
}
‘this’ keyword
• To refer to own or current object in a method or a
constructor, Java defines the ‘this’ keyword.
• Uses of this keyword:
1. ‘this’ can be used inside any method to refer to the
current object.
2. ‘this’ to resolve instance variable hiding
3. ‘this’ to call one constructor from another constructor
Uses of ‘this’ keyword
1) ‘this’ can be used 2) ‘this’ to resolve instance
inside any method to variable hiding
refer to the current When a local variable has
object. the same name as an
instance variable, the local
Box(double w, double h) variable hides the instance
{ variable.
this. width = w; Box(double width, double
height)
this. height = h;
{
}
this. width = width;
this. height = height;
}
Uses of ‘this’ keyword
3) ‘this’ to call one constructor from another
constructor within a class
class Student
{
int roll,marks; String name;
Student () //constructor1
{
roll=1;
name=“xyz”;
}
Student(int m) //constructor2
{
this();
marks = m;
}
}
Methods overloading
• defining two or more methods within the
same class that are having the same name,
but with different parameter
• implementation of compile time
polymorphism.
• Java uses the type and/or number of
arguments to determine which version of the
overloaded method to actually call.
Methods overloading
class Area class Shape
{ {
int area(int side) public static void main(String args[])
{ {
Area s = new Area();
return(side * side);
}
int x=s.area(10);
float area(float radius)
System.out.println ("Area of square : "+x);
{
return(3.14f * radius * radius); int y=s.area(10,20);
} System.out.println ("Area of rect: "+y);
int area(int len, int wid)
{ float z = s.area(5.5f);
return(len * wid); System.out.println ("Area of circle : "+z);
} }
} }
Command line argument
• Sometimes we need to pass information into a program
when we run it. This is accomplished by
passing command-line arguments to main( ).
• Command-line argument is the information that directly
follows the program’s name on the command line when
it is executed.
• Can be used to specify configuration information while
launching application.
• There is no restriction on the number of java command
line arguments. We can specify any number of
arguments
• Information is passed as Strings.
• They are captured into the String args of your main
method
Command line argument
• The first command-line argument is stored at args[0],
the second at args[1], and so on
• For Example:
class CommandLine
{
public static void main(String args[])
{
for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
}
Varargs: Variable-Length Arguments
• It simplifies the creation of methods that need to take a
variable number of arguments. This feature is called
varargs and it is short-form for variable-length
arguments.
• A method that takes a variable number of arguments is a
varargs method.
• A variable-length argument is specified by three
periods(…).
• Syntax of varargs :
public static void fun(int ... a)
{
// method body
}
Varargs: Variable-Length Arguments
• Rules for varargs:
1. There can be only one variable argument in the
method.
2. Variable argument (varargs) must be the last
argument.
Method Description
Access Modifier
Public Protected Default Private
Access Location
Subclass in same
Yes Yes Yes No
package
Subclass in other
Yes Yes No No
package
ii)String (char ch[]) - Initializes a new String from the given Character array.
ex: char ch[]={‘j’,’a’,’v’,’a’};
String s1=new String(ch);
iii)String (char ch[],int startindex,int n) –Initialized with ‘n’ no. of characters from
a given character array started from the start_index.
ex: char ch[]={‘J’,’a’,’v’,’a’};
String s1=new String(ch,2,2);
6)equalsIgnoreCase()
• It is used to check two strings for equality and returns the boolean
value true if they are equal else false.
• The equalsIgnoreCase( ) is not case sensitive method.
• Syntax: boolean equalsIgnoreCase(String str)
• Example: String a = “Hello”;
String b = “HELLO”;
boolean res=a. equalsIgnoreCase(b) ; //true
String Methods
7) compareTo( ) and compareToIgnoreCase( )
• used to check whether one string is greater than, less than or equal to
another string or not.
• returns the “difference” string1 and string2
• compareTo( ) is case-sensitive and compareToIgnoreCase( ) is case
insensitive.
• Syntax: int compareTo(String str)
int compareToIgnoreCase(String str)
• It will return
10) replace( )
• used to replace all the occurrences of a character with another
character
• Syntax: String replace(char original, char replacement)
• For ex: String s = “mama”;
String s1=s.replace(‘m’,’k’);
String Methods
11) toLowerCase( ) and toUpperCase( )
• These methods will convert the strings into lower case and upper case
respectively
• Syntax:
String toLowerCase( )
String toUpperCase( )
• For ex: String str = “Solapur City”;
String t = str.toUpperCase();
String u = str.toLowerCase();
12) trim()
• removing white space at both ends
• does not affect whites space in the middle
• Example:
String s = “ What is this? “;
String k = s.trim();
StringBuffer class
• StringBuffers are mutable that is we can modify the
characters of the string.
• We can insert new characters, modify them delete them at any
location of string of can append another string to other end.
• So StringBuffer provides the flexible string.
• Constructors:
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 and reserves room for 16 more characters without
reallocation.
3. StringBuffer(int capacity): creates an empty string buffer with
the specified capacity as length.
• For ex StringBuffer sb = new StringBuffer("India");
StringBuffer Methods
1) length( )
• Returns total number of characters stored in StringBuffer object
• Syntax: int length( )
• Example:
StringBuffer sb = new StringBuffer("India");
int len = sb.length());
2) capacity( )
• Returns total allocated capacity
• Syntax: int capacity( )
• Example:
StringBuffer sb = new StringBuffer("India");
int cap = sb.capacity());
• Here the variable cap will contain capacity 21 i.e. actual length +
additional room for 16 characters.
StringBuffer Methods
3) setLength( )
• used to set the length of the buffer.
• Syntax: void setLength(int len)
• Example:
StringBuffer sb=new StringBuffer(“Solapur”);
sb.setLength(3); // now sb object contains only 3 chars
4) setCharAt( )
• Used to set the character at certain index in the StringBuffer
• Syntax:
void setCharAt(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer(“Kolkata”);
sb.setCharAt(0,‘C’);
• After execution of these statements, ‘sb’ will be “Colkata”.
StringBuffer Methods
5) append( )
• Used to concatenates any other type of data to the end of the invoking
StringBuffer object.
• Syntax: StringBuffer append(datatype var)
• Example:
StringBuffer sb = new StringBuffer(“Parle");
int x = 20;
StringBuffer a = sb.append(x); //a will be “Parle20”
6) insert( )
• used to insert one string, character or object into another string.
• Syntax:
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "love ");
• After this, the contents of ‘sb’ will be “I love Java!”
StringBuffer Methods
5) append( )
• Used to concatenates any other type of data to the end of the invoking
StringBuffer object.
• Syntax: StringBuffer append(datatype var)
• Example:
StringBuffer sb = new StringBuffer(“Parle");
int x = 20;
StringBuffer a = sb.append(x); //a will be “Parle20”
6) insert( )
• used to insert one string, character or object into another string.
• Syntax: StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
• Example:
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "love ");
• After this, the contents of ‘sb’ will be “I love Java!”
StringBuffer Methods
7) reverse( )
• To reverse the characters inside the StringBuffer
• Syntax: StringBuffer reverse()
• Example: StringBuffer s = new StringBuffer(“Yellow”);
s.reverse(); //s will be “wolleY”
For ex:
int x = 25;
Integer y = new Integer(33);
Integer Wrapper Class
• An Integer object encapsulates a simple int value.
• Integer is a wrapper class for int.
• Constructors:
• Integer(int i) : constructs an Integer object equivalent to
the integer i . Eg: Integer it1=new Integer(25);
• Integer(String s) : constructs an Integer object equivalent
to the numeric string s. Eg: Integer it1=new Integer(“25”);
Integer Wrapper Class
• Methods of Integer Wrapper class:
static int parseInt(String s) Converts numeric string to signed
decimal int value
Ex: int a=Integer.parseInt(“25”);
static String toString(int i) Converts int value into a String object
Ex: String s=Integer.toString(25);
byte byteValue() Converts Integer object into primitive
type. These methods unwraps object.
short shortValue()
Integer it1=new Integer(25);
int intValue()
long l=it1.longValue();
long longValue() int i=it1.intValue()
float floatValue()
double doubleValue()
Integer Wrapper Class
• Methods of Integer Wrapper class:
static String toBinaryString(int Used to convert decimal into binary,
i) octal and hex respectively.
static String toOctalString(int i) Ex:
String s=Integer.toBinaryString(10);
static String toHexString(int i) String s=Integer.toOctalString(10);
String s=Integer.toHexString(10);
static Integer valueOf(String s, int Used to convert binary, octal and hex
base) into decimal.
Ex:
int dec=Integer.valueOf(“1010”,2);
int dec=Integer.valueOf(“10”,8);
int dec=Integer.valueOf(“a”,16);
Enumerated Types
• used to define collections constants
• To define enumerated types enum keyword is used.
• Syntax:
enum collectionname { list of elements separated by comma};
• It can be used in s
• witch.
• It can be traversed
• It can have fields, methods as well as constructors.
Enumerated Types
class EnumDemo
{ enum color{Red,Green,Black,Yellow,White}
public static void main(String args[])
{
for(color s:color.values())
{
System.out.println(s);
}
}
}