Constructors in Java:
n Constructor is a special method that gets invoked
“automatically” at the time of object creation.
n Constructor is normally used for initializing objects
with default values unless different values are supplied.
n Constructor has the same name as the class
name.
n Constructor cannot return values.
n A class can have more than one constructor as long as
they have different signature (i.e., different input arguments syntax).
n If you not write any constructor in class, java
compiler automatically creates one constructor called default constructor.
->
Apart from the default constructor, we can create our own constructors also. A
constructor can be defined with or without parameters but a constructor should
not have any return types. Also, a constructor can have any number of
parameters.
Rules for Java Constructor:
1. Constructors can use any access
modifier, including private.(A private constructor means only code within the
class itself can instantiate an object of that type, so if the private
constructor class wants to allow an instance of the class to be used, the class
must provide a static method or variable that allows access to an instance
created from within the class.)
2. The constructor name must match the
name of the class.
3. Constructors must not have a return
type.
4. It’s legal (but stupid) to have a
method with the same name as the class, but that doesn’t make it a constructor.
If you see a return type, it’s a method rather than a constructor. In fact, you
could have both a method and a constructor with the same name the name of the
class in the same class, and that’s not a problem for Java. Be careful not to
mistake a method for a constructor, be sure to look for a return type.
5. If you don’t type a constructor into
your class code, a default constructor will be automatically generated by the
compiler.
6. The default constructor is ALWAYS a
no-argument constructor.
7. Every constructor has, as its first
statement, either a call to an overloaded constructor (this()) or a call to the
super class constructor (super()), although remember that this call can be
inserted by the compiler.
8. A call to super () can be either a
no-arg call or can include arguments passed to the super constructor.
9. A no-argument constructor is not
necessarily the default (i.e., compiler-supplied) constructor, although the
default constructor is always a no-argument constructor. The default
constructor is the one the compiler provides! While the default constructor is
always a no-argument constructor, you’re free to put in your own no argument
constructor.
10. You cannot make a call to an
instance method, or access an instance variable, until after the super
constructor runs.
11. Only static variables and methods
can be accessed as part of the call to super() or this(). (Example: super
(Animal.NAME) is OK, because NAME is declared as a static variable.)
12. Abstract classes have constructors,
and those constructors are always called when a concrete subclass is
instantiated.
13. Interfaces do not have constructors.
Interfaces are not part of an object’s inheritance tree.
14. The only way a constructor can be
invoked is from within another constructor.
IMPORTANT POINTS TO REMEMBER:
If you write non static data member inside non static method then it is converted as this.non static data member
Whenever we declared a local variable with same name as non static data member then non static data member usage cannot be converted as this.non static data.
How these blocks are
executed?
->Whenever
we ask JVM to execute a .class file, it checks whether that file is available
or not.If available, before loading main() and other static members into
memory, it checks whether the program is having any static blocks.If available,
these blocks are loaded and executed.
->If
in the main(), we are creating the object of the class,before loading the
constructor of the class the JVM checks whether the class is having any
non-static blocks.If available, they are loaded and executed.Then, the
constructor block will gets executed.
->Stated
simply, static blocks are executed before main() and non-static blocks are
executed before constructors.
Benefits of using static
and non-static blocks:
->In
real-time applications, before loading the main module of the software, if we
want to provide any user-guide information, we will provide it in static
blocks.
->A
class may have any no. of constructors. If multiple constructors of the class
are having some statements in common, instead of writing them in all
constructors, we can define them in non-static blocks.
->The
following program demonstrates the use of static and non-static blocks :
/*
Program to implement static and non-static blocks */
class
StaticBlockDemo
{
StaticBlockDemo()
{
System.out.println("Inside
constructor");
}
static //static block
{
System.out.println("Inside static
block");
}
void display()
{
System.out.println("Inside display function");
}
{
//non-static block
System.out.println("Inside
non-static block");
}
public static void main(String args[])
{
System.out.println("Inside main");
StaticBlockDemo sd = new StaticBlockDemo();
sd.display();
}// end of main()
}//
end of class
Wrapper
Classes:
Wrapper
class:
All wrapper classes are defined in java.lang package.
A wrapper class wraps contains a primitive
data type in its object.
Character is a wrapper class in to a char
data type.
Primitive
data type Wrapper class:
char
Character
byte
Byte
int
Integer
float
Float
double
Double
long
Long.
1) Character
class: The character class wraps a value of the primitive type ‘char’
an object. An object of type character contains a single field whose type is
char.
Constructors:
1)
Character (char ch)
Ex: char ch = ‘A’
Character obj=new Character (ch);
Methods:
1)
char charValue ( )
Returns the char value of the invoking
object.
Ex: char x =obj.charValue( );
2)
static boolean isDigit(char ch)
Returns true if ch is a digit (0 to 9)
otherwise returns false.
Ex: char = ‘9’; boolean x =
character.isDigit(ch);
3)
static boolean isLetter(char ch).
returns true if ch is a letter (A to Z
or a to z)
4)
static boolean isupperCase(char ch).
returns true if ch is an upper case
letter (A to Z).
5)
static boolean isLowerCase(char ch)
returns true if ch is an Lower case
letter (a to z).
6)
static boolean isSpaceChar(char ch).
returns true if ch is coming from
Space Bar.
7)
static boolean iswhitespace(char ch )
returns true if ch is coming from Tab,
Enter, Backspace.
8) static char toUpperCase (char ch ).
converts ch into upper case.
9)
static char toLowerCase (char ch)
Converts ch into lowercase.
Q)
Which of the wrapper classes does not a
constructor with string parameter? (or) Which of the wrapper classes contains
only one constructor?
A)
Character
// test a character
import
java.io.*;
class CharacterTest
{
public static void main(String[] args)
throws IOException
{
while(true)
{
// to accept data
from key board
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter
a char");
char
ch=(char)br.read( );
// test the ch
if(ch=='@')
System.exit(0);
else
if(Character.isDigit(ch))
System.out.println("It
is a digit");
else
if(Character.isUpperCase(ch))
System.out.println("It
is a capital letter");
else
if(Character.isLowerCase(ch))
System.out.println("It
a small Letter");
else
if(Character.isSpaceChar(ch))
System.out.println("It is coming from space
bar");
else
if(Character.isWhitespace(ch))
System.out.println("It
is a white space");
else
System.out.println("Sorry, i don't know that
character");
}
}
}
D:\prr\Core
java>javac CharacterTest.java
D:\prr\Core
java>java CharacterTest
Enter
a char
p
It
a small Letter
Enter
a char
4
It
is a digit
Enter
a char
~
Sorry,
i don't know that character
Enter
a char
@
2) Byte class: The byte class wraps a value of primitive
type ‘byte’ in an object. An object of type byte contains a single field whose
type is byte.
Constructor:
1)
Byte(byte num)
2)
Byte(String str)
Ex: 1) byte b=99;
Byte
obj=new Byte(b);
2)
String str=”120”
Byte obj=new Byte(str);
Methods:
à1) byte byteValue( )
Returns the value of invoking object
as a byte.
à2) int compareTo(Byte b)
Compares
the numerical value of invoking object with that of ‘b’. returns 0, if the
values all equal. Returns a –ve value, if the invoking object has a lower
value. Returns a +ve value, if the invoking object has a grater value.
Ex: int n=b1.CompareTo(b2)
If b1==b2; n==0;
If b1<b2; n== ve;
If b1>b2; n== +ve;
à3) static byte parseBytes(String str)
throws NumberFormatException
Returns the byte equivalent ot the
number contained in the string specified by ‘str’.
à4) String toString( )
Returns a string that contains the
decimal equivalent of the invoking object.
à5) static ByteValueOf(String str)
throws NumberFormatException
Returns a byte object that contains
the value specified by string ‘str’.
// creating & comparing byte objects
import
java.io.*;
class
Bytes
{
public static void main(String
args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("enter
a byte no : ");
String str=br.readLine( );
Byte b1=new Byte(str);
System.out.print("enter
another byte no : ");
str=br.readLine( );
Byte b2=Byte.valueOf(str);
int n=b1.compareTo(b2);
if(n==0)
System.out.println("both
same ");
else
if(n>0)
System.out.println(b1+"is
bigger than"+b2);
else
System.out.println(b1+"is
lesser than"+b2);
}
}
D:\prr\Core
java>javac Bytes.java
D:\prr\Core
java>java Bytes
enter
a byte no : 34
enter
another byte no : 56
34is
lesser than56
3) Integer Class: The integer class wraps a value of the
primitive type ‘int’ in a object. An object of type integer contains a single
field whose type is int.
Constructors:
1)
Integer(int num)
2)
Integer(String str)
Methods:
1)
int intValue( )
Returns the value of invoking object
as an ‘int’.
2)
int compareTo(Integer obj)
Compare the numerical value of the
invoking object of ‘obj’. Returns 0, ve or +ve value.
3)
static int parseInt(String str) throws NumberFormatException
Returns int equivalent of the string
str.
Ex:
String str=”Hyderabad”;
Int n=Integer.parseInt(str);
4)
String toString( )
Returns a string from of the invoking
object.
5)
static Integer valueOf(String str) throws NumberFormatException
Returns an integer object that contain
the value shown by str.
6)
static String toBinaryString(int i)
Returns a string representation of the
integer argument in base 2.
7)
static String toHexString(int i)
Returns a string representation of the
integer argument in base 6.
8)
static String toOctalString(int i)
Returns a string representation of the
integer argument in base 8.
//converting into other
number system
import
java.io.*;
class
ConvertIntegers
{
public static void main(String
args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter
int :");
String str=br.readLine( );
int n=Integer.parseInt(str);
System.out.println("in
Decimal ="+n);
str=Integer.toBinaryString(n);
System.out.println("In
Binary ="+str);
str=Integer.toHexString(n);
System.out.println("In
HexaDecimal ="+str);
str=Integer.toOctalString(n);
System.out.println("In
Octal ="+str);
}
}
D:\prr\Core
java>javac ConvertIntegers.java
D:\prr\Core
java>java ConvertIntegers
Enter
int :
123
in
Decimal =123
In
Binary =1111011
In
HexaDecimal =7b
In
Octal =173
4) Float class: The float class wraps a value of primitive
type ‘float’ in an object. An object of type float contains a single field
whose type is float.
Constructers:
1)Float (float num)
2)Float (String str)
Methods:
1)
float floatValue( )
returns the value of the involving object as a float.
2)
double doubleValue( )
returns the value of the involving object as a double.
3)
int compareTo(Float f)
compares the numeric value of the involving object with
that of ‘f’ returns ., ve.+ve value.
4)
static float parseFloat (string str) throwsnumberFormatExecution.
Returns the float equivalent the string str .
5)
String toString ( )
returns the string equivalent of the involving object.
6)
static float valueOf (String str) throwsnumberFormatExecution
.Returns the float object with the value specified by
string str.
5) double class: The double class wraps a value of primitive
type ‘double’ in an object. An object of type float contains a single field
whose type is double.
Constructers:
1)
Double (double num)
2)
Double (String str)
Methods:
à1) double floatValue( )
returns the value of the involving object as a double.
à2) double floatValue( )
returns the value of the involving object as a float.
à3) int compareTo(Double d)
compares the numeric value of the involving object with
that of ‘d’ returns ., ve.+ve value.
à4)static double parseDouble (string
str) throws NumberFormatExecution
Returns the double equivalent the string str .
à5) String toString ( )
returns the string equivalent of the involving object.
à6) static double valueOf (String str)
throws NumberFormatExecution
Returns the double object with the value specified by
string str.
6)
Math class: The class math
contains methods for performing numerical operations.
Methods:
1)
static double sin(double arg)
Returns the sine value of arg. Arg is
an radians.
2)
static double cos(double arg)
Returns the cosine value of arg. Arg
is an radians.
3)
static double tan(double arg)
Returns the tangent value of arg. Arg
is an radians.
4)
static double log(double arg)
Returns the natural logarithm value of
arg.
5)
static double pow(double x,double y)
Returns x to the power of y value.
6)
static double sqrt(double arg)
Returns the square root of arg.
7)
static double abs(double arg)
Returns the absolute value of arg.
8)
static double ceil(double arg)
Returns the smallest integers which is
grater or equal to arg.
Ex: Math.ceil(4.5) à
is 5.0
Ceil means ceiling. It means up.
9)
static double floor(double arg)
Returns the grater integer which is
lower or equal to arg.
Ex:
Math.floor(4.5) à is 4.0
10)
static double min(arg1,arg2)
Returns the minimum value of arg1
& arg2.
11)
static double max(arg1,arg2)
Returns the maximum value of arg1
& arg2.
12)
static long round(arg)
Returns the rounded value.
Ex:
Math,round(4.6) à is 5
13)
static double random( )
Returns the random numbers between
0&1.
14)
static double toRadians(double angle)
Converts angle in degrees in to
radians.
15)
static double toDegrees(double angle)
Converts angle in radians in to
degrees.
// random numbers between
1 & 10
class
Rand
{
public static void main(String args[]) throws InterruptedException
{
while(true)
{
double
d=10*Math.random( );
int n=(int)d;
System.out.print(n+”\t”);
if(n==0)
System.exit(0);
Thread.sleep(3000);
}
}
}
D:\prr\Core
java>javac Rand.java
D:\prr\Core
java>java Rand
7 7 8 5 6 2 7 6 1 0