Download New Operator - E

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
JAVA PROGRAMMING
SUBJECT
CLASS
UNIT
SEMESTER
STAFF
NASC –IT
: JAVA PROGRAMMING
: II BSC IT
: II
: 4
: M. SHEELA NEWSHEEBA
UNIT-II:
Constants, Variables, Data Types - Operators and Expressions – Decision Making and
Branching: if, if ..else, nested if, switch, ? : Operator - Decision Making and Looping: while, do,
for – Jumps in Loops - Labeled Loops – Classes, Objects and Methods.
CONSTANT
The values does not change during the execution of program
LITERALS
Literals are nothing but constants. A literal represents a value of certain type, whereas the type itself
describes how the value behaves and how it is stored.
The various literals are as follows
Integer literals
Any integral numeric value is an integer value. Ex are 5, 7 etc. These are decimal values i.e. of
base 10.
The other two bases used in integral literals are octal and hexadecimal. Octal values are denoted
in Java with a leading zero. Decimal numbers cannot have leading zero. A hexadecimal constant
can be specified with a leading 0x or 0X.
Floating Point literals
Floating Point numbers represent decimal values with a fractional component. They can be
expressed in two ways
Standard notation – use some number followed by a decimal point and then some fractional
digit.
Ex – 5768.33333333
Scientific notation – a standard notation floating point number with a additional notation that
indicates a multiplication times ten to the specified exponent. The exponent is given by a E or e
followed by decimal number. Ex – 45.34e12, 348e-01.
Floating point literals in Java default to double precision, you need to append an F or f to force
the constant to be small enough to store into a variable declared as a float.
JAVA PROGRAMMING
NASC –IT
Boolean Literals
The Boolean literals can have two values i.e. true or false.
Character Literals
A literal character is represented inside a pair of Parentheses (‘ ‘). For characters that are
impossible to enter directly, there are several escape sequences which allow to enter the
character such as (‘\’), for the single quote character itself and ‘\n’ for new line character.
String literals
String literals are arbitrary text enclosed in double quotes. Ex – “name”, “Command”. Java strings must
begin and end in the same line. There is no line continuation escape sequence as in other language.
VARIABLES
The variable is the basic unit of storage in Java. A variable is defined by the combination of an
identifier, a type and a optional identifier. All variables have a scope, which defines their visibility and a
lifetime.
Declaring a variable
The variables must be declared before using them. The format for declaration is
type identifier [= value][, identifier [=value]…]
Examples :
int a, b, c;
int a = 8, b = 7;
double x = 49.90;
char c = ‘j’;
Dynamic initialization
The variables can be initialized dynamically, using any expression valid at the time the variable
is declared.
Class Leng{
public static void main(String args[ ]){
double a = 3.0 , b = 4.0;
double c = Math.sqrt(a * a + b * b) ;
System.out.println(“ Hypotenuse “ +c);
}
}
a and b are declared as constants, c is initialized dynamically to the length of the hypotenuse.
The scope and lifetime of variables
JAVA PROGRAMMING
NASC –IT
A block defines the scope. A scope determines what objects are visible to other parts of the
program. It determines the lifetime of those objects. In Java the two major scopes are those defined by
a class and those defined by a method.
When you declare a variable within a scope, you are localizing the variable and protecting it
from unauthorized access and/or modification. Scopes can be nested. Objects declared within
inner scope will not be visible outside it.
class Scope{
public static void main(String args[ ]){
int x;
x = 12;
if ( x == 12){
int y = 6;
// y is visible only to this block
System.out.println(“the value of y :” +y);
x = y + 4;
}
y = 5;
// error as y is not visible here
System.out.println(“the value of x : +x);
}
}
y is defined within the if block. So its value is not visible outside that block. Within the if block x
can be used as code within a block has access to the variables declared by an enclosing scope.
Variables are created when their scope is entered, and destroyed when their scope is left. So the
variables declared within a method will not hold their values between calls to that method.
Type conversion and casting
It is common to assign a value of one type to a variable of another type. If the two types
are compatible, then Java will perform the conversion automatically. It is possible to assign a int
value to a long variable. Not all types are compatible, so not all type conversions are implicitly
allowed. i.e. there is no conversion defined from double to byte. It is possible to get a conversion
between incompatible types using the ‘casting’
Automatic conversion
Automatic conversion occur under the following conditions
1. The two types are compatible
2. The destination type is larger than the source type
A widening conversion takes place when the conditions are met. Numeric types are compatible with
each other. The numeric types are incompatible with char or boolean. char and boolean are not
compatible with each other.
JAVA PROGRAMMING
NASC –IT
Type casting
When you assign an int value to a byte variable the conversion will not be performed automatically as
a byte is smaller than an int. The conversion is called a narrowing conversion as you are explicitly
making the value narrower to fit into the target type.
A cast is a explicit type conversion. The form is
(target-type)value
The target-type specifies the desired type to convert the specified value to.
Ex –
int a;
byte b;
b = (byte) a;
Type promotion rules
1.
2.
3.
4.
All bytes and short values are promoted to int
if one operand is long, the whole expression is promoted to long
If one operand is float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
DATA TYPES
Java defines eight simple types of data: byte, short, int, long, char, float , double and boolean.
These can be put in four groups.
Integers - this group includes byte, short, int and long which are for whole-valued signed
numbers
Floating - point numbers : This includes float and double
Characters - this includes char
Boolean - this includes boolean, which is a special type for representing true/false values
Integers :
All the four integer types are signed, positive and negative values. Java doesn’t support
unsigned, positive-only integers.
The width and the range of the integer types can be specified
Type width
long
64
Range
-9,233,372,036,854,775,808 to 9,233,372,036,854,775,807
JAVA PROGRAMMING
int
32
-2,147,483,648 to 2,147,483,647
short
16
-32,768 to 32,768
byte
8
-128 to 127
NASC –IT
byte- This is a signed 8-bit type that has a range from –128 to 127. The variables of type byte
are used when you work with a stream of data from a network or file. The variables can be
declared as - byte a ;
short - This is a signed 16-bit type that range from -32,768 to 32,768.
int - It is a signed 32 bit type that ranges from -2,147,483,648 to 2,147,483,647
long - long is a signed 64 bit type and is useful when an int type is not large enough to hold the
desired value.
Floating –point types
The two kinds of floating point types are float and double which represent single and double
precision numbers
type
width
range
double
64 bits
1.7e-308 to 1.7e+308
long
32 bits
3.4e-038 to 3.4e+038.
float - specifies single precision values. Single precision is faster on some processors and
takes half as much space as double precision. float can be useful when representing dollars and
cents
double – It uses 64 bits to store a value. double precision is actually faster than single precision.
All mathematic, trigonometric functions such as sqrt(), sin(), cos() return double values. double
is the best choice if you need to maintain accuracy.
Characters
The data type used to store characters is char. Java uses Unicode to represent characters.
Unicode defines fully international char set that represents characters of all languages, such as
Latin, Greek. Arabic etc. It requires 16 bits. The range of char is 0 to 65536. There are no
negative chars.
Ex
class Chardemo{
JAVA PROGRAMMING
NASC –IT
public static void main(String args[ ]){
char ch1, ch2;
ch1 = 88;
ch2 = “Y”;
System.out.println(“ch1 and ch2 : ” + ch1+” “+ch2);
}
}
The output is
ch1 and ch2 : X Y
where 88 is the ASCII value that corresponds to X.
Booleans
boolean is the type used for logical values. It can have any one of the two possible values true
or false. This is the type returned by all relational operators such as a > b. boolean is the type
required by conditional expressions that govern the control statements such as if or for.
JAVA OPERATORS
OPERATORS
Operators are characters that instruct the compiler that you wish to perform an operation on some
operands. Operators specify operation instructions, while operands are variables, expressions or literal
values. Some operators take a single operand these are called unary operators. Some operators come
before the operand, these are called prefix operators. And those that come after the operands are called
postfix operators. Most operators are between operands and are called as infix binary operators. An
operator that takes 3 operands called as ternary operator.
The basic types of operators are – arithmetic, bitwise, relational and logical.
Arithmetic Operators
The operands must be a numeric type, and cannot be used on boolean types. We can use it on char type
since char is a subset of int in Java.
Four function calculator operators
class Calculate{
public static void main(String args[ ]){
JAVA PROGRAMMING
NASC –IT
int a = 5;
int b = a + 2;
int c = a * b;
int d = c – b;
int e = c / d;
int f = - b;
System.out.println(“value of b =” +b);
System.out.println(“value of c =” +c);
System.out.println(“value of d =” +d);
System.out.println(“value of e =” +e);
System.out.println(“value of f =” +f);
}
}
Modulus operator
this operator returns the remainder of a division operation. It can be applied to floating-point
types as well as integer types.
Arithmetic assignment operator
The statement is of the form
var = var op expression
which can be written as
var op = expression
ie a = a + 5 ; can be written as a + = 5 ;
the other operators can be given as
a % = 5 ; which is nothing but a = a % 5;
a/=7;
a * = 10 ;
BITWISE LOGICAL OPERATORS
Bitwise NOT
JAVA PROGRAMMING
NASC –IT
This is the unary NOT operator ^. which inverts all the bits of its operand .
EX
the number 18 can be represented in binary as 10010 which becomes 01101 after the NOT
operator is applied.
Bitwise AND
The AND operator (&) produces 1 when both the operands are 1 , 0 zero is produced in all other cases.
ex
1010
& 1110
1010
Bitwise OR ( | )
In this case , the result is 1 if any one of the operands is 1.
Ex
1010
| 1001
1011
Bitwise XOR ( ^ )
The result is 1 if exactly one operand is 1, else the result is zero.
Ex 1110
^ 1100
1011
Right shift ( >> )
This operator shifts all the bits in a value to the right to a specified number of times. The syntax is
value >> num ;
Ex int a = 16 ;
JAVA PROGRAMMING
NASC –IT
a = a>>2 ;
The result is 4 . ie the binary value of 16 is 10000 which after right shift becomes 00100 . The
decimal value of the result is 4.
The operator shifts the value of 16 to the right two positions, which causes 2 low – order bits to
be lost resulting in number being set to 4.
Left shift ( << )
The syntax is value << num ;
Ex
int a = 64 ;
a = a << 2 ;
the result is 256.
ie the binary value of 64 is 0100 0000 is shifted left two positions, and the result is 1 0000
0000 which is 256.
unsigned right shift ( >>> )
>> operator automatically fills two high order bits with its previous contents each time a shift
occurs. This preserves the sign of the value. If you are shifting something that doesn’t represent
a numeric value, you may not want sign extension to take place. In this case you need to shift a
zero to the high order bit no matter what the initial value was. This is known as unsigned shift.
Relational operator
These operators determine the relationship that one operand has to the other. They determine the
equality and the ordering.
operators
==
equal to
!=
not equal to
>
greater than
>=
greater than and equal to
JAVA PROGRAMMING
<
less than
<=
less than and equal to
NASC –IT
Boolean logical operators
They operate on boolean operands.
&
logical AND
|
logical OR
^
logical XOR
||
short circuit OR
&&
short circuit AND
!
logical unary NOT
==
assignment
?:
ternary
Ternary operator
Java includes a special ternary operator(three way ) that can replace certain types of if then else
statements. It has the form
exp1 ? exp2 : exp3
ie if expression1 is true then expression2 will be evaluated else expression3 will be evaluated
OPERATOR PRECEDENCE
The precedence or priority of the operators is given as follows
Highest
()
[]
++
--
~
*
/
%
+
-
!
JAVA PROGRAMMING
>>
>>>
<<
>
>=
<
==
!=
NASC –IT
<=
&
^
&&
||
?:
=
op=
Lowest
Square brackets provide the array indexing. The dot operator is used to dereference objects.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often necessary
to obtain the result you desire. For ex, consider the following expression
a >> b + 3 ;
This expression first adds 3 to b and then shifts right by that results. ie. the expression can be
written using redundant parentheses like
a >>(b + 3 ) ;
If you want to first shift right by b positions and then add 3 to that result, you will need to
parenthesize like,
(a >> b ) + 3 ;
CONTROL STATEMENTS
Control statements are used to alter the flow of execution according the changes to the state of a
program.
The control statements are basically categorized into three types.
JAVA PROGRAMMING
NASC –IT
1. Selection statements
2. Iteration statements
3. Jump statements
SELECTION STATEMENTS
These statements make the program to choose different paths based on the result of an
expression or the state of a variable. The two selection statements in Java are
1. if
2. switch
3.
If Statement
The if statement is a conditional statement and it is two-way. The syntax is
if (condition)
statement1;
else
statement2;
the condition is a expression which returns a boolean value. The else clause is optional.
NESTED-IF STATEMENT
Syntax :
if (condition){
If(condition)
Statement1;
else
Statement2;
}
else
Statement3;
Once the first condition is satisfied, we have to move to the inner if statement which checks for
the next condition. And depending on its evaluation Statements 1 or 2 is executed.
JAVA PROGRAMMING
NASC –IT
SWITCH STATEMENT
Switch is a multi-way branch statement. It provides a better alternative than a large series of ifelse –if statements.
Syntax :
switch(expression){
case value1 :
statement sequence
break;
case value2 :
statement sequence
break;
case value3 :
statement sequence
break;
……………………………….
case valueN :
statement sequence
break;
default :
statement sequence
}
The expression must be of type byte, short, int or char. Each of the values specified in the case must
be type compatible with the expression. Each value must be a unique literal. Duplicate case values
are not allowed.
Nested switch statements
You can use a switch as a part of the statement sequence of an outer switch. This is called a
nested switch.
Important notes on switch statement
1. The switch differs from if statement in that switch can only test for equality Whereas if
can evaluate any type of Boolean expression.
2. No two case constants in the same switch can have identical values
3. A switch statement is usually more efficient than a set of nested ifs.
JAVA PROGRAMMING
NASC –IT
DECISION MAKING AND LOOPING STATEMENTS
These statements create loops. A loop executes the same set of statements repeatedly until a
certain condition is met.
WHILE STATEMENT
Syntax :
while(Condition){
body of the loop
}
The condition can be any Boolean expression. The statements within the body of while will be executed
till the condition is true. If the condition becomes false, control passes to the statement that follows the
loop. Ex class Sum{
public static void main(String args[ ]){
int i = 1;
int sum = 0;
while(i = 10){
sum = sum + i;
i = i + 1;
}
System.out.println(“The sum of first 10 natural numbers :” +sum);
}
}
DO – WHILE STATEMENT
Sometimes we need to check a condition at the end of the loop rather than the beginning . This can be
done with the help of do-while.
do{
body of the loop
}while(condition);
JAVA PROGRAMMING
NASC –IT
Each iteration of the loop , executes the body of the loop first and then the condition is evaluated. If the
condition is true, the loop will repeat else the loop will terminate
class Dowhile{
public static void main(String args [ ]){
int sum = 0;
int n = 10;
int inc = 2;
do{
sum = sum + inc;
inc = inc + 2;
}while(inc <=10);
System.out.println(“the sum of even numbers till 10:” +sum);
}
}
FOR STATEMENT
Syntax:
for(initialization ; condition ; iteration ){
body of the loop
}
First the initialization part of the loop is executed. Then the condition is evaluated. If the result of the
condition or the expression is true, the body of the loop is executed, and the iteration part of the loop is
executed. This is repeated till the condition becomes false. If it is false the loop is terminated.
JUMP STATEMENTS
BREAK STATEMENT
Use of break statement
1. To terminate a statement sequence in switch statement
2. To exit a loop
3. As a civilized form of goto.
Using break to exit a loop
JAVA PROGRAMMING
NASC –IT
By using break, you can force intermediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop. When a break statement
is encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop.
class Usebreak1{
public static void main(String args[ ]){
for(int i = 1; i<=10;i++){
if (i = = 4) break;
System.out.println(“The value of i is : “ + i ) ;
}
}
}
when used inside a set of nested loops, the break statement will only break out of the innermost
loop.
class Usebreak2{
public static void main(String args[ ] ){
for(i = 1 ; i <=5 ; i ++ ){
System.out.println(“i = “ +i ) ;
for( j = 1 ; j <= 5 ; j ++){
if ( j = = 3 ) break;
System.out.println(“j = “ +j ) ;
}
}
}
}
Using break as a form of goto
Java doesn’t have a goto statement , but it uses break statement as a form of goto.
Syntax :
break label1 ;
label1 is the name of the label that identifies a block of code. When this statement executes, control
is transferred out of the named block of code.
JAVA PROGRAMMING
NASC –IT
class Break{
public static void main(String args[ ]){
bolean t = true ;
first : {
second : {
third :{
System.out.println(“Before break”);
if (t) break second ;
System.out.println(“this wont execute”);
}
System.out.println(“Within second”);
}
System.out.println(“After the second block”);
}
}
}
Continue Statement
Sometimes we need to continue the execution of the loop, but we need to stop the remainder of the
code in the body of the loop. This can be done with the continue statement. It can be used in all the
looping statements. In the case of do-while and while statements, continue statement causes control to
be transferred directly to the conditional expression that controls the loop. In the case of for loop,
continue transfers control to the iteration portion.
class Continue{
public static void main(String args [ ]){
int i ;
for(i = 0; i < 10 ; i++){
System.out.println( i + “ “);
If (i % 2 == 0) continue;
System.out.println( “ “);
}
}
}
Use Of Continue In For Loop
class Continuefor{
JAVA PROGRAMMING
NASC –IT
public static void main(String args [ ]){
outer : for( i = 0 ; i<10 ; i ++){
for( j = 0 ; j<10 ; j ++){
if (j < i){
System.out.println();
continue outer;
}
System.out.println(“ “ +(i * j));
}
}
System.out.println();
}
}
Return Statement
return is used to explicitly return from a method. It causes program control to transfer back to the
caller of the method
class Return{
public static void main(String args [ ]){
boolean t = true;
System.out.println(“Before return”);
if ( t ) return;
System.out.println(“After checking value of t”);
}
}
CLASSES – DECLARATION
A class is a logical construct upon which objects can be build. The class can be considered as a
template for objects. All your applications are encapsulated within a class. So depending on the
application your class can be simple or complex. We can say that class is a new type of data defined
by the user.
The general form of declaration of a class is as follows –
class classname {
datatype instancevariable1;
datatype instancevariable2;
………………………
returntype methodname1( list of parameters){
method – implementation ;
}
returntype methodname2 (list of parameters){
JAVA PROGRAMMING
NASC –IT
method- implementation;
}
……………………………….
}
the class declaration starts with the keyword “class” followed by the name of the class which the
user can give with relevance to his application. The scope of the class lies between the curly
braces following the class name and the braces after the method declaration.
In the declaration we have specified the instance variables inside the class. These are variables
which belong to every instance or object of a class. Hence they are given the name instance
variables . In addition to instance variables, we can also declare class variables. Hope you
remember that the keyword ‘static’ used in the main method specifies that main is a class
method. So static, is the access modifier that specifies that the data member or a method is a
class variable or class method.
The method definition follows the declaration of the variables. If your method returns some
value specify the return type which is followed by the method name.
Let us declare a simple class called Employee
class Employee{
int eno;
String ename;
double hra;
double cca;
double pf;
double it;
}
DECLARING OBJECTS
As we know the class is a new type of data declared by the user. This type can be used to declare
objects of the same type. For ex, if we want to create an instance of type Employee, the
statement is
Employee e = new Employee();
Where we are declaring a variable ‘e’ of type employee. The new operator allocates
memory for Employee object at runtime and reference is assigned to ‘e’. So ‘e’ can be called as
object reference variable.
JAVA PROGRAMMING
NASC –IT
Eno
Name
hra
e
Cca
Pf
it
The object reference variables behave differently when an assignment is made . For ex ,
Employee e = new Employee();
Employee em = e ;
e, em doesn’t refer to two different objects. Because we haven’t allocate
memory for employee object in the second statement. So em just refers to the same object which
e is referring.
e
eno
name
hra
em
cca
pf
it
New Operator
The new operator dynamically allocates memory for an object. It has the general syntax :
class-var = new classname();
class-var is the variable of the class type being created. The classname is the name of the class
that is being instantiated. The class name followed by parentheses specifies the constructor for
the class. A constructor defines what happens when an object of a class is created. If no explicit
constructor is defined, then the compiler will automatically invoke a default constructor.
JAVA PROGRAMMING
NASC –IT
Since the memory allocation takes place at runtime, this approach is advantageous. Like, your
program can create as many as objects as you need during the execution of the program. As
memory is finite, there is a possibility that new will not be able to allocate memory for an object
when memory is insufficient. A run-time exception will occur. We can handle such errors using
exception handling.
INTRODUCTION METHODS
Although it is perfectly fine to create a class that contains only data, it rarely happens. We
will use methods to access the instance variables. Let us use methods to print the net salary of the
Employee class which we have declared earlier.
class Employee{
int eno;
String ename;
double hra;
double cca;
double pf;
double it;
public void netsal(){
System.out.println((hra+cca) –( pf + it));
}
}
public class Empex{
public static void main(String args[ ] ){
Employee e = new Employee();
e.eno = 1;
e.ename = “Asha”;
e.hra = 200;
e.cca = 150;
e.pf = 100;
e.it = 150;
e.netsal();
}
}
When e.netsal() is invoked, the Java run-time system transfers control to the code defined inside
netsal(). After the statements inside netsal() have executed, control is returned to the calling
routine . The instance variables pf, it , hra and cca are referred directly without using dot
operator. When a method uses an instance variable defined inside a class it can use it directly
without explicit reference to an object and without using the dot operator. A method is invoked
JAVA PROGRAMMING
NASC –IT
relative to some object of the class. Thus there is no need to specify the object the second time
within the method.
METHODS RETURNING A VALUE
We must consider certain features with these methods returning a value. i. e
1. The type of data returned by a method must be compatible with the return type specified
by the method.
2. The variable receiving the value returned by a method must also be compatible with the
return type specified for the method
class Student{
int rno;
String sname;
int m1;
int m2;
public int rettotal(){
return (m1+m2);
}
}
public class Studex{
public static void main(String args [ ] ){
Student s = new Student();
s.rno = 5;
s.sname = "Swathee";
s.m1 = 86;
s.m2 = 89;
System.out.println( "RNo Name Mark1 Mark2 Total" );
System.out.println( s.rno+" "+s.sname+" "+s.m1+" "+s.m2+"
}
"+s.rettotal());
}
The method rettotal() returns the total marks of the student. The first println statement prints the
heading.The second println statement prints the value for rollno, name of the student , his/her
marks and the total marks. The blank space in between the values is provided by the space
between the double quotes in the second print statement. i.e s.rno+ followed by double quotes
and few blank spaces and again double quotes provides the required blank space between s.rno
and s.sname. Similarly we have provided blank spaces between the other values. In this
statement + is the operator that is used for concatenation.
JAVA PROGRAMMING
NASC –IT
ADDING METHODS THAT TAKES PARAMETERS
In the above examples, we have assigned the values for instance variables as follows ,
s. rno = 5;
s.sname = “Swathee”;
etc. Sometimes with this type of assignment we might forget to give some values. Moreover, in
well defined programs , instance variables should be accessed only through methods.
class Student{
int rno;
String sname;
int m1;
int m2;
public void setvalues(int rollno, String name, int mark1, int mark2){
rno = rollno;
sname = name;
m1 = mark1;
m2 = mark2;
}
public int rettotal(){
return (m1+m2);
}
}
public class Studex{
public static void main(String args [ ] ){
Student s = new Student();
s.setvalues(1, “Sruthee”, 78, 90);
System.out.println( "RNo Name Mark1 Mark2 Total" );
System.out.println(s.rno+" "+s.sname+" "+s.m1+" "+s.m2+" "+s.rettotal());
}
}
CONSTRUCTORS
When we create an object of a class, a special kind of method called a constructor is always
invoked. If we don’t define a constructor the compiler will provide a default constructor. The
constructor’s main purpose is to initialize the instance variables .
The two main features that distinguish constructors from other class methods are
1. A constructor never returns any value and we neednt specify the return type
2. The constructor has the same name as the class.
JAVA PROGRAMMING
NASC –IT
class Box{
double width;
double height;
double depth;
Box (){
width = 15.5;
height = 10.3;
depth = 12.7;
}
public double vol(){
return (width * height * depth);
}
}
public class Boxex{
public static void main(String args[ ]){
Box b1 = new Box();
Box b2 = new Box();
System.out.println(“Volume of the box "+b1.vol());
System.out.println(“Volume of the box "+b2.vol());
}
}
PARAMETERIZED CONSTRUCTORS
We have used a constructor, where the dimensions are similar for all box objects that are
created. This may not be of much use for us. We need to create box objects of different
dimensions. This can be done by adding parameters to constructors.
class Box{
double width;
double height;
double depth;
Box (double w, double h, double d){
width = w;
height = h;
depth = d;
}
public double vol(){
return (width * height * depth);
}
}
JAVA PROGRAMMING
NASC –IT
public class Boxex{
public static void main(String args [ ] ){
Box b1 = new Box(10.54, 12.89, 10.43);
Box b2 = new Box(12.5, 13, 15.8);
System.out.println(“Volume of box1 "+b1.vol());
System.out.println(“Volume of box2 "+b2.vol());
}
}
this KEYWORD
this keyword can be used inside any method to refer the current object. this is a reference to the
object on which the method was invoked.
INSTANCE VARIABLE HIDING
It is illegal to have two local variables with the same name within the same scope. But we can
have a local variable with the same name as that of a instance variable. In that case, the local
variable hides the instance variable, and a name collision occurs as both these have the same
name. Such name collisions can be resolved with the help of this keyword.
In the above example, we have the formal parameters w, h and d for the constructor Box. If we
have the name for these parameters as width , height and depth , then our constructor changes
with the use of this keyword as follows,
Box (double width, double height, double depth){
this.width = width;
this.height = height;
this.depth = depth;
}
METHOD OVERLOADING
Java allows you to define several methods in a class with the same name as long as each
method has a set of parameters that is unique. This is called as method overloading. The name
of a method with the type and number of parameters form the signature of the method. Method
overloading is one way through which Java implements polymorphism. The overloaded methods
must differ in the type and /or the number of parameters. They may have different return types
but the difference in return type alone is not sufficient to distinguish two versions of a method.
JAVA PROGRAMMING
NASC –IT
class Add{
void sum(int a, int b){
System.out.println(“ the result is :” +(a+b));
}
void sum(double a, double b){
System.out.println(“ the result is : “+ (a+b));
}
}
class Addex{
public static void main(String args [ ]){
Add a1 = new Add();
Add a2 = new Add();
a1.sum(10,15);
a2.sum(10.9,23.67);
}
}
In the above example the method sum() is overloaded. The type of parameter passed to the first
version is int, and then we have passed values of type double.
When an overloaded method is called, Java looks for a match between the arguments used to call
the method and the method’s parameters. Then the corresponding method is invoked
OVERLOADING CONSTRUCTORS
Similar to method overloading we can overload constructors. In our example Box we
have used constructor with three parameters. Every time we need to pass three arguments to this
constructor. If we don’t provide the three arguments then we will get an error. Sometimes we
might need to create objects and we need to initialize all the dimensions with a same value. We
can do this with the help of constructor overloading.
class Box{
double width;
double height;
double depth;
Box (double w, double h, double d){
width = w;
height = h;
depth = d;
}
Box(double val){
width = height = depth = val;
}
public double vol(){
return (width * height * depth);
}
JAVA PROGRAMMING
NASC –IT
}
public class Boxex{
public static void main(String args[ ] ){
Box b1 = new Box(10, 12, 10);
Box b2 = new Box(12.5);
System.out.println(“Volume of box1"+b1.vol());
System.out.println(“Volume of box2: “ +b2.vol());
}
}
So the second version of the constructor passes a value 12.5 which is assigned to all the three
dimensions width, height and depth.