42
Tutorial on Java Page  | 1 What is data abstraction? Object Oriented Programming has a special feature called Data Abstraction. Data abstraction means to, providing only essential features and to hide its background details. That is to represent the needed information in program without presenting the details. While defining a class, both member data and member functions are described. However while using an object the built in data types and the members in the class are ignored. This is known as data abstraction. Features of Object Oriented Programming The main features of object oriented programming are data abstraction, encapsulation, inheritance and polymorphism. They are described below: Abstraction:  Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Encapsulation:  In general, encapsulation is the inclusion of one thing within another thing so that the included thing is not visible. Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data. Thus the data and functions can be kept safely from outside interference and misuse. Data encapsulation means data hiding also. Inheritance: One of the most useful aspects of object-oriented programming is code reusability.  As the name suggests Inheritance is the process of forming a new class from an existing class. The existing class called as base class and the new class formed from the base class is called as derived class. As a result the properties of the base class are not re-written in the child class. This is a very important concept of object-oriented programming since this feature helps to reduce the code size. Inheritance defines relationship among classes in an object-oriented language. Polymorphism: The ability to use an operator or function in different ways is called polymorphism. In other words giving different meaning or functions to the operators or functions is called polymorphism. Poly means many. In OOP we can define more than one functions by the same name is a class or in base class and child class. Though the name of the functions is same but they can perform different tasks. This feature is called polymorphism. Why Is Java Called Pure Object Oriented Programming Language? Java is a programming language that uses Object in each of its programs. In each java program we have to create classes and in the main function of java we have to create objects of the classes. You can write a C++ program without creating a class but we have to create class and objects in each java program. Moreover, all concepts of object oriented programming language, like inheritance, polymorphism, and encapsulation are supported by java. That ‘s why java is called "purely" object oriented programming language. What is Byte Code?  After compilation of a java program, a .class   file is created which is written in bytecode. Bytecode is an intermediate code which is produced by the Java compiler by compiling that source code. This byte code is a machine independent code. It is not completely a compiled code but it is an intermediate code which is later interpreted and executed by JVM. What is JVM? JVM is a platform-independent execution environment that converts Java bytecode into machine language and executes it. Java was designed to write programs that can be executed on any

Java Notes for ECE

Embed Size (px)

Citation preview

Page 1: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 1/42

T u t o r i a l o n J a v a P a g e  | 1

What is data abstraction?Object Oriented Programming has a special feature called Data Abstraction. Data abstraction

means to, providing only essential features and to hide its background details. That is to represent

the needed information in program without presenting the details. While defining a class, both

member data and member functions are described. However while using an object the built in data

types and the members in the class are ignored. This is known as data abstraction.Features of Object Oriented ProgrammingThe main features of object oriented programming are data abstraction, encapsulation,

inheritance and polymorphism. They are described below:

Abstraction: Data abstraction refers to, providing only essential information to the outside world

and hiding their background details, i.e., to represent the needed information in program without

presenting the details.

Encapsulation: In general, encapsulation is the inclusion of one thing within another thing so that

the included thing is not visible. Encapsulation is an Object Oriented Programming concept that

binds together the data and functions that manipulate the data. Thus the data and functions canbe kept safely from outside interference and misuse. Data encapsulation means data hiding also.

Inheritance: One of the most useful aspects of object-oriented programming is code reusability.

 As the name suggests Inheritance is the process of forming a new class from an existing class.

The existing class called as base class and the new class formed from the base class is called as

derived class. As a result the properties of the base class are not re-written in the child class. This

is a very important concept of object-oriented programming since this feature helps to reduce the

code size. Inheritance defines relationship among classes in an object-oriented language.

Polymorphism: The ability to use an operator or function in different ways is called

polymorphism. In other words giving different meaning or functions to the operators or functions is

called polymorphism. Poly means many. In OOP we can define more than one functions by thesame name is a class or in base class and child class. Though the name of the functions is same

but they can perform different tasks. This feature is called polymorphism.

Why Is Java Called Pure Object Oriented Programming Language?Java is a programming language that uses Object in each of its programs. In each java program

we have to create classes and in the main function of java we have to create objects of the

classes. You can write a C++ program without creating a class but we have to create class and

objects in each java program. Moreover, all concepts of object oriented programming language,

like inheritance, polymorphism, and encapsulation are supported by java. That‘s why java is called"purely" object oriented programming language.

What is Byte Code? After compilation of a java program, a .class  file is created which is written in bytecode. Bytecode

is an intermediate code which is produced by the Java compiler by compiling that source code.

This byte code is a machine independent code. It is not completely a compiled code but it is an

intermediate code which is later interpreted and executed by JVM.

What is JVM?JVM is a platform-independent execution environment that converts Java bytecode into machine

language and executes it. Java was designed to write programs that can be executed on any

Page 2: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 2/42

T u t o r i a l o n J a v a P a g e  | 2

platform without compiling for each separate platform. A Java virtual machine makes it possible

because it is aware of the particular platform and translates the byte code into machine code

according to that platform. Once a Java virtual machine has been implemented for a given

platform, any Java program can run on that platform.

Why java is called platform independent language?

Java is a platform independent programming language. It means that, after compilation, the same java program can be executed on any platform or operating system without any change. The javacompiler compiles a java program and produces a .class  file which is written in byte code. Bytecode is not executable code. The byte code is interpreted and executed by the java runtimesystem which is called Java Virtual Machine (JVM). The .class  file (written in byte code) can beinterpreted and executed by any computer under any operating system, only if JVM is installedthere. That is once compiled; the .class  file can be executed in any platform. Hence java is calleda platform independent language.

 W HAT IS A CLASS? 

 A class is a blueprint or skeleton of a real entity. A class can be defined as a template /blue printthat describe the behaviors/states of object of that type. Technically speaking, defining a class

means to define a new data type. That is a class is a user defined data type. A class is virtual in

nature.

While defining a class we have to define some variables and some methods within the class.

Those variables and methods are called the members of the class.

 W HAT IS AN OBJECT?

The real implementation of a class is called an object. An object is the real thing which possesses

all the features declared in a class. All the objects of a class are identical. In fact an object is a

class type variable. The term ―object‖, is also known as instance of a class.

 After compilation of a java program, a .class file is created. A java program can have several user

defined classes and individual .class file is created for each of the classes. Let a java program

contains four user defined classes named class A, class B, class C and class D. after compilation

of the program four .class file named, A.class, B.class, C.class, D.class will be created. All the

classes can have their own main () method also.

COMPILATION AND EXECUTION OF A JAVA PROGRAM  

In java, both compiler and interpreter are used. At first the program is compiled and then the .class

file is interpreted by an interpreter.

Compiler javac.exe

Interpreter java.exe

1) Write a Java in Notepad and save it with the extension .java2) Compile he program using the java compiler javac as below:

>javac <file name.java>

Page 3: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 3/42

T u t o r i a l o n J a v a P a g e  | 3

That is if the name of the file is Asansol.java then it has to be compiled as

>javac Asansol.java

3) After successful compilation .class file will be created. The program will be executed usingthe interpreter of java.exe as below:>java <name of the .class file containing the main () method>

P ACKAGE  A Package can be defined as a collection of related classes and interfaces for better organization.It is also useful to avoid naming conflict and to control access to various classes and interfaces.Some of the predefined packages in java are given below:

 java.lang java.io java.net java.util java.applet java.awt

 java.awt.event java.sql etc.

If we want to use any particular class or interface from a package, then we have to include that

package to our program using the impor t  statement. In C language, if we want to use a function

then we have to include the entire header file. But in Java either we can import a particular class

from a package or we can import the entire package.

1) To import a particular class from a package, the syntax is: impo rt packagename

.classname;  

For example; if we want to import the Button class from the java.awt package, then we have

to write: imp ort java.awt.Button;  2) To import an entire package, the syntax is: imp ort packagenam e.*;  

For example; if we want to import the java.awt package, then we have to write: import

 java.aw t.* ;

 A DVANTAGE OF P ACKAGE

  Package is used to categorize the classes and interfaces so that they can be easily

maintained.

  Package provides access protection.

  Package removes naming collision.

The java.lang package is automatically imported in all java programs

FILE CREATION R ULES 

  We can define several classes in a java program and those user-defined classes can be

organized in a user defined package. If the user-defined classes are stored in a package,

then all the user-defined classes of a java program must be stored in a single package.

That is the user defined classes of a java program cannot be stored in different packages. If

the use defined classes are stored in a package, then the very first statement of the

program must be,

package package-name;

If we don‘t want to store the user defined classes of a java program in a package, then the

package statement is not required. So, the package keyword is optional in a java program

Page 4: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 4/42

T u t o r i a l o n J a v a P a g e  | 4

and if it is used then it can be used only once and it must be the first statement of the

program.

  As already stated, the java.lang package is automatically imported in all java programs. If

any other package is required then that package is included using the import statement

which must appear just after the package statement (if the package statement exists at all).

If the package statement does not appear in a program then the import statement will bethe first statement of the program. That is import statement is also optional as it may not be

