We
create the objects of the class to call the functions of that particular class.
Sometimes we need to call a function of a class only once in the entire
program. In such cases if we create the object and assign the address of that
object to variable, this leads to unnecessary wastage of the memory. Because
the variable holding the address of the object will occupy some memory and the
object itself occupies some memory. Even though during the entire execution of
the program even though its use is limited.
So
to avoid this unnecessary usage of memory we create the object, call function
and after this we delete the object immediately. This allows for better memory
management.
Consider the
following program.
class DatTypes {
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
Boolean flag;
|
public static
void main(String args[]){
DataTypes dataTypes = new
DataTypes();
System.out.println
(dataTypes.b);
System.out.println
(dataTypes.s);
System.out.println
(dataTypes.i);
System.out.println
(dataTypes.f);
System.out.println
(dataTypes.d);
System.out.println
(dataTypes.c);
System.out.println
(dataTypes.flag);
} }
|
When we compile and execute
the above programme we will get the following output.
b à 0, s-à 0 I à 0, f à 0.0 d à 0.0
c à flag à false
These are the default values
of primitive data types.
NOTE:-
After loading all the non
static elements into the Object, then the JVM initializes all the un
initialized variables with their default values.
è Default
value of char is ‘ ‘(empty space.)
è Character
has to be represented with ‘ ’ (quotes).
è Almost
we can assign only one character to char variable.
Ex: - char c =‘s ‘; x = ‘9’, etc…
Ex: class
LocalVariable
{
byte b;
short s;
public static
void main (String args []) {
LocalVariable variable = new
LocalVariable ();
int j;
System.out.println (j); // here we get an error.
j = 10;
System.out.println (j); // here we do not get any error
//
because already j is initialized to 10.
} }
}
|
In the programme we have
variable j of type integer inside main method
If we compile this programme
we get an error as shown in the comment lines.
This is because of the
following reason.
Reason:-Here j is a local variable JVM will not
initialize it to its default value since it is not an instance variable.
NOTE:-UN
initialized local variable cannot be used in java.
So if we want to use a
variable as a local variable in the programme first it must be initialized to some value before using
it. Or operating on it. In the
programme.
è When
we assign any non decimal number to a variable
the JVM accepts it as an integer.(32 bit)
è Any
number with a decimal point would be accepted by the JVM as double (64 bits)
Type Casting:-
Type Castings are 2 types in java.
1. Implicit Typecasting
2. Explicit Typecasting
è Implicit Type casting is storing a smaller value into its
equivalent bigger location.
è Explicit Type casting is storing a bigger value into its equivalent
smaller location.
Note:
- the above two definitions are not always true there are some violations.
Consider
the following programme.
Ex:
class Typecasting
{
public static
void main (String args []) {
int I = 6;
float f = 7;
System.out.println
(f); // f = 7.0
Float k
= 7.0;
System.out.println
(k); //
here we get a compilation error.
Float k =
(Float) 7.0; // Explicit Type casting.
long l =
8; // implicit type casting.
S.o.p
(l);
int x =
l;
Byte b =
6;
} }
|
//
here we do not get any error infact implicit type casting takes place.
//This
type of type casting (implicit type casting) takes place by only some versions
of JVM.
b = x; // error
b =
(byte) x; // in these cases explicit
type casting is highly recommended.
Float
f = 7.2f; // this is another way of
type casting.
Char
ch = (char) x;
S.o.p
(ch);
Char
ch1 = ‘&’;
S.o.p
(ch1);
Int
z = (int) ch; // this is also possible.
S.o.p
(z); }
Methods with parameters:-
We
can have java methods with parameters, but to call that function we have to
pass values to those parameters.
Parameters
will act as a local variable of that function.
class Arguments
{
void
argFun (int a) {
a
= a+100;
System.out.println
(a);}
public static void main (String args []) {
Arguments
arg=new Arguments ();
arg.argFun
(5);
} }
|
Output:-
105.
|
Program:-
class
Arguments {
int
result;
void argFunction (int a)
{
result =a+100;
System.out.println
(result); }
|
void argFunction (int a,
int b, int c) {
result = a + b + c + 100;
System.out.println
(result); }
public static
void main (string args []) {
Arguments ar=new Arguments
();
Ar.argFunction (5, 6, 7); }
}
|
Note:-
When we define a function
with parameter or with number of parameters while calling we should call that
function by passing the arguments to that function.
We can define methods with
object parameters also. So, to call those functions we have to pass the
reference of those objects.
Program:-
class A {
Int I, j;
void FunA () {
System.out.println (i);
System.out.println (j);
} }
class callByReference {
void funRef (A a) {
System.out.println
(a.i+a.j);
System.out.println“Call
by reference function”);
}
|
public static
void main (String args []) {
System.out.println
(“main method”);
A a1=new A
();
CallByReference ref=new calByReference ();
ref.functionRef
(a1);
} }
|
OutPut :
main method
0
Call by reference function
|
Note:-
We
can have methods with parameters of class or parameters with primitive
datatypes.
We
can have object references as instance variables of a class.
E.g.:-
class B {
Int i=0;
Int j=0;
A a = new A
();
void functionB () {
System.out.println (i);
System.out.println (j);
}
|
public static
void main (String args []) {
B b = new B ();
System.out.println (b.i);
System.out.println (b.j);
System.out.println
(b.a); //
address of a object
System.out.println
(b.a.i);
b.a.funA (); //calling function A which
is in A class
} }
|
]
Explanation:-
§ B
class contains 3 non-static variables I, j, a and one non-static function is
funB().
§ ‘a’
is again referring to object of class A. where class A contains 2 non-static
variables I,j and one non-static function funA().
§ We
can access non-static contents of class B using B class object. we can access
non-static contents of class A also by using B class object. Because, ’a’ is
instance variable of class B.
§ E.g.:- b.a.i
,Will give us ‘I’ value inside A class
§ E.g.:- b.a.funA ()
will give the output of funA () which is there inside class A.
System.out.println () is used to print the content inside the
console. that has a logic as shown in below.
class PrintWriter
{
void println() {
//logic to
print the string content inside console. }
}
class System {
PrintWriter out = new PrintWriter ();
public static
void main (String[] args) {
System system=new System
();
System.out.println
(); } }
|
We should not or we can’t
have instance variable of one class that is referring to the same class object.
Note:-
If we create object of that
class, this object creation will go into infinite loop which will kill the
memory.
Program:-
class C {
int k;
C c = new
C();
void funC () {
System.out.println (“ I am
inside the function C of class C ” );
}
public static
void main (String arg []) {
C c =new C ();
} }
|
Explanation:-
C c = new C
();
This object creation will
creates the infinite loop. Because, C contains ‘c’ which is referring to the
same class object. This is not recommended to used.
Program:-
class TaxCalluculator
{
void calluculatorTax
(float income, int rate) {
float
tax = ( income * rate ) / 100;
System.out.println (“tax
is” + tax + ”rupees”); }
public static
void main (String args [])
{
TaxCalluculator cal = new TaxCalluculator ();
cal.calluculateTax
(200000.00f, 10);
} }
|
Output:- Tax is 20000.00rupees
Note:-
We can have methods with
return data type for such methods we have to keep a return statement at the end
of the method and return a value of type that is the method is expecting.
Program:-
class Taxcalluculator {
float calluculateTax
(float income, int rate) {
float tax = (
income * rate ) / 100;
return tax; }
public static
void main (String args []) {
Taxcalluculator cal=new
Taxcalluculate ();
System.out.println
(cal.calluculateTax ((float) (200000.00),10));
float
resultTax=cal.calluculateTax ((float) (20000.00));
System.out.println (“final
tax is”+resultTax+”rupees”);
} }
|
Output: - 20000.00rupees
Note:-
float calluculateTax (float
income, int rate) ----- function declaration
Body of function ----- function definition.
Function declaration having
return datatype , name of a method and parameters.
Program:-
class Addition {
int sum(int I, int j) {
int result=a+b;
return result; }
public static
void main (String args []) {
Addition add = new Addition ();
int c=add.sum (5, 6);
System.out.println (sum
is”+c);
}
}
|
In the class Addition int
sum (int a, int b) is a declaration of a function. It contains return data
types ‘int’ and it is accepting 2’int’ parameters. In the function definition
we have to return a value of type integer.
While calling this method we
have to handle the return value. That means we have to accept value returned by
the sum method into a variable of returned data type. Int c=add.sum (5, 6);
Note:-
There will be no method
& no return value that means we should not declare a method without return
data type. Atleast we have to keep void keyword to declare a method, if method
is not returning anything.
Default value of any object
defined as instance variable of a class is “null”.
On top of “null” object we
cannot call methods or variables, because that will give you
“NullPointerException”.
class A {
Int a;
void functionA () {
System.out.println
(“function A of class A”); } }
class Obj {
Int k;
A a1;
void funObj () {
System.out.println
(“funObj of class obj”);
System.out.println (a1);
a1.functionA (); } //null pointer exception
public static void main
(string args []) {
Obj o=new obj ();
o.funObj (); } }
|
“ static” “ keyword:-
If
we use a static keyword to declare variable/method then that is known as static
variable/method.Static loading will takes place for static contents. Previously
we have learned that, when we create a new object JVM will allocate a memory
for non-static contents of a class.This is not 100% true, but the underling
concept is as following
Program:-
class A {
int a;
static int b;
int sum(int x, int
y) {
int retValue =
0;
ret Value = x+y;
return
retValue;
}
static int subtract
(int r, int s) {
int dif = r-s;
return dif;
}
public static void
main (String args[]) {
int difference =
subtract(10,2);
System.out.println
(difference);
b = 100;
System.out.println
(b);
A obj = new A();
obj.a = 120;
System.out.println
(obj.a);
int res =
obj.sum(22,32);
System.out.println
(res);
A obj2 = new A();
} }
|
·
When
we execute any .class all the “static” contents will be loaded into specific
memory known as content of a class among all static
contents JVM will search for main() and start its execution from there.
·
Context
of the class exist as long as the main method is under the execution. When the
main () method comes to closing brace ( } ) JVM will delete the context of a
class from the RAM.
·
When
new operator encountered by the JVM for “non-static” contents of a class which
is known as instance of a class. There can be any number of instances, but the
context of a class is only one.
Note:- We can access static methods/contents
directly without creating the instance of a class.
Program:-
static StaticCls {
int i=10;
static int j;
static void fun1 () {
staticCls obj = new StaticCls();
System.out.println
(obj.i);
j = 1012;
System.out.println
(j); }
public
static void main (String [] args) {
System.out.println
(“main method”);
fun1
(); } }
|
Explanation:-
fun1
() is a static function; main is also a static function. When we try to access
‘I’ inside fun () without creating instance of a class, then that will give us
a compilation error (because non-static contents cannot be accessed by the
static methods without creating the instance of a class).
class StaticCls {
int i =20 ;
static int j;
static void fun1 () {
staticCls obj = new
StaticCls ();
System.out.println
(obj.i);
j = 1012;
System.out.println
(j); }
public static
void main (String [] args) {
fun1 ();
staticCls obj1 = new
StaticCls ();
System.out.println
(obj1.j);
obj1.j = 10;
obj1.i = 200;
System.out.println
(obj1.i);
StaticCls obj2 = new StaticCls();
System.out.println
(obj2.j);
System.out.println
(obj2.i);
StaticCls obj3 = new StaticCls();
System.out.println
(obj3.j);
System.out.println
(obj3.i);
StaticCls obj4 = new StaticCls();
System.out.println
(obj4.j);
System.out.println
(obj4.i);
} }
|
Difference b/w context of a class and instance of
a class:-
·
We
can create any number of objects for a particular .class file, but there will
be only context for one .class file. Which is common to all the instances of a
class.
·
Garbage
collection of objects will not have any effect on context of a class. Context
of a class will be deleted only after the execution of main ().
·
Instance
of an object is created and it will be deleted, if we will not use it.
·
When
we try to execute a .class file JVM loads all the contexts (static contents)
into context of a file.
Note:-
If we want to execute any function () more
than once then we will declare or define the function () as static function ()
(because if we declare a non-static function, when we call it by creating an
object the byte code of a function will be loaded into the RAM, JVM will
execute it then JVM will be delete the bytecode loaded into the RAM.
·
If
we want to execute the same function for 10 times (more than once), then JVM
will load that function execute it and delete it 10 times.
·
Which
will become a Burdon to JVM.so in such cases if we define a function as static
function, then the function bytecode will be loaded into the RAM, when the
context of a class is created.
·
This
will be available as long as the main () is under execution.
Program:-
class Employee {
static int sal;
int yearsOfExp;
static int income (int paramSal) {
int annualIncome = 12
* paramSal ;
return annualIncome;
} }
class Main {
public
static void main (String [] args) {
//System.out.println
(sal);
Employee emp = new
Employee ();
System.out.println (emp.yearsOfExp);
System.out.println
(emp.sal);
//
another way of accessing static contents.
Employee.sal =
Employee.sal +1000;
System.out.println
(Employee.sal);
System.out.println
(emp.sal);
//
another way of calling static functions.
int anualSal = Employee.
income (2000);
System.out.println
(anualSal);
int salAnual = emp.income(3000);
System.out.println
(salAnual); } }
|
Explanation:-
Employee.sal=Employee.sal+100;
·
When
this statement will executed, then context for Employee. Class file will be
created (for static contents).
·
So
we can access the static contents using context of a class. Now here the
Employee can be treated as a context .
int
AnnualSal=Employee.income (2000);
·
When
this statement is executed JVM will start executing income (), which is already
loaded into context.
·
We
can access the contents of a context (static contents) using object reference
also.
int
salAnnual=emp.income (3000);
Note:- we can’t use static keyword to
declare a class
static class A {
public static void main (String args []) {
System.out.println (“hello”);
}
}
|
No comments:
Post a Comment