Java Exam Notes PDF
Java Exam Notes PDF
Java Exam Notes PDF
com
Introduction
Introduction to Java world
Setting up JAVA in computer
Popular Java Editors
Platform Independence
Java Virtual Machine
Object Oriented Programming
javadoc
JAR Files
PATH and CLASSPATH
Common errors
Comments
My First JAVA program
Compiling and Running an Application
Variables
Why variables?
Why so many variables
Using variables in JAVA
Identifiers
Global Variables AND Local Variables
Datatypes
Fundamental data types
Int
Char
Float etc
Compound data types
Struct
Array
Character sequence
Other data types
Typredef
Enum
Union
Constants
Instance Members
Static Members
Operators
Assignment
Arithmetic
Increment, decrement
Compound assignment
1
Relational
Page
&&, ||, ?, ,
Visit ExamFear.com for Free Question Papers for almost all Exams.
Sizeof
Precedence operator
Control
If else
While
Do while
For
Jump
Continue
Goto
Exit
Switch
Try catch finally
Function
Declaring function
Calling function
Parameters with function
Static method
Overloaded function
Inline function
Recursion
Inheritance
Single Inheritacne
Multi-Level inheritance
this and super keywords
Object Serialization
Introduction to Object Serialization
Transient Fields and Serialization
2
Visit ExamFear.com for Free Question Papers for almost all Exams.
Java String Comparison
Compare String objects to determine Equality
Java StringBuffer
StringBuffer Class
Creation of StringBuffer's
StringBuffer Functions
Others
Polymorphism
Type casting
Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of
its type support.
Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Environment variable PATH should be set to point to where the java binaries have been installed. Example, if
you use bash as your shell, then you would add the following line to the end of your '.bashrc: export
PATH=/path/to/java:$PATH'
Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for
this tutorial), TextPad.
Netbeans : it is a Java IDE that is open source and free which can be downloaded from
http://www.netbeans.org/index.html.
Eclipse : it is also a java IDE developed by the eclipse open source community and can be downloaded
from http://www.eclipse.org/
Platform independent :
Java is platform independent. Java code complied in one machine can run in any other machine if JRE or JDK
is installed in that machine. Java was conceived with the concept of WORA: "write once, run anywhere". This
4
Visit ExamFear.com for Free Question Papers for almost all Exams.
Java virtual Machine:
Java Virtual Machine, or JVM as its name suggest is a ―virtual‖ computer that resides in the ―real‖ computer as
a software process. JVM gives Java the flexibility of platform independence. JVM is java interpreter as it
converts the byte code into machine code for the computer one wants to run.
The programs written in Java or the source code translated by Java compiler into byte code and after that the
JVM converts the byte code into machine code for the computer one wants to run. JVM is a part of Java Run
Time Environment that is required by every operating system requires a different JRE .
The architecture of the JVM is given below . This architecture tell us how the JVM works . Firstly we write the
simple java program(source code) the java compiler converts the source code into the bytecode , after that JVM
reads this bytecode and converts this into the machine code.
in memory that has attributes and methods. The attributes of an object are the same as variables and the methods
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
programming based on a hierarchy of classes, and well-defined and cooperating objects. In java we create
objects and classes. Also JAVA follows concepts of OOPS such as polymorphism, Inheritance, encapsulation.
Javadoc
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML
format from Java source code . The Javadoc provides information about various methods such as
1. Purpose of function
2. Parameters of function
3. Return type of function
JAR Files:
JAR file is the compressed file format. You can store many files in a JAR file. JAR stands for the Java Archive.
This file format is used to distribute a set of java classes. This file helps you to reduce the file size and collect
many file in one by compressing files. Downloading the files are become completed in very short duration of
time because of reducing the file size. You can make the jar file executable by collecting many class file of your
java application in it. The jar file can execute from the javaw (Java Web Start).
The JAR file format is based on the popular ZIP file format. Usually these file format is not only used for
archiving and distribution the files, these are also used for implementing various libraries, components and
plug- ins in java applications. Compiler and JVMs (Java Virtual Machine) can understand and implement these
formats for java application.
The classpath tells Java where to look on the filesystem for files defining these classes.
The virtual machine searches for and loads classes in this order:
1. bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of
the Java Class Library, and the private classes that are necessary for this library to be functional).
2. extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/
3. user-defined packages and libraries
Commenting in Java:
6
Visit ExamFear.com for Free Question Papers for almost all Exams.
// Single line comment: this is used for single line comment.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different
meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in Upper
Case.Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several words are used to
form the name of the method, then each inner word's first letter should be in Upper Case. Example
public void myMethodName()
Program File Name - Name of the program file should exactly match the class name. When saving the
file you should save it using the class name (Remember java is case sensitive) and append '.java' to the
end of the name. (if the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the main() method which
is a mandatory part of every java program..
4. Type ' javac ExamFear.java ' and press enter to compile your code. If there are no errors in your code the
Page
command prompt will take you to the next line.( Assumption : The path variable is set).
Visit ExamFear.com for Free Question Papers for almost all Exams.
5. Now type ' java ExamFear ' to run your program.
6. You will be able to see ' Hello ExamFear USers ' printed on the window.
"javac class_name.java" - Compiles a Java program stored a file named with the program class name.
We compile Java file with extension *.java to create bytes code with extension *.class
"java -cp . class_name" - Runs a compiled Java program. "-cp ." specifies the current directory as the
class path.
Why variables?
Variables are used to store values that can be used by program. Also it is used to pass value from user to
computer. A variable of type char stores a single character, variables of type int store integers (numbers without
decimal places), and variables of type float store numbers with decimal places. Each of these variable types -
char, int, and float - is each a keyword that you use when you declare a variable.
int x;
char student_name;
float cost_price;
It is permissible to declare multiple variables of the same type on the same line; each one should be separa ted
by a comma.
int a, b, c, d;
If you were watching closely, you might have seen that declaration of a variable is always followed by a
8
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
semicolon (note that this is the same procedure used when you call a function).
Ok, so you now know how to tell the compiler about variables, but what about using them? One application of
variable is an addition program. Suppose you want to add two numbers, in that case you have to put number1
and number2 in memory and then add it. In such case you will need variable.
int a = 6;
int b = 3;
int result = a + b;
Java Identifiers:
All java components require names. Names used for classes, variables and methods are called identifiers. Java
identifiers should follow the rules below:
All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: cost, $price, _value, __1_value
Examples of illegal identifiers : 567pqr, - india
Java Modifiers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories
of modifiers.
Access Modifiers : defualt, public , protected, private. These are keywords that help set the visibility
and accessibility of a class, its member variables, and methods
Java Variables:
We would see following type of variables in Java:
9
Local Variables
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Instance Variables (Non static variables)
Fundamental types
Java provides the following fundamental built- in data types: Boolean, character, integer and floating-point.
Boolean Type
The Boolean type can have the value true or false. For example: bool flag = false;
If a Boolean value is converted to an integer value true becomes 1 and false becomes 0 and vice versa.
Character Type
The character type is used to store characters - typically ASCII characters but not always. For example: char
alphabet = 'a';
char number = '52';
We can declare signed and unsigned characters, where signed characters can have positive and negative values,
and unsigned characters can only contain positive values. A char is guaranteed to be at least 8 bits in size.
Integer Types
The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer values as
follows:
Like characters, signed integers can hold positive or negative values, and unsigned integers can hold only
positive values. However, plain integer can always hold positive or negative values, they're always signed.
Integer values come in three sizes, plain int, short int and long int. The range of values for these types will be
defined by your compiler. A short integer is guaranteed to be at least 16 bits and a long integer at least 32 bits.
10
Floating-Point Types
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float (single-
precision), double (double-precision) and long double (extended-precision). Some examples:
The range of values that can be stored in each of these is de fined by your compiler.
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
2 or 4
wchar_t Wide character. 1 wide character
bytes
* The values of the columns Size and Range depend on the system the program is compiled for.
11
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
A composite data type is any data type which can be constructed in a program using primitive data types and
other composite types. Examples of composite data types are enum, struct, class, string etc
Structs or Structures
There are many instances in programming where we need more than one variable in order to represent
something. For example, to represent student, you might want to store name, age, address, phone number etc, or
any other number of characteristics about student. You could do so like this:
However, you now have 4 independent variables that are not grouped in any way. If you wanted to pass
information about yourself to a function, you‘d have to pass each variable individually. Furthermore, if you
wanted to store information about more people, you‘d have to declare 4 more variables for each additional
student.
Fortunately, Java allows us to create our own user-defined aggregate data types. An aggregate data type is a
data type that groups multiple individual variables together. One of the simplest aggregate data type is the
struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit.
Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can
begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct
declaration:
struct Student
{
char strName[20];
int age;
char address;
int phoneNumber;
}
This tells the compiler that we are defining a struct named Student. The Employee struct contains 4 variables
inside of it: two ints and two char. These variables are called members (or fields). Keep in mind that the above
is just a declaration — even though we are telling the compiler that the struct will have variables, no memory is
allocated at this time.
In order to use the Employee struct, we simply declare a variable of type Employee:
Student s1, s2;
Using this command we create objects of student , S1 and S1 and hence memory is allocated.
Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be
12
Visit ExamFear.com for Free Question Papers for almost all Exams.
That means that, for example, we can store 10 values of type int in an array without having to declare 10
different variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.
unt arrayStudentId[10]; // This can store 10 student ids..
arrayStudentId[0]= 123; arrayStudentId[1]= 124; etc..
int ExamFear[3][4];
0 1 2 3
0 1 2 3
Java Keywords:
13
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
The following list shows the reserved words in Java. These reserved words may not be used as constant or
variable or any other identifier names.
Enumerated types
An enumerated type is a data type where every possible value is defined as a symbolic constant (called an
enumerator). Enumerated types are declared via the enum keyword. Let‘s look at an example:
14
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is declared
memory is allocated for that variable at that time.
Enum variables are the same size as an int variable. This is because each enumerator is automatically assigned
an integer value based on it‘s position in the enumeration list. By default, the first enumerator is assigned the
integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:
Operators
Operator is used to operate variables and constants. Lets discuss various kinds of operators in Java.
Assignment (=)
This operator assigns a value to a variable.
This statement assigns the integer value 10 to the variable i. The part at the left of the assignment operator (=) is
variable whereas the one on right is constant. The assignment operation always takes place from right to left
only.
Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the JAVA language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators.
Modulo is the operation that gives the remainder of a division of two values. For example, if we write:
int b = 10 % 4;
the variable a will contain the value 2, since 2 is the remainder from dividing 10 by 4.
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
15
Compound assignment operators are used when we want to modify the value of a variable by performing an
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Usage Example:
p -= 6; p = p - 6;
p /=q; p = p / q;
a *= b - 5; a = a * (b -5);
Increase operator (++) and the decrease operator (--) increase or decrease by one the value stored in a variable.
P=5;
Q= ++P; //Here both P and Q stores 6.
P=5;
R = P++; //Here R stores 5 and P stores 6.
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Visit ExamFear.com for Free Question Papers for almost all Exams.
(5<2) // this returns false. (2<5) // this returns true
(2>5) // this returns false. (5>2) // this returns true
&& Operator
This is AND operator. For A && B, if both A and B are true, result is true else it is false. Even if one is false,
result is false.
|| Operator:
This is logical OR operator. For A && B, even if either of A or B is true, result is true. It is false only when
both A and B are false.
Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a different one
if the expression is evaluated as false. Its format is:
variable = condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
A = 9<5 ? 5 : 6 // returns 6, since 9 is not greater than 5.
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression
is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is
p = (q=4, q+3);
Here q is assigned 4 in first place, then q+3, that is (4+3 =7) is assigned to P.
The above code converts float float_vlaue to int. here integer_value stores values 5 as decimal place is lost in
type conversion.Type casting can also be done in the syntax mentioned below.
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
integer_value = int (float_value );
sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes
of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined before program execution.
Control Structures
In real world, we need scenarios where program need to take decision, jump to code in some other place, repeat
code etc. This can‘t be achieved by linear sequence of instructions. So we have concept of control structures.
Before we proceed further, let me introduce you to a concept called block. Block is a group of sentence that are
enclosed in {};
if and else
The if keyword is used to execute a piece of statement or block only when a given condition is true.
Else statement is used to execute a piece of statement or block only when a given statement is false.
Syntax:
if ( condition)
{ Execute this block if condition is true}
else
{ Execute this block if condition is false}
Code:
if (a == b)
{System.out.println( ― both a and b are equal‖)}
else
{ System.out.println( ― both a and b are not equal‖)}
18
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Loop is used when we want a block to be executed certain number of times.
Format:
while (Condition is true)
{ statements to be executed }
In this case, the statements will be executed till the condition is true.
while(true)
{ System.out.println(―this is a tutorial by examfear.com‖); }
int i=10;
while(i>0)
System.out.println(―this is a tutorial by examfear.com‖);;
i--;
}
This statement will be executed 10 times.
Do-while loop
Do while loop and while loop are almost similar with a difference that do while loop is executed at least once
even if the condition is false. This is because condition in the do-while loop is evaluated after the execution of
statement instead of before.
Syntax:
do
{statements to be executed}
while
(condition);
CODE:
int i=10;
do
{ System.out.println((―this is a tutorial by examfear.com‖);
}
while (i ==5)
This statement will be executed once even when the condition is false
19
int i=10;
while (i ==5
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
}
while(true)
{ System.out.println(― this document is brought to you by examfear.com‖);
break;
}
Without break statement, this loop will print infinite times, but sine we have placed a break statement, the cout
statement will be executed only once.
The continue statement is used to skip rest of the loop and goes back to the start of the current iteration as if end
of the block is reached.
Suppose we want to print odd numbers from 1 to 10. then we can use continue statement to skip printing of
even number.
int i = 0;
while ( i <10)
{i++;
if(i%2 == 0) continue; // if the number is even, it will return true and hence we will skip the next statement.
System.out.println( i);
}
int i = 0;
while ( i <10)
{i++;s
if(i%2 == 0) Label1234; // if the number is even, it will return true and hence we will to label1234.
20
System.out.println( i);
Label1234:
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
The exit function
The purpose of exit is to terminate the current program with a specific exit code. exit is a function defined in the
cstdlib library .
Syntax:
void exit (int exitcode);
The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit
code of 0 means that the program finished normally and any other value means that some error or unexpected
results happened.
Switch statement.
Switch statement is used to check several possible values for an expression and then decide to execute a
statement or block based on that value.
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
switch (a) {
case 1: System.out.println("a is 1‖); break;
case 2: System.out.println("a is 2‖); break;
case 3: System.out.println(("a is 3‖); break;
21
default:
System.out.println("a is unknown");
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
}
This code will print ―a is 1‖ is a ==1; ―a is 2‖ if a==2; ―a is 3‖ if a==3 and ―a is unknown‖ if a is any other
number.
Example:
/**
* @param args
*/
22
Visit ExamFear.com for Free Question Papers for almost all Exams.
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);
int i = 0;
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
}
}
Functions
In real world programming, code is huge. It is difficult to manage code if it is not structured. Also in most of the
case we use same logic at multiple places, so it doesn‘t make any sense to write same block of code multiple
times. Hence comes the concept of function.
Advantage of functions:
A function is a group of statements that is executed when it is called from some point of the program. The
following is its format:
where:
23
1. type is the data type returned by the function. E.g.: if it is Int, it means that function return integer.
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
3. parameters: Each parameter consists of a data type specifier followed by an identifier, like any regular
variable declaration (for example: int a) and which acts within the functio n as regular local variable.
4. statements is the function's body. It is a block of statements surrounded by braces { }.It is the bunch og
code that needs to be executed on function call.
Output:
The sum of 6 and 2 is 8
Explanation:
The code starts from void main() function. The first statement creates an integer a variable. In the next
statement function additionFx () is called with two parameters viz 6, 2. Thus the control will now go to the
function. As we notice that return type of function is integer it will return integer and the output will be stored in
integer variable named a. If we go inside the function than we notice that the function use two local variables p
and q , that are also parameters to the function. We define a variable called r, this variable stores the sum of p
and q and returns back which is now captured by a. And finally the number ―a‖ is printed.
void main ()
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
int a,b,c;
b=6;
c=2;
a = additionFx (b,c);
System.out.println( "The sum of 6 and 2 is " + a);
}
Output:
The sum of 6 and 2 is 8
Explanation:
This program is similar to what mentioned above with only one difference. Instead of passing constant values 2
and 6 to function, now we are passing variables to the function. This works perfectly fine.
}
void main ()
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
{
System.out.println (additionFx (3));
System.out.println (‖ , ‖);
System.out.println( additionFx (3,5));
}
Output:
7 , 8
Explanation:
When additionFx (3)is called, b takes its default value that is 4 and thus output is 3+ 4 =7;
When additionFx (3,5) is called the output is 3+5 =8;
Overloaded functions.
To make code more readable, we need functions that perform different action if they have either differen
number of parameter or different type of parameter.
void main ()
{int l=2,b=3,r=7;
System.out.println (―Area of rectangle is ‖ + area (l,b));
System.out.println (―Area of circle is ‖ +area(r));
}
Area of rectangle is 6
Area of circle is 154
Explanation:
Here we have two methods with same name called area. First one calculates area of rectangle while second one
calculates area of circle. This is done by overloaded function. The argument to both function are different.
When we call area (l,b), then first function is called that calculates area of rectangle. When we call area ®, then
second function is called , calculating area of circle.
Declaring functions.
26
Till now, we have defined function and then we have used it. If we try to do other way round it will throw error
as compiler will not be aware of the function. In order to avoid this we can just declare the function before
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Syntax:
It is identical to a function definition, except that it does not include the body of the function and also it doesn‘t
have braces {}. Also note the semicolon at the end of declaration.
The parameter enumeration does not need to include the identifiers, but only the type specif ier. Both statement
below will work fine.
Output:
The sum of 6 and 2 is 8
Here addition function is just defined after function invocation, but still it ran successfully because of function
declaration before function calling.
Let‘s revise what all we can do with function. Things we can do with function:
Classes
27
A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and
functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Classes are generally declared using the keyword class, with the following format:
class class_nm {
access_specifier_a:
member1;
access_specifier_b:
member2;
...
function(parameters);
} object_nm;
Here Class_nm is unique name of class. object_nm is name of object. Access_specifier are keywords private,
public or protected. These specifiers modify the access rights that the members following them acquire:
Private member of a class are accessible only from members of the same class. We will talk about
friendslater.
Public members are accessible from anywhere where object is visible.
If no access specifier is defined then it is considered private.
//Example of class
class ExamFear {
int x, y;
public:
void print_message(char);
int user_id (char);
} user1234;
The above code defines a class called Examfear which has two variables x and y defined . Also it has two
function. ―user1234‖ is the object of the class. If we want to access variable or function of the class then we
have to prefix it with ―objectname. ― . Eg: in this case we have to say user1234.print_message(―a‖);
Also we need to note that we can‘t access x and y outside the body of class as they are private variables. Only
functions of the class can use it.
Constructors
In real world problems, we need to initialize variables during the process of creation based on business logic to
avoid null values during exception. In order to achieve that we need special function called constructor.
Constructor is automatically called when a new object is created. Then name of constructor should be same as
class name and should not have any return type, not even void.
class ExamFear {
Page
int userId;
Visit ExamFear.com for Free Question Papers for almost all Exams.
public:
ExamFear (int id) {
userId = id;
}
int showUserId()
{return userId;
}
Here we see that while creating object (ef1) of class ExamFear, we passed the value of userId. The value 1234,
is assigned to UserId. When we invoke showUserId, it displays the value 1234.
Please note that constructors cannot be called explicitly as a regular member functions. They are only executed
when a new object of that class is created. Also neither constructor declaration nor constructor definition has a
return type.
Overloading Constructors
Like any other function, a constructor can also be overloaded with more than one function that have the same
name but different types or number of parameters. Remember that for overloaded functions the compiler will
call the one whose parameters match the arguments used in the function call. In the case of constructors, which
are automatically called when an object is created, the one executed is the one that matches the arguments
passed on the object declaration:
Default constructor
If you do not declare any constructors in a class definition, the compiler assumes the class to have a default
constructor with no arguments. But as soon as you declare your own constructor for a class, the compiler no
longer provides an implicit default constructor. So you have to declare all objects of that class according to the
constructor prototypes you defined for the class:
Java Package:
In simple it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds
29
of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life
Page
much easier.
Visit ExamFear.com for Free Question Papers for almost all Exams.
Import statements:
In java if a fully qualified name, which includes the package and the class name, is given then the compiler can
easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler
to find that particular class.For example following line would ask compiler to load all the classes available in
directory java_installation/java/io :
import java.io.*;
Interfaces:
In Java language an interface can be defined as a contract between objects on how to communicate with each
other. It provides only name of method not the definitio n. Interfaces are used to provide a template or design for
concrete subclasses down the inheritance tree. Eg: In case of car, it is defined that it should have methods such
as tyresSize() , enginePower(),and howToStartCar().
Here if we just declare that tyresSize() , enginePower(),and howToStartCar() are mandatory features of car
without commenting anything on this, and allowing different manufactures to decide on tyres size, Engine
power and steps to start car. The above scenario can be represented in Java by using interface and inheritance.
interface CarInterface
int tyreSize;
int enginePower ;
int tyresSize();
int enginePower();
}
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
public int tyresSize() { return tyreSize;}
Like any other class, an abstract class can contain fields that describe the characteristics and methods that
describe the actions that a class can perform. An abstract class can include methods that co ntain no
implementation. These are called abstract methods. The abstract method declaration must then end with a
semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class
must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the
abstract methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided
for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses.
An object must have an implementation for all of its methods. You need to create a subclass that provides an
implementation for the abstract method.
methods. The abstract method declaration must then end with a semicolon rather than a b lock.
6. If a class has any abstract methods, whether declared or inherited, the entire class must be declared
Page
abstract.
Visit ExamFear.com for Free Question Papers for almost all Exams.
7. An abstract class can contain access modifiers for the subs, functions, properties
Inheritance:
In java classes can be derived from classes. Basically if you need to create a new class and there is already a
class that has some of the code you require, then it is possible to derive your new class from the already existing
code. This concept allows you to reuse the fields and methods of the existing class with out having to rewrite
the code in a new class. In this scenario the existing class is called the super class and the derived class is called
the subclass.
Here we see that Vehicle inherits some property of Engine, Normal car inherits some property of Vehicle, and
luxury car inherits property of normal car.
Class normalCar extends Vehicle { String SeatBelt; String Steering; String brake; }
Class luxuryCar extends normalCar { String AirConditioner; String Stereo; String LeatherSeats; }
Multiple Inheritance
32
The mechanism of inheriting the features of more than one base class into a single class is known as multiple
Page
inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the
Visit ExamFear.com for Free Question Papers for almost all Exams.
interface. In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than
one interfaces in a class. We will see this in Interface section.
This keyword:
It is used to get values of current class. The keyword this is useful when you need to refer to instance of the
class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we
have declare the name of instance variable and local variables same. Now to avoid the confliction between them
we use this keyword. Here, this section provides you an example with the complete code of the program for the
illustration of how to what is this keyword and how to use it.
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class.It is used
for two purposes in java.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to handle situations
where the local members of a subclass hides the members of a super class having the same name. The following
example clarify all the confusions.
class ABC{
int b;
void display()
a1.display();
Visit ExamFear.com for Free Question Papers for almost all Exams.
p1.display();
Output:
Value of b in class ABC is 5
Value of super b in class PQR is : 5
Value of b in class PQR is 8
Object Serialization
Java object serialization is used to persist Java objects to a file, database, network, process or any other system.
Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then
be read at a later time, or in another environment, to recreate the original objects.
Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the
state from being written to the stream and from being restored during deserialization. Java provides classes to
support writing objects to streams and restoring objects from streams. Only objects that support the
java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.public interface
Serializable
These high- level streams are each chained to a low- level stream, such as FileInputStream or FileOutputStream.
The low- level streams handle the bytes of data. The writeObject method saves the state of the class by writing
the individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
34
Visit ExamFear.com for Free Question Papers for almost all Exams.
String:
String comparison
We should use ".equals" rather than "==" to avoid unexpected outcome. It simply because ".equals" will
compare 2 strings character by character to determine equality while "==" checks whether 2 string objects are
identical. Try to do this experiment and you will understand:
It returns false.
It returns true.
It returns true.
String buffer
StringBuffer Class : StringBuffer class is a mutable class unlike the String class which is immutable. Both the
capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers
are preferred when heavy modification of character strings is involved (appending, inserting, deleting,
modifying etc).
Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method
from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String
Buffer manipulations
}
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Output
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16
StringBuffer Functions
3. charAt(int index) :The specified character of the sequence currently represented by the string buffer, as
indicated by the index argument, is returned.
4. setCharAt(int index, char ch) : The character at the specified index of this string buffer is set to ch
6. insert(int offset, char c) : Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‗insert‘ methods which can be used based on the
application need.
7. delete(int start, int end) : Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str) : Replaces the characters in a substring of this StringBuffer with
characters in the specified String.
9. reverse() : The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str) : Appends the string to this string buffer. Note that the StringBuffer class has got many
overloaded ‗append‘ methods which can be used based on the application need.
Exception handling
An exception can be defined as an unexpected event that occurs during the execution of a program and disrupts
the normal of instructions.
The exception- handling facility of Java allows programs to handle abnormal and unexpected situations in a
structured and orderly manner.
36
try blocks
Visit ExamFear.com for Free Question Papers for almost all Exams.
catch blocks
throw expressions
Exception specific
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred
is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a
method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.
}
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
This would produce following result:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try.
If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the
data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the exception either is caught or falls through all
catches, in which case the current method stops execution and the excep tion is thrown down to the previous
method on the call stack.
Example: Here is code segment showing how to use multiple try/catch statements.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
38
Visit ExamFear.com for Free Question Papers for almost all Exams.
f.printStackTrace();
return -1;
}
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list
separated by commas. For example, the following method declares that it throws a RemoteException and an
InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred.
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what
happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
Visit ExamFear.com for Free Question Papers for almost all Exams.
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:
You just need to extend the Exception class to create your own Exception class. These are considered to be
checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends
the Exception class, making it a checked exception. An exception class is like any other class, containing useful
fields and methods.
Polymorphism
Polymorphism enables one common interface for many implementations, and for objects to act differently
under different circumstances.Java supports several kinds of static (compile-time) and dynamic (run-time)
polymorphisms. Compile-time polymorphism does not allow for certain run-time decisions, while run-time
polymorphism typically incurs a performance penalty.
Let us summarize:
If an object A wishes object B to achieve some objective , it conveys this to object b by sending a message .The
set of action taken by object B to achieve the end objective is called the method ;in other words , an object
responds to a message using a method .Different objects may use different methods in response to the same
41
message.
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
The term polymorphism has been derived from greek words ‗poly‘ and ‗morphos‘ which means ‗many and
‗forms‘ respectively .
Static Polymorphism
Static polymorphism refers to an entity existing in different physical forms simultaneously. Static
polymorphism involves binding of functions based on the number, type, and sequence of arguments. The
various types of parameters are specified in the function declaration, and therefore the function can be bound to
calls at compile time. This form of association is called early binding. The term early binding stems from the
fact that when the program is executed, the calls are already bound to the appropriate functions.
The resolution of a function call is based on number, type, and sequence of arguments declared for each form of
the function. Consider the following function declaration:
When the add() function is invoked, the parameters passed to it will determine which version of the function
will be executed. This resolution is done at compile time.
Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the circumstances. A function is said
to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are
resolved dynamically when the program is executed. The term late binding refers to the resolution of the
functions at run-time instead of compile time. This feature increases the flexibility of the program by allowing
the appropriate method to be invoked, depending on the context.
As applications are becoming larger and more complicated, the need for flexibility is increasing rapidly. Most
users have to periodically upgrade their software, and this could become a very tedious task if static
42
polymorphism is applied. This is because any change in requirements requires a major modification in the code.
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
In the case of dynamic binding, the function calls are resolved at run-time, thereby giving the user the flexibility
to alter the call without having to modify the code.
To the programmer, efficiency and performance would probably be a primary concern, but to the user,
flexibility or maintainability may be much more important. The decision is thus a trade-off between efficiency
and flexibility.
Type Casting
Converting an expression of a given type into another type is known as type-casting. We have already seen
some ways to type cast:
Implicit conversion
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a
compatible type. For example:
short a=2000;
int b;
b=a;
Here, the value of a has been promoted from short to int and we have not had to specify any type-casting
operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and
allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to
or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which
the compiler can signal with a warning. This can be avoided with an explicit conversion.
Implicit conversions also include constructor or operator conversions, which affect classes that include specific
constructors or operator functions to perform conversions. For example:
class A {};
class B { public: B (A a) {} };
A a;
B b=a;
Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that
takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.
Explicit conversion
43
Java is a strong-typed language. Many conversions, especially those that imply a different interpretation of the
value, require an explicit conversion. We have already seen two notations for explicit type conversion:
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.
short a=2000;int b;
44
Page
Visit ExamFear.com for Free Question Papers for almost all Exams.