required to import any other package other than java.lang. But one can import as many

packages as needed and they can be imported in any order.

  After the package and the import statement, we have to define the classes required.

That is the basic skeleton of a java program is as below:

package - Optional

import - Optional

import

--------------

import

class A

{

}

class B

{

}

FILE N AMING R ULES:

 A java program can have several user defined classes, but only one of them can be declared as

public. I f a class is declared as public in a program then the name of the file must be same as the

name of that public class. That is if a program contains four classes named, class A, class B, class

C and class D, and class B is declared as public, then the name of the file must be B.java,

otherwise it will be a compilation error.

If none of the classes in a program is public then the program can have any name.

R ULES FOR IDENTIFIER :

  An identifier must start with a letter, a currency character ($), or the underscore (_).

Identifiers cannot start with a number.  After the first character, identifiers can contain any combination of letters, currency

characters ($), underscore (_), or numbers.  There is no limit to the number of characters in an identifier.  A Java keyword cannot be used as an identifier.  Identifiers in Java are case-sensitive; rate and RATE are two different identifiers.

 A CCESS SPECIFIERS IN J  AVA  

 Access Specifiers (also known as Visibility Specifiers) control access to classes, variables andmethods in Java. These Specifiers determine whether a variable or method in a class, can be

used or invoked by another method in another class or sub-class. Access Specifiers can be usedto restrict access. Access Specifiers are an integral part of object-oriented programming. The fouraccess levels are:

  Visible to the package. the default. No modifiers are needed.

Page 5: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 5/42

T u t o r i a l o n J a v a P a g e  | 5

  Visible to the class only (private).  Visible to the all (public).  Visible to the package and all subclasses (protected).

K EYWORDS IN J  AVA  

There are some words that cannot be used as object or variable names in a Java program. Thesewords are known as ―reserved‖  words or ―keywords‖.  They are called keywords as they are

already defined by the Java programming language.

Here is a list of keywords in the Java programming language. We cannot use any of the followingas identifiers in our programs. The keywords cons t  and goto  are reserved, even though they arenot currently used. t rue , fa lse , and nul l  might seem like keywords, but they are actually literals.Here is a complete list of the keywords in java:

abstract boolean break byte case catchchar class const continue default dodouble else extends final finally floatFor goto If implements import instanceofInt interface long native new packageprivate protected public return short staticstrictfp super switch synchronized this throwthrows transient try void volatile while

D ATA TYPES IN J  AVA  

There are eight primitive data types supported by Java. Primitive data types are predefined by thelanguage and named by a keyword.

Data Type Size(in Byte) Default Value

Byte 1 0Short 2 0Int 4 0Long 8 0Float 4 0.0Double 8 0.0Char 2 nullboolean 1 false

Instance variables:

Instance variables are variables within the objects. Every time we create an object from a class, anew copy of these instance variables is created for this object. So each object has its own copy ofinstance variables which exist as long as the object exists.

Default Access Modifier - No keyword:

If a variable or method is declared without any access specifier then it is said to have defaultaccess. A variable or method declared without any access control modifier is available to anyother class in the same package. That is if we do not specify any access specifier, then such aclass, method, or variable will be accessible from inside the same package to which the class,method, or variable belongs, but not from outside this package. 

Private Access Modifier - private:It is the most restricted access specifier. Methods, Variables and Constructors that are declaredprivate can only be accessed within the declared class itself. Private access modifier is the mostrestrictive access level. Private methods and variables are not visible within subclasses and arenot inherited by subclasses. So, the private access specifier is opposite to the public access

Page 6: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 6/42

T u t o r i a l o n J a v a P a g e  | 6

specifier. Classes and interfaces canno t be private . Using the private modifier an objectencapsulates data and hides data from the outside world.

Public Access Modifier - public:

 A class, method, constructor, interface etc. declared as public can be accessed from any otherclasses. Therefore variables, methods, blocks declared inside a public class can be accessed

from any other class belonging to the Java Universe.However if the public class we are trying to access is in a different package then we have to importthat public class. A public member has maximum accessibility and minimum security.

Protected Access Modifier - protected:

 A member declared as protected in a class can be accessed only byi) Any classes within the same package of the protected members' class and byii) The subclasses even if the subclass is in other package.

The protected access mo dif ier cannot be appl ied to c lass and interfaces . Methods, variablescan be declared protected, however methods and fields in an interface cannot be declared

protected.The following table summarizes the given concept:

Access Specifier default private protected public

 Accessible inside the class Yes Yes Yes Yes Accessible within the subclass inside thesame package

Yes NO Yes Yes

 Accessible outside the package NO NO NO Yes Accessible within the subclass outside thepackage

NO NO Yes Yes

In short the accessibility can be described as below:

private Within the same Class onlydefault Within all the classes of the same package Within all the classes of the

same package as well as within theprotected sub-class also even if the subclass is in other packagepublic Everywhere

So in terms of accessibility, publ ic>protected>default>private .But in terms of restriction, private>default>protected>publ ic  

DECLARING CLASSES AND OBJECTS: 

Let us look at the way of creation of a class and an object. Say we want to create a class named,Room as below:class Room{

int I , b, h;void volume (){

int v;v=l*b*h;System.out.println (―The volume is ―+v); 

}}

Page 7: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 7/42

T u t o r i a l o n J a v a P a g e  | 7

Here Room is a class (that is a data type) which has four members ; three variables and amethod. After declaring the class we can create objects from that class as below:

Room r ; Here r  is a Room type variable which can store the address (reference) of anobject of Room class. As it can store reference, hence it is called a reference

variable .

r=new Room ()  this statement creates the real object. The new keyword in java is used tocreate a new instance of a class (that is an object) or an array. When the newkeyword is used:

  A new instance of the given class is created  Memory is allocated for it  a constructor is called

I NSTANCE V  ARIABLE 

When a number of objects are created from a class, all of them have their own distinct

copies of instance variables. That is an instance variable is a variable which has its own individualcopy in each objects of that class.  Instance variables are declared in a class, but outside a method, constructor or any block.  When a space is allocated for an object in the heap, memory space for each instance

variable is allocated.  Instance variables are created when an object is created with the use of the keyword ‗new ‘ 

and destroyed when the object is destroyed.  Access modifiers can be given for instance variables.  The instance variables are visible for all methods, constructors and block in the class.

Normally, it is recommended to make these variables private.  Instance variables are initialized with default values.

Instance variables can be accessed directly by calling the variable name inside the class. Howeverwithin different class (when instance variables are given accessibility) should be called using thefully qualified name, i.e. ObjectName. VariableName .

In the above example, if several objects of the Room class are created, then all of them will havethe variables l , b  and h . Here those variables are instance variable. That is memory space for aninstance variable is allocated whenever an object is created.Hence the pictorial representation of the statement r=new Room ()  will be as below:

CONSTRUCTOR :

 A constructor is a method which is automatically called whenever an object of a class is created. Aconstructor has the following features:

  It is automatically called when an object is created.  It initializes the instance variables of an object as soon as the object is created.  The name of the constructor must be same as the name of the class.

Page 8: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 8/42

T u t o r i a l o n J a v a P a g e  | 8

  As long as no constructor is defined in a class, JVM will supply a default constructor whichinitializes the instance variables with the default values mentioned above. As soon as aconstructor is defined, supply of the default constructor is stopped.

 A constructor can be parameterized or without any parameter. A constructor without anyparameter is called an ―EMPTY CONSTRUCTOR‖. Be careful of the fact that empty constructorand default constructor are not the same. A default constructor is supplied by the JVM but anempty constructor is defined in a class. Even if an empty constructor is defined in a class, JVM willnot supply the default constructor.

Look at the following program to find out the sum of two numbers:Sumation.javaclass A{

int x, y; A (int a, int b){

x=a;y=b;

}void sum(){

int s;s=x + y;System.out.println ("The sum is "+s);

}}class B{

public static void main (String s[]){

 A obj=new A (10, 20);obj. sum();

}}

Here the class A contains two instance variables x  and y  and a method sum () . To initialize theinstances variables, a constructor with two parameters has been defined. When an object iscreated, the constructor is called. It initializes the instance variables x and y. the sum method iscalled with that object and it finds out the sum of those two variables. The program is compiled as

below:>javac Summ ation. java

But it is executed using the class B, as class B contains the main () method.

>java B

STATIC K EYWORD

In java we can declare a variable either in a class or in a method. A variable declared in a methodis called a local variable and it is accessible within that method only. Variables declared in a classcan either be an instance variable or a static variable

Page 9: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 9/42

T u t o r i a l o n J a v a P a g e  | 9

Static is a very important keyword and can be applied to  Variable, declared in a class  Method  Inner class

STATIC V  ARIABLE 

Static variables also known as Class variables are declared with the static keyword in a class, but

outside a method, constructor or a block. There will only be one copy of each static variable foreach class, irrespective of how many objects are created from it. Memory space for an instancevariable is allocated whenever an object of that class is created and each object will have its owninstance variable. Moreover the instance variables always reside within an object and instancevariables can‘t exist unless and until an object is created. On contrary, a static variable can existwithout the existence of an object, even a static variable can exist before creation of any object. Astatic variable is not a member of an object of a class and it does not reside within an object of theclass. Let us take an example:

class ABC{

int x, y; //Instance variablestatic int p; //Static variable}Now create some object of that class. ABC obj1=new ABC (); ABC obj2=new ABC ();Here we have created two objects of the class. The memory representation is like below:

From the diagram it is clear that there are individual copies of each instance variable for eachobject, but there will be only one copy for a static variable for the entire class.

Whenever a .class file is loaded by the ClassLoader class, memory space for the static variablesis allocated. A static variable is automatically initialized with the default value according to its datatype.

USING A STATIC VARIABLE IN THE CLASS IN WHICH IT IS DECLARED: 

The following example shows how to use a static variable in a class in which it has been declared:class A

{int x, y;static int p;

Page 10: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 10/42

T u t o r i a l o n J a v a P a g e  | 10

void sum(){

int s=x+y;System.out.println("The sum is "+s);

}public static void main(String s[]){

p=18; A obj=new A();obj. x=4;obj. y=9;obj. sum();System.out.println("p= "+p);System.out.println("x= "+obj. x);

}}

In the given example, p  is a static variable but x  and y  is instance variables. The static variable p  

can be used in the same class just using the name of the variable, but instance variables must beused with the object name only.

DECLARING A STATIC VARIABLE IN A CLASS AND USING IN ANOTHER CLASS: 

class A{

int x, y;static int p;void sum(){

int s=x+y;

System.out.println("The sum is "+s);}

}class B{

public static void main(String s[]){

 A.p=18; A obj=new A();obj. x=4;obj. y=9;

obj. sum();System.out.println("p= "+A. p);System.out.println("x= "+obj. x);

}}

 A static variable declared in a class can be used in another class using the name of its declaringclass. Here the static variable p of class A is used in class B as A. p. But instance variables arealways used with an object name.

Static Method

Normally you can't call a method of a class without creating an object of that class. By declaring amethod as static, we can call it without creating an object because it becomes a class method (i.e.a method that belongs to a class rather than an object). A static method has the following features:

 A static variable declared in aclass can be used by the name ofthe variable in the same class.

Instance variables must be usedwith the object.

 A static variable of a class canbe used in another class usingthe name of the declaringclass.

Instance variables must beused with the object.

Page 11: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 11/42

T u t o r i a l o n J a v a P a g e  | 11

  A static method belongs to the class rather than object of a class.

  A static method can be invoked without creating an object of a class.

  Static method can access static data member and can change the value of it.

  A static method cannot use non-static variable or can‘t call any non-static method.

  The ―this‖ and ―super ‖ keywords can‘t be used in a static method.

Using a static method in the class in which it is declared:class Static1{

int x;static int p;static void show(){

System.out.println(p);//x=5; compilation error, as static method can‘t use instance variable.

}void abc(){

System.out.println("x= "+x);System.out.println("p= "+p);

}static public void main(String s[]){

p=10;show();Static1 s1=new Static1();Static1 s2=new Static1();

s1.x=100;s2.x=50;s1.abc();s2.abc();System.out.println(s1.x);System.out.println(s1.p);System.out.println(s2.p);s1.p=s2.p+p;System.out.println("Now p= "+s1.p);

}}

main () of a java program is public and static-Explain.When a class member is declared as public, then that member can be accessed by code outsidethe class in which it is declared. In this case, main must be declared as public, since it must becalled by code outside of its class when the program is started. A static method can be called without an object. The main () is the starting point of execution of a java program. That is, main () is always called without an object. Hence main () must be declaredas static.

Method Overloading

Method overloading is a very important concept in Java. It allows Java programmer to declaremore than one method with same name but different behavior. Method overloading is based onpolymorphism. Method overloading is resolved using static binding in Java at compile time.

 A non-static method can use both

static and non-static variables.

 A static method called in thecontaining class using the methodname only

 A non-static method must be calledwith the object of that class.

 As there is only one copy of a staticvariable for the entire class, so s1.p ,s2.p   and p   refer to the samevariable.

Page 12: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 12/42

T u t o r i a l o n J a v a P a g e  | 12

In object oriented programming, it is possible to define more than one method with the same namein a class. This feature is known as method overloading and those methods are called overloadedmethods.The return type of the overloaded methods may be same or may not be same. In fact the returntype of the methods has no role to play in method overloading. But either-

i) Number of parameters or

ii) The data type of the parameters oriii) The sequence of the parameters

Of the overloaded methods must be different. It means that the overloaded methods canperform similar type of operations on different data type.The following example demonstrates the concept of method overloading.class Addition{

void sum(int x, int y){

int s=x+y;System.out.println ("The sum is "+s);

}void sum(int x, double y){

double s=x+y;System.out.println ("The sum is "+s);

}void sum(double x, int y){

double s=x+y;System.out.println ("The sum is "+s);

}int sum(int x, int y, int z){

int s=x+y+z;return s;

}

}class OverloadMethod{

public static void main(String s[])

{ int p; Addition a1=new Addition ();p=a1. sum (10,20,30); (1)System.out.println ("The sum is "+p);a1.sum (12.5, 18); (2)a1.sum (16, 39); (3)a1.sum (10, 2.5); (4)

}}The above example contains four methods called sum (). They are overloaded methods. Among

them return type of three of the methods is void and the return type of the fourth one is int.(1) The sum () method with three integer parameters has been called.

(2) The sum () method with one double and one integer parameter has been called.

Page 13: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 13/42

T u t o r i a l o n J a v a P a g e  | 13

(3) The sum () method with two integer parameters has been called.

(4) The sum () method with one integer and one double type parameter has been called.

The “this” keyword

The ―this‖  keyword is used for several purposes in java. There can be a lot of usage of thiskeyword. In java, this is a reference variable that refers to the current object. Within an instance

method or a constructor, this is a reference to the current object — the object whose method orconstructor is being called. You can refer to any member of the current object from within aninstance method or a constructor by using this.

Usage of this keyword

Here is given the 6 usage of this keyword.

1. this keyword can be used to refer current class instance variable.

2. this () can be used to invoke current class constructor.

3. this keyword can be used to invoke current class method (implicitly)

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.6. this keyword can also be used to return the current class instance.

  The “this”  keyword can be used to refer to the instance variable of thecurrent class 

in a class, the name of a parameter of a method may be same as the name of an instance variableof that class. Then within the method, there will be an ambiguity between the instance variable andthe local variable, i.e. the parameter of the method. This ambiguity can be resolved using the ―this‖ keyword. The ―this‖ keyword will refer to the instance variable of the class. Look at the followingexample:

class ThisDemo{

int x, y;ThisDemo (int x, int z){

this. x=x;y=z;

}}Here the constructor has a parameter x and the class has an instance variable x. so within theconstructor this.x   refers to the instance variable x   and x   refers to the local variable x . in this

fashion ―this‖  keyword can resolve the ambiguity. If local variables (formal arguments) andinstance variables are different, there is no need to use this keyword.

 “this()” can be used to invoked current class constructor

If a class has several constructors, then “this ()”  can call a constructor of the class in anotherconstructor of the same class. Only “this ()”  will call the empty constructor of the same classwhereas “this  (parameters  )”   will call a parameterized constructor of the same class. Thefollowing example demonstrates it.class Student{

String name, add;int age, roll;Student (String s1, String s2){

Page 14: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 14/42

T u t o r i a l o n J a v a P a g e  | 14

name=s1;add=s2;

}Student (String p, String q, int a, int r){

this (p, q);

age=a;roll=r;}void show (){

System.out.println ("Name: "+name);System.out.println ("Address: "+add);System.out.println ("Age: "+age);System.out.println ("Roll: "+roll);

}}

class ThisDemo{public static void main (String s[]){

Student s1=new Student("Amit","Asansol");Student s2=new Student("Kunal","Kulti",21,34);s1.show();s2.show();

}}

The “this (p, q)”   used in a constructor of Student class will invoke another constructor of theStudent class which accepts two integer parameters. This approach is better if we have manyconstructors in the class and want to reuse that constructor.

STRING Class

The String  class of java.lang package represents character strings. All string literals in Javaprograms, such as "abc", are treated as instances of String class. Strings are constant; theirvalues cannot be changed after they are created. The String class is final, i.e. we cannot inheritthe String class.

Constructors:

The String class supports several constructors. They are described below:1 To create an empty String, we call the default constructor. For example,

String s = new String ();  will create an object of String class with no characters in it.2 String (char p[ ])  It will create an object of String class and initializes the object with an array

of characters. For example:char p[] = { 'a', 'b', 'c' };String s = new String (p); The constructor initializes the string with ―abc‖. 

3 You can specify a sub-string of a character array to initialize a string using the followingconstructor:

String(char p[ ], int startIndex, int numChars)Here, startIndex specifies the index at which the sub-string begins, and numChars specifies thenumber of characters to use. Here is an example:char p[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

Page 15: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 15/42

T u t o r i a l o n J a v a P a g e  | 15

String s = new String(chars, 2, 3);It creates a string and initializes the string with ―cde‖. 

4 You can construct a String object that contains the same characters as another String objectusing this constructor: String(String strObj);class MakeString{

public static void main(String s[]){

char c[] = {'J', 'a', 'v', 'a'};String s1 = new String(c);String s2 = new String(s1);System.out.println(s1);System.out.println(s2);

}}The output from this program is as follows:Java

Java5 A simple String can be created using a string literal enclosed inside double quotes as shown;String str1 = ―Learning Java‖; 

String PoolString Pool is a pool of Strings stored in heap memory. We know that we can create String objectusing new operator as well as providing values in double quotes. Here is a diagram which clearlyexplains how String Pool is maintained in java heap space and what happens when we usedifferent ways to create Strings.

When we use double quotes to create a String, it first looks for String with same value in the Stringpool, if found it just returns the reference else it creates a new String in the pool and then returns

the reference.However if a string is created using new  operator, then a new string object is created. Here is anexample:Output of the above program is:s1 == s2: trues1 == s3: false

class StringPool{public static void main(String[] s){

String s1 = "Cat";String s2 = "Cat";String s3 = new String ("Cat");

Page 16: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 16/42

T u t o r i a l o n J a v a P a g e  | 16

System.out.println ("s1 == s2 :"+( s1==s2));System.out.println ("s1 == s3 :"+( s1==s3));}}

Methods:1. char charAt(int index)

It returns the character at the specified index.String str ="study to night";System.out.println (str. charAt (2));Output: u

2. boolean equalsIgnoreCase(String s)Determines the equality of two Strings, ignoring their case (upper or lower case doesn't matterswith this function).String str = "java";System.out.println (str. equalsIgnoreCase ("JAVA"));Output: True

3. int length ()The function returns the number of characters in a String.String str=‖This is a String‖; int len=str.length();System.out.println (―Length is ―+len); Output: Length is 16

4. String concat (String str)Concatenates the specified string to the end of this string.class StringDemo1{

public static void main(String s[])

{String s1="Java";String s2=s1.concat ("World");System.out.println (s1);System.out.println (s2);

}}Output:JavaJavaWorld

5. int compareTo(String str)This method compares two Strings and returns an int value. It returns  – 

i) 0, if this string is equal to the string argumentii) a value less than 0, if this string is less than the string argumentiii) a value greater than 0, if this string is greater than the string argument

class StringDemo2{

public static void main(String s[]){

String s1="Dog";String s2="Lion";int N1=s1.compareTo(s2);int N2=s2.compareTo(s1);System.out.println ("N1= "+N1);

Page 17: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 17/42

T u t o r i a l o n J a v a P a g e  | 17

System.out.println ("N2= "+N2);}

}Output:N1= 8N2= -8

6. int compareToIgnoreCase(String str)Compares two strings, ignoring case differences and returns same type of values.

7. String substring(int index)The method returns a new string which is a substring of this string. The substring begins from thegiven index.class StringDemo3{

public static void main(String s[]){

String s1="God is Great";

String s2=s1.substring(4);System.out.println(s2);}

}Output: is Great.

8. String substring(int beginIndex, int endIndex)The method returns a new string that is a substring of this string. The sub-string begins from theindex beginIndex  and ends at (endIndex-1) .class StringDemo4{

public static void main(String s[]){

String s1="God is Great";String s2=s1.substring(4,8);System.out.println(s2);

}}Output: ―is G‖ 

9. String toUpperCase()Converts all of the characters in this String to upper case and returns a new string.

10.String toLowerCase()Converts all of the characters in this String to lower case and returns a new string.

Concatenation of Strings Apart from concat() method, two strings can be appended using the + operator also. For example,String s = "Hello" + "World";System.out.println(s);Output: HelloWorld.Look at the following example:String s = "Java";s = s + "World";

Page 18: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 18/42

T u t o r i a l o n J a v a P a g e  | 18

From the above example, it looks like the string has been modified. But we know that string cannotbe modified and here practically the string has not been modified. Actually here an object ofStringBuffer  class is created. The procedure is given below:

1.   A StringBuffer  object is created2.  The 1st string, i.e., ―Java‖ is copied to the newly created StringBuffer object.3.  The 2nd string, i.e., ―World‖ is appended to the StringBuffer (concatenation)4.  The result is converted to back to a String object.5.  Now the reference variable s  refers to that new String.6.  The old String, that s  previously referenced, is then made null.

toString () Method

The toString() method of Object class is used when we need a string representation of an object.This method can be overridden to get the String representation of an Object. Whenever we wantto concatenate any other primitive data type, or object of other classes with a String object,toString() method is called automatically to change the other object or primitive type into string. For

example:int age = 10;String str = "He is" + age+ "years old.";In above case 10 will be automatically converted into string for concatenation using valueOf() method.

 A number can be converted in to string using the valueOf() method of String class. It can take anyof the primitive data type numbers as an argument and produce a String:int x= 20;Str ing s = Str ing. valueOf(x) ; It converts the value of x  from int to string and stores the stringvalue in s . We can use the toString method of any of the wrapper classes:

String s = Integer. toString(x);

StringBuffer Class An object of String class is immutable, i.e., once created, an object of String class cannot bechanged. That‘s  why the StringBuffer class is introduced. An object of StringBuffer class ismutable, i.e., after creation, the object can be modified. An object of StringBuffer  class can be changed dynamically. StringBuffer class is preferred whenthe string needs several modifications(appending, inserting, deleting, modifying etc.).

Constructor

1 StringBuffer  () Constructs a string buffer with no characters in it and an initialcapacity of 16 characters.

2 StringBuffer  (int capacity) Constructs a string buffer with no characters in it and theinitial capacity of the string buffer is mentioned.

3 StringBuffer  (String str) Constructs an object of StringBuffer class which is initializedwith the contents of the given string and reserves space for 16 more characters.

Methods

capacity()The capacity() function returns the current capacity of the StringBuffer object. The capacity of anempty StringBuffer object is 16. But the capacity of a non-empty StringBuffer object is (number ofcharacters+16). Look at the following example:class StringBuffer1

Page 19: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 19/42

T u t o r i a l o n J a v a P a g e  | 19

{public static void main(String s[]){

StringBuffer sb1=new StringBuffer();StringBuffer sb2=new StringBuffer("HELLO");System.out.println("Capacity is "+sb1.capacity());System.out.println("Capacity is "+sb2.capacity());

}}Output is :Capacity is 16Capacity is 21

ensureCapacity (int x): The method is used to set the capacity to the given value. Look at the following example:class SB{

public static void main(String s[]){StringBuffer sb=new StringBuffer();System.out.println("Capacity is "+sb.capacity());sb.ensureCapacity(40);System.out.println("Now Capacity is "+sb.capacity());

}}Output:Capacity is 16Now Capacity is 40

append()

This method will append the string representation of any type of data to the end of the invokingStringBuffer   object. append() method has several overloaded forms. After appending theparameter with the invoking object, it returns another object of StringBuffer class.class SB{

public static void main(String s[]){

StringBuffer sb=new StringBuffer("Hello");

sb.append("Java");System.out.println("sb= "+sb);int x=123;sb.append(x);System.out.println("sb= "+sb);

}}

insert( )

The method inserts one string into another. It is overloaded to accept all primitive types, plusStrings. It calls String.valueOf ( )  to obtain the string representation of the supplied value. Thisstring is then inserted into the invoking StringBuffer object. These are a few of its forms:StringBuffer insert (int index, String str)

Page 20: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 20/42

T u t o r i a l o n J a v a P a g e  | 20

StringBuffer insert (int index, char ch)class SB4{

public static void main(String s[]){

StringBuffer sb=new StringBuffer("I Indian");sb.insert(2,"am ");System.out.println("Now the string is "+sb);

}}Output: I am Indian

reverse ( )

We can reverse the characters within a StringBuffer object using reverse ( ). This method returnsthe reversed object on which it was called, i.e. the original string is reversed. The prototype isStringBuffer reverse ( )

class SB5{

public static void main (String s[]){

StringBuffer sb=new StringBuffer ("HELLO");System.out.println ("sb "+sb);System.out.println ("The reversed string is "+sb.reverse ());System.out.println ("Now sb= "+sb);

}}

Output:sb=HELLOThe reversed string is OLLEHNow sb= OLLEH

delete ( ) and deleteCharAt ( )

The methods delete ( )  and deleteCharA t ( )   can delete a set of characters or a particularcharacter from a string buffer object.StringBuffer delete (int x, int y)

StringBuffer deleteCharAt (int x)The delete ( )   method deletes a set of characters from the invoking object. It deletes all thecharacters from index x  to the index (y-1) . After deleting the characters, the remaining StringBufferobject is returned.The deleteCharA t ( )   method deletes the character at the index specified by x. It returns theresulting StringBuffer object.

replace( )

It replaces one set of characters with another set of characters inside a StringBuffer object.StringBuffer replace (int x, int y, String str)

The substring from index x  to index (y  –1)  is replaced by the string s tr . After replacement the newStringBuffer object is returned.class SB6

Page 21: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 21/42

T u t o r i a l o n J a v a P a g e  | 21

{public static void main(String s[]){

StringBuffer sb=new StringBuffer("I am Indian");System.out.println("After replacement the string is "+sb.replace(2,4,"are"));

}}Output: After replacement the string is I are Indian.

substring ( )

The substring ( ) method returns a portion of a StringBuffer. It has the following two forms:String substring (int x)String substring (int x, int y)The first form returns the substring that starts at the index x  and runs to the end of the invokingStringBuffer object. The second form returns the substring starting from index x  to index (y  –1 ).class SB7

{ public static void main(String s[]){

StringBuffer sb=new StringBuffer ("I am Indian");System.out.println ("sb.substring (5) = "+sb. substring (5));System.out.println ("sb.substring (5,9)= "+sb.substring(5,9));

}}Output:sb.substring (5) = Indiansb.substring (5, 9) = Indi

Difference between String & StringBuffer

String  StringBuffer  

It implements the interfaces Serializable,CharSequence and Comparable

It implements the interfaces Serializable,CharSequence and Appendable

 An object of String class is immutable, that is,once created a string object cannot bechanged.

 An object of StringBuffer   is mutable i.e. wecan change the value of the object.

 A string object is stored in the Constant String

Pool.

 An object of StringBuffer is stored in the heap.

 After creation, the size of a String object can‘t be changed.

 After creation, the size of a StringBuffer objectcan be changed.

What is an interface? How does it differ from a class?

In Java, an interface is like a class, but we can only declare methods and variables in theinterface. In an interface all the methods are public, static and abstract and all the variables arepublic and static. Thus an interface is a collection of abstract methods. If a class implements aninterface, then it inherits the abstract methods of the interface. We cannot actually implement themethods. Interfaces are a way to achieve polymorphism in Java.

 An interface also declares variables and methods like a class. But there is several differencesbetween them. They are as below:

Class Interface

Page 22: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 22/42

T u t o r i a l o n J a v a P a g e  | 22

The variables may be public and static ormay not.

The variables must be public and static only.

The methods may be public, static andabstract or may not be.

The methods must be public, static andabstract.

We can create an object of a class except anabstract class.

We can never create an object of aninterface.

 A class may have a constructor. An interface can‘t have a constructor. A class can extend a single class. An interface can extend multiple interfaces.

How do you define and access member of an interface? Explain with an example. 5The variables declared in an interface are public, static and final by default, and the methods arepublic and abstract. That is we can only declare a method in an interface but it cannot be defined.If a class implements the interface, then the class has to override the methods of the interface.The variables of the interface can be used with the name of the interface using . (dot) operator. Letus take an example where the members of an interface have been used by a class:interface Address{

String city="Asansol";int pin=713305;void show();

}class Employee implements Address{

String name, dept;Employee (String n, String d){

name=n;dept=d;

}public void show(){

System.out.println ("Name is "+name);System.out.println ("Department is "+dept);System.out.println ("Lives in "+Address.city);System.out.println ("Pin code is "+Address.pin);

}}class InterfaceDemo{

public static void main(String s[]){

Employee e1=new Employee ("Bijay‖, Sales");Employee e2=new Employee ("Ravi","Finance");e1.show ();e2.show ();

}}The interface has two variables. They are public, static and final, though the variables have notbeen declared as public, static and final. The Employee class can use the variables as

Address.city and  Address.pin as they are static. Similarly, the Employee has overridden theshow () method of the interface and after that the method has been called with object of Employeeclass.

They are public static andfinal by default

Page 23: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 23/42

T u t o r i a l o n J a v a P a g e  | 23

InheritanceInheritance means to acquire the properties of an existing class. If class B inherits from class A,then A is called super class and B is called subclass. If class B inherits from class A, then class Bcan use the variables and methods of class A. But a subclass can‘t inherit the following propertiesof the super class:

1. The private members of the super class

2. Constructors of the super class.Whenever an object of the subclass is created, before execution of the subclass constructor, theconstructor of the super class must be executed. If class B inherits from class A and class Cinherits from class B and an object of class C is created, then the constructors are executed in thefollowing order:

i) Constructor of class Aii) Constructor of class B

iii) Constructor of class CIf the super class and the subclass do not have any constructor, then before execution of thedefault constructor of the subclass, the default constructor of the super class is executed.If the super class has an empty constructor, then before execution of the constructor of thesubclass, the empty constructor of the super class is executed.If the super class has some constructors but does not have an empty constructor, then beforeexecution of the subclass constructor, any one of the super class constructors must be calledusing the super keyword.

The “super” keyword

The super keyword is associated with Inheritance. Inheritance is a concept of Object OrientedProgramming where in the sub class inherits characteristics and properties of the super class. Thebase class is also called as super class. The various usage of the super keyword is as below:

i) super is used to refer to the instance variable of the immediate parent class.ii) super() is used to invoke constructor of the immediate parent class.iii) super is used to invoke method of immediate parent class.  “super” is used to refer immediate parent class instance variable.

If the subclass has an instance variable with the same name as an instance variable of the superclass, then to resolve the naming conflict within the subclass, the “super” keyword is used withthe instance variable of the super class. Similarly, the super class method can be called within thesubclass method using the super keyword. let us take an example:class A{

int x, y;

 A (int p, int q){x=p;y=q;

}void sum (){

int s=x+ y;System.out.println (―The sum is ―+s);

} A ()

{}}class B extends A{

Page 24: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 24/42

T u t o r i a l o n J a v a P a g e  | 24

int x;B (int p, int q, int r){

super. x=p;y=q;this. x=r;

}void sum (){

int m=super.x + y + this.x;System.out.println (―The sum is ―+s);

}}Class B has an instance variable x and the super class A also has an instance variable x. Sowithin class B, super.x  refers to the instance variable x inherited from the super class and this.xrefers to the instance variable x of class B itself.  super is used to invoke parent class constructor

The super keyword can also be used to invoke the parent class constructor as given below:class Employee{

String nm;int basic;Employee (String n, int b){

nm=n;basic=b;

}}

class Manager extends Employee{

String dept;Manager (String nm, int basic, String d){

super (nm, basic);dept=d;

}}class Inherit1{

public static void main (String s []){

Manager m=new Manager ("Anup", 8900,"Acct");}

}In the constructor of Manager  class, super (nm, basic) will call the constructor of the super classthat is the constructor of Employee class which accepts two integer parameters.  super can be used to invoke parent class method.

The super keyword can also be used to invoke parent class method. It should be used in casesubclass contains the same method as parent class as in the example given below:Class Person{

void message (){

Page 25: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 25/42

T u t o r i a l o n J a v a P a g e  | 25

System.out.println ("welcome");}

}Class Student extends Person{

void message (){

System.out.println ("Welcome to java");}Void display (){

message (); //will invoke current class message () methodsuper . message (); //will invoke parent class message () method

}public static void main (String s[]){

Student s=new Student ();

s. display ();}}In the display () method of the Student class (subclass), sup er.mess age ()   will invoke themess age ()  method of the super class that is of the Person class. In this way a method of thesuper class can also be called in a method of the subclass using the super keyword.

Method Overriding After inheritance, if the super class method is redefined in the sub-class then this feature is calledmethod overriding and the method of the super class is called overridden method and the methodof the sub-class is called overriding method.

When a method in a subclass has the same name and type signature as a method in itssuperclass, then the method in the subclass is said to overr ide   the method in the superclass.When an overridden method is called from within a subclass, it will always refer to the version ofthat method defined by the subclass. The version of the method defined by the superclass will behidden. The return type and parameters of the overriding method (method of the subclass) must be sameas the return type and parameters of the overridden method (method of the super class).Let‘s take an example:class A{

void show(){System.out.println("Show() of class A");}

}class B extends A{

void show(){System.out.println("Show() of class B");}

}class OverrideBasics{

public static void main(String s[])

Page 26: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 26/42

T u t o r i a l o n J a v a P a g e  | 26

{B obj=new B();obj.show();}

}The sum() method of class A has been redefined in class B. It means that the sum() method ofclass A has been overridden by the sum() method of class B. When show( ) is invoked on anobject of type B, the version of show( ) defined within B is used. That is, the version of show( )inside B overrides the version declared in A.Overriding does not mean to define a new method, but it is actually redefinition of an existingmethod of the super class.Rules for method overriding:

  The arguments of the overriding method must be exactly the same as that of the overriddenmethod.

  The return type of the overriding method must be the same or a subtype of the return typeof the overridden method in the superclass.

  The accessibility of the overriding method must be same or more than the accessibility of

the overridden method. For example: if the superclass method is declared public then theoverriding method in the sub class cannot be either private or protected.   A method can be overridden only if it is inherited by the subclass.   A method declared as final cannot be overridden.  Constructors are not inherited and hence cannot be overridden.

Discuss different wrapper classes in JavaJava is an object-oriented language and everything is treated as an object. The primitive datatypes are not objects. They do not belong to any class. Sometimes, it is required to convert datatypes into objects. In Java, a wrapper class is a class in which a primitive value is wrapped up.These primitive wrapper classes are used to represent primitive data type values as objects.

Java provides wrapper classes for each of the primitive data types. For example, Integer wrapperclass holds primitive ‗int‘ data type value. Similarly, Float wrapper class contain ‗float‘ primitivevalues, Character wrapper class  holds a ‗char‘  type value, and Boolean wrapper class represents ‗boolean‘ type value.The following diagram gives the detail of the various wrapper classes in java:

The Number  class is an abstract class. It is the super class for the classes Byte, Short, Integer,Long, Float and Double. Boolean and Character classes are direct subclass of Object class.Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.

PrimitiveData Type

Wrapperclass

byte Byteshort Shortint Integerlong Longfloat Floatdouble Doublechar Character

Page 27: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 27/42

T u t o r i a l o n J a v a P a g e  | 27

boolean BooleanThe following two statements illustrate the difference between a primitive data type and an objectof a wrapper class:int x = 25;Integer y = new Integer (33);The first statement declares an int type variable named x and initializes it with the value 25. Thesecond statement declares an Integer object. The object is initialized with the value 33 and areference to the object is assigned to the reference variable y. the similar operation can be donefor all types of data types.Each of the eight wrapper classes have a method to retrieve the value that was wrapped in theobject. These methods have the form aaaValue ()  where aaa  refers to the corresponding datatype. For example, to retrieve the value stored in the Integer object, we use the followingstatement.Integer y = new Integer (33);int x = y.intValue();We have methods for the other seven wrapper classes: byteValue (), shortValue (), longValue (),floatValue (), doubleValue (), charValue (), booleanValue ().

 All the wrapper classes are declared final. That means we cannot create a subclass from any oneof them. All of the wrapper classes except Character  class have two constructors. The first onetakes a primitive type value as argument, and the second one takes a String.

What is abstract class?If a method is declared in a class but not defined in that class, then the method is called anabstract method. If a class contains at least one abstract method, then the class is known as anabstract class. We can‘t create an object of an abstract class.

What is an interface? An interface is a user defined data type in java with the following properties:

  All the variables declared in an interface are public, static and final by default.  All the methods are public and abstract.

 A class can implement one or more than one interfaces.

Exception and its typesWhen something abnormal occurs within a method during execution, the method creates an objectto represent that abnormal situation and hands it off to the runtime system. The object is called anexception object . This event can be caused by the program itself or by an outside resource theprogram wants to use. For example, an exception is thrown if a Java program tries to access anelement of an array which is outside the bounds of the array. Or, let's say a Java application needsto read the contents of file. If that file does not exist then an exception will be thrown.There are basically three types of exceptions. They are as below:

Checked exceptions are the exceptions that are checked at compile time. If some code within amethod throws a checked exception, then the method must either handle the exception or it mustthrow the exception using throws keyword. If a checked exception is neither handled nor thrown,then it will be a compilation error.

Unchecked exceptions are the exceptions that are not checked at compiled time. If an uncheckedexception occurs in a method, but it is not handled, still the program will be compiled. All theexceptions under Error   and Runt imeExcept ion   classes are unchecked exceptions. Everything

else under Throwable class is checked.

Page 28: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 28/42

T u t o r i a l o n J a v a P a g e  | 28

Errors: These are not exceptions at all. They are problems that are beyond the control of the useror the programmer. For example, if a stack overflow occurs, an error will arise. They are alsoignored at the time of compilation.

Exception Handling Mechanism

Whenever an exception occurs, the java runtime system supplies a piece of code to handle thatexception. This piece of code is known as default exception handler. The default handler givessome relevant information about the exception and terminates the execution of the program. So,while handling an exception, the main objective is to prevent the default handler by providing anappropriate exception handler.The exception handling mechanism is based on the following five keywords:

1. try2. catch3. finally4. throw5. throws

The statement(s) that might generate an exception is written within a try block. The try block isknown as guarded region also. The ―try‖  keyword must be used within a method and must befollowed by either catch or finally block. The basic syntax of the try-catch-finally block is as below:try{Statements---------------}catch (ExceptionType1){Statements----------------}catch (ExceptionType2){Statements----------------}catch (ExceptionType3){Statements

----------------}finally{---------------- // Block of code that is always executed // No matter whether the exception is handled or not  ----------------}If there is no exception in within the try block, then the entire try block executes normally and theexecution will be transferred to the finally block (if present) or after the try-catch construct. If an

exception occurs anywhere within the try block, then the rest part of the try block is not executedand the catch blocks are inspected. The catch block is the exception handler. The catch blocksimmediately follow the try block. If there is more than one catch blocks, then they must appear justafter the try  block. Additionally, the catch blocks must all follow each other, without any other

Page 29: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 29/42

T u t o r i a l o n J a v a P a g e  | 29

statements or blocks in between them. If any exception does not occur within the try block thennone of the catch block is executed. The following flowchart will make it clear.

The catch statement accepts only one parameter, which is a reference variable of Exception class or any of its sub-class. More than one catch block can‘t  accept the reference variable ofsame class. that is each of the catch blocks must have reference variable of different classes.Whenever an exception occurs within the try block, the exception object is immediately thrown to

the nearest catch block. The catch block has one parameter which is a reference variable ofException class or any subclass of Exception class. In any one of the following two cases a catchblock associated with a try block is executed.

i) If the reference variable within the catch block and the exception generated within the tryblock are of the same class.

ii) If the reference variable of the catch block is of a super class and the exception generatedin the try block is of a subclass.

The 2nd point needs some explanation. It is already known that a super class reference variablecan store the reference of a subclass object. The exception object generated in the try block ischecked against the reference variable of the catch block to see whether the object is storable in

that reference variable or not. Let an object of class A is generated in the try block and the catchblock has a reference variable of class B. If A is a subclass of B then that exception object can bestored in the reference variable of the catch block.In either of the cases, exception object is stored in the reference variable of the catch block andthat catch block is executed, that is, the exception is handled. If the exception object is not storedin the reference variable of any one of the catch blocks, then the exception is not handled and thedefault handler handles the exception.

The finally block is always executed irrespective of exception. Any one of the three cases maytake place:

i) If no exception occurs, then after the execution of the try block, the finally block is executed.ii) If an exception occurs and it is handled by a catch block then after handling the exception,

the finally block is executed.

No catch block found

No Exception

Execute finally block

Execute try block Find 1st matching catch

block

Execute catch block

for Exception1 

Execute catch block

for Exception2 

Execute catch block

for Exception

Exception

No exception or exception handled Exception not handled or rethrown

Normal execution continues after try-catch-finally Execution aborted and exception propagated

Page 30: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 30/42

T u t o r i a l o n J a v a P a g e  | 30

iii) If an exception occurs and it is not handled by a catch block then before execution of thedefault handler, the finally block is executed.

The runtime environment always executes the code within the finally block irrespective of whathappens in the try block. So it is the ideal place to keep the code which must be executed.

throw and throws

There is another approach of exception handling. A method, capable of throwing an exception,may not handle the exception. Rather the method can declare that it can throw one or moreexceptions. Any method capable of causing exceptions must list all the possible exceptions at thetime of declaration of the method. So that anyone calling that method gets a prior knowledgeabout which exceptions to handle. A method can do so by using the throws keyword. That is thethrows keyword is used in the signature of the function. Following is an example of declaring amethod using throws.

return type method_name (Parameter list) throws Exception1, Exception2, Exception3… 

{ Method body}

On the other hand, the throw keyword is used to throw an exception explicitly. Only object ofThrowable class or its sub classes can be thrown. As soon as an exception is throws using thethrow statement, execution is transferred to the nearest catch statement and it is checked formatching type of exception. Here is a segment of code to demonstrate the usage of throw andthrows:public void sample () throws ArithmeticException{

Statements.....if (Condition){ ArithmeticException exp = new ArithmeticException ();

throw exp;...}}Difference between throw and throws:

i) throws clause in used to declare an exception and throw  keyword is used to throw anexception explicitly.

ii)  As per syntax throw is followed by an object of Exception class or a subclass of Exceptionclass throws is followed by exception class names.

iii) The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).

iv) By using throw keyword  in java we cannot throw more than one exception but usingthrows you can declare multiple exceptions.

Threading All programmers are familiar with writing sequential programs. We have probably written aprogram that displays "Hello World!", or sorts a list of names, or computes a list of prime numbers.These are sequential programs: each has a beginning, an execution sequence, and an end. Atany given time during the runtime of the program there is a single point of execution.

Page 31: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 31/42

T u t o r i a l o n J a v a P a g e  | 31

 A thread is similar to the sequential programs described above: a single thread also has abeginning, an end, a sequence, and at any given time during the runtime of the thread there is asingle point of execution. However, a thread itself is not a program. It cannot run on its own, butruns within a program.Definition: A thread is a single sequential flow of control within a program.Threads are sometimes referred to as lightweight processes. Like processes, threads areindependent, concurrent paths of execution through a program, and each thread has its ownstack, its own program counter, and its own local variables. However, threads within a process areless insulated from each other than separate processes are. They share memory, file handles, andother per-process state.Java is a multithreaded application that allows multiple thread execution at any particular time. In asingle-threaded application, only one thread is executed at a time because the application orprogram can handle only one task at a time. But a multithreaded application allows performingmore than one task at a time.

Multithreading refers to two or more tasks executing concurrently within a single program. A threadis an independent path of execution within a program. Many threads can run concurrently within a

program. Every thread in Java is created and controlled by the  java.lang.Thread class. A Javaprogram can have many threads, and these threads can run concurrently, either asynchronouslyor synchronously.Multithreading has several advantages over Multiprocessing such as;

  Threads are lightweight compared to processes  Threads share the same address space and therefore can share both data and code  Context switching between threads is usually less expensive than between processes  Cost of thread intercommunication is relatively low that that of process intercommunication  Threads allow different tasks to be performed concurrently.

In java we can create a thread either

i) Extending the Thread class of java.lang package or byii) Implementing the Runnable interface

Extending the Thread class: The Thread class itself implements Runnable interface. A classcan inherit the Thread class and override the run ()  method according to its need.

public class HelloThread extends Thread{public void run (){System.out.println ("Hello from a thread!");

}public static void main (String s []){HelloThread t=new HelloThread ();t.start ();}}

Implementing the Runnable interfaceThe Runnable interface defines a single method, run, which contains the code executed in thethread. The Runnable object is passed to the Thread constructor, as in the HelloRunnableexample:

public class HelloRunnable implements Runnable

Page 32: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 32/42

T u t o r i a l o n J a v a P a g e  | 32

{public void run (){System.out.println ("Hello from a thread!");}public static void main (String s []){

HelloRunnable h=new HelloRunnable ();Thread t=new Thread (h)t.start ();}}Note that both examples invoke start () to start the new thread.

Life cycle of a Thread

 A thread can be in one of the five states in the thread. According to Sun Microsystem, there are

only 4 states new, runnable, non-runnable and terminated. There is no running state. But forbetter understanding the threads, we are explaining it in the 5 states. The life cycle of the thread iscontrolled by JVM. The thread states are as follows:

1. New2. Runnable3. Running4. Non-Runnable (Blocked)5. Dead

 Above-mentioned stages are explained here:  New:  A new thread begins its life cycle in the new state. The thread is in new state when

we create an object of Thread class but before the invocation of start () method. It remainsin this state until the program starts the thread. It is also referred to as a born thread.

  Runnable:  The thread is in runnable state after invocation of start () method, but the

thread scheduler has not selected it to be the running thread. But a thread can return to thisstate after either running, waiting, sleeping or coming back from blocked state also. On thisstate a thread is waiting for a turn on the processor. The start () allocates the systemresources to the thread.

Page 33: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 33/42

T u t o r i a l o n J a v a P a g e  | 33

  Running:  A thread is in running state that means the thread is currently executing itstask. There are several ways to enter in Runnable state but there is only one way to enter inRunning state: the scheduler select a thread from runnable pool.

  Not Runnable or blocked:  A thread becomes Not Runnable when one of theseevents occurs:   Its sleep () method is invoked.  The thread calls the wait () method to wait for a specific condition to be satisfied.  The thread is blocking on I/O.

 A thread in blocked state is inactive. That is it is not eligible to processor time. This thread can bebrought back to the runnable state at any time. A thread can go a number of times from runningstate to blocked state and vice versa in its life cycle.

  Dead:  A running thread enters the dead state when it completes its task or otherwiseterminates. A thread is in terminated or dead state when its run () method exits. A threadalso goes to the dead state when the stop ()  is called. A dead thread can never berestarted.

Thread Synchronization

When we start two or more threads within a program, there may be a situation when multiplethreads try to access the same resource and finally they can produce unexpected result due toconcurrency issue. For example if multiple threads try to write within a same file then they maycorrupt the data because one of the threads can overwrite data or while one thread is opening thesame file at the same time another thread might be closing the same file.So there is a need to synchronize the action of multiple threads and make sure that only onethread can access the resource at a given point in time. This is implemented using a conceptcalled monitors. Each object in Java is associated with a monitor, which a thread can lock orunlock. Only one thread at a time may hold a lock on a monitor.

Why do we need Synchronization in Java?

If our code is executing in multi-threaded environment, we need synchronization for objects, whichare shared among multiple threads, to avoid any corruption of state or any kind of unexpectedbehavior. Synchronization in Java will only be needed if shared object is mutable. If the sharedobject is either read only or immutable object, than we don't need synchronization, in spite ofrunning multiple threads. JVM guarantees that Java synchron ized c ode w i l l on ly be executed

by o ne thread at a t ime . In Summary Java synchronized Keyword provides following functionalityessential for concurrent programming:

  Synchronized keyword in Java provides locking, which ensures mutual exclusive accessof shared resource and prevent data race.

  Synchronized keyword involve locking and unlocking. Before entering into

synchronized method or block a thread needs to acquire the lock, at this point it readsdata from main memory than cache and when it release the lock, it flushes writeoperation into main memory which eliminates memory inconsistency errors.

Understanding the concept of LockSynchronization is built around an internal entity known as the lock or monitor. Every object has alock associated with it. By convention, a thread that needs consistent access to an object's fieldshas to acquire the object's lock before accessing them, and then release the lock when it's donewith them.

Problem without Synchronization

Look at the following which has not used the synchronized method:class Table

Page 34: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 34/42

T u t o r i a l o n J a v a P a g e  | 34

{void printTable (int n)//method not synchronized{

for (int i=1; i<=5;i++){

System.out.println (n*i);try{

Thread.sleep (400);}catch (Exception e){

System.out.println (e);}

}}

}

class MyThread1 extends Thread{Table t;MyThread1 (Table t){

this.t=t;}public void run (){

t. printTable (5);}

}class MyThread2 extends Thread{

Table t;MyThread2 (Table t){

this.t=t;}public void run (){

t. printTable (100);

}}class Use{

public static void main (String s[]){

Table obj = new Table (); //only one object. It will be used by two threads.MyThread1 t1=new MyThread1 (obj);MyThread2 t2=new MyThread2 (obj);t1. start ();t2. start ();

}}The result of the code is:

Page 35: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 35/42

T u t o r i a l o n J a v a P a g e  | 35

510010200153002040025500It means that both the threads try to access the same object. Hence the values are being printedin this fashion.But if the printTable () is declared as synchronized, then the result changes a lot. At first onethread gets the lock associated with the object, completes its task with the object and thenreleases the lock. After that the next thread is allowed to access the object. The code will remainthe same, except that the printTable () method will be declared as below:syn chro nized void printTable (int n)

Now the result will be:510152025100200300400500

Synchronized blockSynchronized block can be used to perform synchronization on any specific resource of themethod. Suppose we have 50 lines of code in our method, but we want to synchronize only 5lines, you can use synchronized block.If we put all the codes of the method in the synchronized block, it will work same as thesynchronized method.Points to remember for Synchronized block

  Synchronized block is used to lock an object for any shared resource.  Scope of synchronized block is smaller than the method.

Syntax to use synchronized block 

synchronized (object reference expression){//code block}Here is a synchronized block of Java code inside an unsynchronized Java method:public void add (int value){synchronized (this){this.count += value;}}Note that a synchronized block takes an object in parentheses. In the example "this" is used,which is the object on which the add method has been called. The object taken in the parentheses

Page 36: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 36/42

T u t o r i a l o n J a v a P a g e  | 36

by the synchronized construct is called a monitor object. The code is said to be synchronized onthe monitor object. A synchronized instance method uses the object it belongs to as monitorobject. Only one thread can execute inside a synchronized block on the same monitor object.

Example of synchronized blockLet's see the simple example of synchronized block.

class Table{

void printTable (int n)//method not synchronized{

synchronized (this){

for (int i=1;i<=5;i++){

System.out.println (n*i);try

{ Thread.sleep (400);}catch (Exception e){

System.out.println (e);}

}}

}}

class MyThread1 extends Thread{

Table t;MyThread1 (Table t){

this.t=t;}public void run (){

t. printTable (5);}

}class MyThread2 extends Thread{

Table t;MyThread2 (Table t){

this.t=t;}public void run (){

t. printTable (100);}

}class Use2

Page 37: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 37/42

T u t o r i a l o n J a v a P a g e  | 37

{public static void main (String s []){

Table obj = new Table (); //only one objectMyThread1 t1=new MyThread1 (obj);MyThread2 t2=new MyThread2 (obj);t1. start ();t2. start ();

}}The output will be same as the output with a synchronized method.Static synchronizationIf you make any static method as synchronized, the lock will be on the class not on object. Let ustake an example:Suppose there are two objects of a shared class (e.g. Table) named object1 and object2. In caseof synchronized method and synchronized block there cannot be interference between t1 and t2 ort3 and t4 because t1 and t2 both refers to a common object that have a single lock. But there can

be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquiresanother lock. If we want no interference between t1 and t3 or t2 and t4 then static synchronizationis the solution.The JVM creates a Class object when the class is loaded that is when it is used for the first time.Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates oneinstance of Class for each class that is loaded; The Class instances are Objects and can besynchronized via static synchronized methods.

class Table{

synchronized static void printTable (int n){

for (int i=1;i<=10;i++){System.out.println (n*i);try{

Thread.sleep (400);}catch (Exception e){}

}}

}

class MyThread1 extends Thread{

public void run (){

Page 38: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 38/42

T u t o r i a l o n J a v a P a g e  | 38

Table. printTable (1);}

}class MyThread2 extends Thread{

public void run (){

Table. printTable(1);}

}

class MyThread3 extends Thread{

public void run (){

Table. printTable(1);}

}

class MyThread4 extends Thread{

public void run (){

Table. printTable(1);}

}class Use{

public static void main (String t[]){

MyThread1 t1=new MyThread1 ();MyThread2 t2=new MyThread2 ();MyThread3 t3=new MyThread3 ();MyThread4 t4=new MyThread4 ();t1. start ();t2. start ();t3. start ();t4. start ();

}

}

Java applet

 A Java applet is a small dynamic Java program that can be transferred via the Internet and run bya Java-compatible Web browser. An applet can be a fully functional Java application because ithas the entire Java API at its disposal. An applet is typically embedded inside a web page andruns in the context of a browser. An applet must be a subclass of the  java.applet.Applet class.The Applet  class provides the standard interface between the applet and the browserenvironment.

There are some important differences between an applet and a standalone Java application,including the following:   An applet is a Java class that extends the java.applet.Applet class. But a java application

need not always extend a class.

Page 39: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 39/42

T u t o r i a l o n J a v a P a g e  | 39

   A main () method is not invoked on an applet, and an applet class will not define main (),but a java application needs a main () method.

   Applets are embedded in a web page. But a java application is not embedded in a awebpage.

  When a user views a web page that contains an applet, the code for the applet isautomatically downloaded to the user's machine. A java application is not automaticallyexecuted.

Life Cycle of an Applet:Four methods in the Applet class give you the framework on which you build any serious applet:

  init: This method is like a constructor. It is called by the browser (or applet viewer) to informthe applet that it has been loaded into the system. Hence, it is called before any of the otherthree methods are called, and is used for any initialization that needs to be done. The Applet class provides a default implementation of this method that does nothing.

  start: This method is called after the init method. It is also called after the page has beenmaximized or revisited. The purpose of the method is to inform the applet that it should startexecuting. The start method can be called more than once and the init method is called onlyonce.

  stop: This method is called when the user changes pages, when the page is minimized,and just before the applet is destroyed. It is called by the browser (or applet viewer) toinform the applet to stop executing. If you are explicitly starting an activity with the startmethod, you can stop it with the stop method.

  destroy: This method is called by the browser or the applet viewer to inform the applet thatit is being destroyed and that it should release any resources that it has allocated. Oncedestroyed, an applet can‘t be started again.

  paint: Invoked immediately after the start() method, and also any time the applet needs torepaint itself in the browser. The paint () method is actually inherited from the java.awt.

Advantages and Disadvantages of Java Applets A Java applet can have any or all of the following advantages:

1. Applets are cross platform and can run windows, MAC OS and Linux platform.2. It is supported by most web browser.3. It can work all the version of java plugin.4. An untrusted applet has no access to the local machine and can only access the server it

came from.5. It can work without security approval.6. It can have full access to the machine it is running on if the user agrees.7. It is cached in most web browsers. So, it will be quick to load when returning to a webpage.8. It can move the work from the server to the client.

9. It is used to make a web solution more scalable with the number of user.10. It can run at a comparable speed to other compiled languages such as C++, but many

times faster than JavaScript.

Page 40: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 40/42

T u t o r i a l o n J a v a P a g e  | 40

Disadvantages1. Java plug-in is required to run applet which is not available by default on all web browsers.2. Some browsers, particularly mobile browser running apple IOS or Android don‘t  run java

applet at all.3. Applet cannot start up until the java virtual machine is running and it can take significant

time the first time it is used.4. If applet is not already cached in the machine it will be downloaded from internet and will

take time.5. It is difficult to design and built good user interface compare to HTML technology.6. It may require a specific JRE (Java Runtime Environment).

Java.lang.Object.finalize () MethodBefore an object is garbage collected, the runtime system calls it‘s finalize () method. The intent isfor finalize () to release system resources such as open files or open sockets before gettingcollected.To add a finalize() to a class, just declare it as follows:class Test

{protected void finalize() throws Throwable{// clean up and resource held by this class. Call the super class to clean up resource held by it.super.finalize ();}}The finalize method is defined in the java.lang.Object class. It is defined as protected in the superclass. It is a best practice to call the super.finalize () after our class has freed up the resources itwas holding. This is because call to finalize are not automatically chained and garbage collectorcalls finalize () only once on an instance. If we don‘t call super.finalize, any resource held by the

super class may never be given the opportunity to free it up. Garbage collector has to inspect allobjects to see whether it has a finalize method defined and if true, it has to invoke it. By JavaLanguage Specification there is no timely execution of finalize method.Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space fromobjects which are eligible for Garbage collection. Garbage Collection in Java  is carried by athread called Garbage Col lector . Before removing an object from memory Garbage collectionthread invokes finalize () method of that object and gives an opportunity to perform any sort ofcleanup required. There are methods like System.gc () and Runtime.gc () which is used to sendrequest of Garbage collection to JVM  but it‘s  not guaranteed that garbage collection willhappen.

What is the garbage collector in Java?

 Automatic garbage collection is the process of looking at heap memory, identifying which objectsare in use and which are not, and deleting the unused objects. An object is in use means thatsome part of our program still maintains a pointer to that object. An unused object, orunreferenced object, is no longer referenced by any part of our program. So the memory used byan unreferenced object can be reclaimed.In a programming language like C, allocating and deallocating memory is a manual process. InJava, process of deallocating memory is handled automatically by the garbage collector. The basicprocess can be described as follows.Step 1: Marking

The first step in the process is called marking. This is where the garbage collector identifies whichpieces of memory are in use and which are not.

Page 41: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 41/42

T u t o r i a l o n J a v a P a g e  | 41

Referenced objects are shown in blue. Unreferenced objects are shown in gold. All objects arescanned in the marking phase to make this determination. This can be a very time consumingprocess if all objects in a system must be scanned.Step 2: Normal DeletionNormal deletion removes unreferenced objects leaving referenced objects and pointers to freespace.

The memory allocator holds references to blocks of free space where new object can be allocated.Step 2a: Deletion with CompactingTo further improve performance, in addition to deleting unreferenced objects, we can also compactthe remaining referenced objects. By moving referenced object together, this makes new memoryallocation much easier and faster.

When an Object becomes Eligible for Garbage Collection An Object becomes eligible for Garbage collection or GC  if it’s not reachable from any livethreads or any static references. In other words we can say that an object becomes eligible forgarbage collection if it‘s  all  references are null. Cyclic dependencies  are not counted asreference. So if Object A has reference of object B and object B has reference of Object A andthey don't have any other live reference then both Objects A and B will be el ig ib le for Garbage

col lect io n.Generally an object becomes eligible for garbage collection in Java on following cases:

1. All references of that object explicitly set to null e.g. object = null2. Object is created inside a block and reference goes out scope once control exit that block.3. Parent object set to null, if an object holds reference of another object and when we set

container object's reference null, child or contained object automatically becomes eligiblefor garbage collection.

Page 42: Java Notes for ECE

8/16/2019 Java Notes for ECE

http://slidepdf.com/reader/full/java-notes-for-ece 42/42

T u t o r i a l o n J a v a P a g e  | 42

getCodeBase() and getDocumentBase()

In most of the applets, it is required to load text and images explicitly. Java enables loading datafrom two directories. The first one is the directory which contains the HTML file that started theapplet (known as the document base). The other one is the directory from which the class file ofthe applet is loaded (known as the code base). These directories can be obtained as URL objects

by using getDocumentBase()and getCodeBase () methods respectively.

getDocumentBase

URL getDocumentBase()Gets the URL of the document in which the applet is embedded. For example, suppose an appletis contained within the document:http://java.sun.com/products/jdk/1.2/index.html

The document base is: http://java.sun.com/products/jdk/1.2/index.html

Returns:The URL of the document that contains the applet.

getCodeBase

URL getCodeBase()Gets the base URL. This is the URL of the directory which contains the applet.Returns:The base URL of the directory which contains the applet.