Java Note Revised
Java Note Revised
Introduction to Java
Java is a simple and powerful object oriented programming language.
It is developed by James Gosling and his team at Sun Microsystems, Inc. in 1991.
In many respects it is similar to C and C++.
The older name of Java was OAK.
It was developed to provide a platform-independent programming language.
Initially it was developed to be used in electronic consumer goods like TV, VCR, washing
machine etc.
2. Features of Java
Java possess the following features
It is an object oriented programming language.
Java programs are both compiled and interpreted.
Java programs are platform independent.
Java is a robust programming language.
It is a multithreaded programming language.
It can access data from a local system as well as from net.
Java programming is written within a class. The variables and functions are developed and
defined within the class.
Java programs can create Applets (Programs which run on web browsers) and Applications
are general programs like any other programming languages.
Java doesn’t require any preprocessor or inclusion or header files from creating java
application program.
Java is a case sensitive language. It distinguishes the upper case and lower case letters.
JAVA Page 1
5. What is Java Packages?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, java.awt, java.applet, javax.swing, java.net,
java.io, java.util, java.sql, java.lang, java.net, java.txt, java.math etc.
java.lang is the default package.
To use a package we need to import it in our program.
JAVA Page 2
Following is the basic form of a variable declaration –
<data type> variable1=values;
There are three kinds of variables in Java such as –
Local variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.
Instance variables
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object, a slot for each instance variable value is created.
Instance variables are created when an object and destroyed when the object is destroyed.
Instance variables can be declared in class.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is
false, and for object references it is null.
Instance variables can be accessed directly by calling the variable name inside the class.
Class variables /Static variables
Class variables also known as static variables are declared with the static keyword in a class
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Static variables are rarely used other than being declared as constants.
Static variables are stored in the static memory.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared public.
Static variables can be accessed by calling with the class name ClassName.VariableName.
JAVA Page 3
10. What is the use of final keyword?
When the final keyword is used with some variables they become constants and hence cannot
be changed during the execution of the program.
When the final keyword is used with the method, the method cannot be overridden by
subclasses.
A final class cannot be extended. e.g String class is a final class so we cannot extend it.
Final variables, methods and classes are used for security purpose.
e.g
public class A{
public final int x =1; // declared as final variable
public final void disp() // declared as final method
{
System.out.println(“Final Method”);
}
}
public class B {
public static void main(String args[ ]){
A a = new A();
a.x = 2; //illegal : final variable can’t be changed
}
public class C extends A{
public void final disp(){
System.out.println(“Final method in Derived C”); } //illegal : final method with same
signature) can’t be overrriden
}
public void disp(int a) {
System.out.println(“This number is +a);} //legal : this is method overloading
}
A method is a piece of code that is called by a name and it is associated with an object. In most
respects it is identical to a function except for the following two key differences:
A method is implicitly passed the object on which it was called.
A method is able to operate on data that is contained within the class.
JAVA Page 4
The general format is:
public static int methodName(int a, int b)
{
Method body;
}
Constructor Method
Constructor is used to initialize the state of an Method is used to expose behavior of an
object. object.
Constructor must not have return type Mehod must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default Method is not provided by compiler is any
constructor if you don’t have any constructor. case
Constructor name must be same as the class Method name may or may not be same as class
name. name.
JAVA Page 5
16. Java String Functions
I. length() : length() function returns the number of characters in a String or length of a String.
Syntax : int var = <string variable>. length();
Example :
String str = "Count me";
System.out.println(str.length());
Output : 8
II. charAt():charAt() function returns the character located at the specified index.
Syntax : char var = <string variable>. charAt (index value);
Example :
String str = "COMPUTER";
System.out.println(str. charAt(4));
Output : U
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String
str.
III. indexOf(): It returns the first occurrence of the specified character. If a character is not
present then it returns -1.
Syntax : int var = <string variable>. indexOf(character value);
Example :
String str = "MALAYALAM";
System.out.println(str. indexOf(‘A’));
Output : 1
System.out.println(str. indexOf(‘A’,2));
Output : 3
System.out.println(str. indexOf(‘P’));
Output : -1
System.out.println(str. indexOf(‘Y’));
Output : 4
System.out.println(str. indexOf(‘Y’,5));
Output : -1
IV. lastIndexOf():It returns the last occurrence of the specified character. If a character is not
present then it returns -1..
Syntax : int var = <string variable>. LastIndexOf(character value);
Example :
String str = "MALAYALAM";
System.out.println(str. indexOf(‘A’));
Output : 7
System.out.println(str. indexOf(‘A’,5));
Output : 5
System.out.println(str. indexOf(‘P’));
Output : -1
System.out.println(str. indexOf(‘Y’));
Output : 4
System.out.println(str. indexOf(‘Y’,3));
Output : -1
JAVA Page 6
String str = "COMPUTER";
System.out.println(str.toLowerCase());
Output : computer
VI. toUpperCase():It returns string with all lowercase characters converted to uppercase.
Syntax : String var = <string variable>. toUpperCase();
Example :
String str = "computer";
System.out.println(str.toUpperCase());
Output : COMPUTER
VII. trim():This method returns a string from which any leading and trailing whitespaces has
been removed.
String str = " hello ";
System.out.println(str.trim());
hello
NOTE: If the whitespaces are between the string, for example:
String s1 = " Hello Students "; then System.out.println(s1.trim()); will output "Hello
Students".
trim() method removes only the leading and trailing whitespaces.
VIII. substring(): It returns a part of the string. substring() method has two forms,
public String substring(int begin);
JAVA Page 7
In this function, each character 'X' of the string is replaced by A' starting from 3rd.
index. ... Hence, the new string p results in "MAXAYALAM".
String s = "The green bottle is in green bag";
String p = s.replace ("green", "red");
Here, each sub string "green" of the given string is replaced by "red". Hence, the new
string p results in "The red bottle is in red bag".
XI. equals ():This function is used to compare two strings together to check whether they are
identical or not. It returns a Boolean type value true if both are same, false otherwise.
Syntax: boolean variable = string variablel . equals(string variable2);
Example:
String x = "COMPUTER";
String y = "SCIENCE";
boolean z = x.equals(y);
Here, z results in false.
String x = "COMPUTER";
String y = "computer";
if (x.equals(y))
System.out.println("same");
else
System.out.println("different");
OUTPUT: different
because equals() function treats corresponding upper case and lower case characters
differently.
XII. equalsIgnoreCase():This function is also used to compare two strings to ensure whether both
are identical or not after ignoring the case (i.e., corresponding upper and lower case characters
are treated to be same). It also returns a boolean data as true or false.
Syntax: boolean variable = string variablel . equalsIgnoreCase(string variable2);
Example:
String x = "COMPUTER";
JAVA Page 8
String y = "computer";
boolean p = x.equalsIgnoreCase(y);
System.out.println(p);
Output: true.
if(x.equalsIgnoreCase(y))
System.out.println("same");
else
System.out.println("different");
Output: different
XIII. compareTo(): It is also a type of function which compares two strings. It not only checks the
equality of the strings but also checks whether a string is bigger or smaller than other or not.
The function can return an integer value depending upon the condition you want to check.
In the example given above n is assigned a -ve value, as the string COMPUTER is smaller
than SCIENCE in alphabetical order.
XIV. endsWith(): This function is used to check whether a given string has specified suffix or not.
It returns a boolean type value true or false accordingly.
Syntax: boolean b= string variable 1.endswith(string variable2);
Example:
String p= "COMPUTER IS FUN";
String b= "FUN";
boolean x= p.endswith(b);
It will return x as true.
XV. startsWith(): This function returns a boolean type value true if a given string is used as prefix
to another string, false otherwise.
Syntax: boolean b= string variable 1.startsWith(string variable2);
Example:
String p= "COMPUTER IS FUN";
String b= "YOUR";
boolean x= p.startsWith(b);
It will return x as false as string p does not start with YOUR.
XVI. valueOf():valueOf() method is present in String class for all primitive data types and for type
Object. valueOf() function is used to convert primitive data types into Strings.
Example:
int num = 35;
String s1 = String.valueOf(num); //converting int to String
JAVA Page 9
System.out.println(s1+"IAmAString");
Output: 35IAmAString
These functions deal only with the character manipulations. Some of them are explained below:
I. Character.isLetter(): This function is used to check whether a given argument is an alphabet or
not. It returns a boolean type value either true or false.
Syntax: boolean variable = Character.isLetter(character);
Example:
boolean p=character.isLetter('c');
The function will return true to the variable p.
boolean p=Character.isLetter('6');
It will return false.
II. Character.isDigit( ): This function returns a Boolean type value true if a given argument is a
digit otherwise, false.
Syntax: boolean variable = Character.isDigit(character);
Example:
boolean p=Character.isDigit('7'); It returns true to the variable p
boolean p=Character.isDigit('G'); It returns false to the variable p.
III. Character.isLetterOrDigit( ): This function returns true if the given argument is either a letter
or a digit, otherwise false.
Syntax: boolean variable=Character.isLetterOrDigit(character);
Example:
boolean b=Character.isLetterOrDigit('A');
It returns true to the boolean variable b as 'A' is a letter.
boolean b=Character.isLetterOrDigit('r');
It returns true as the given character ‘r’ is a letter.
boolean b=Character.isLetterOrDigit('9');
It returns true as the given character '9' is a digit.
boolean b=Character.isLetterOrDigit('*');
It returns false as the given character '*' is neither a letter nor a digit.
IV. Character.isWhiteSpace( ): This function can be used to check for existing blank or gap in a
String. It will return a boolean type value (i.e.: true) if the given argument is a white space (blank)
and, false otherwise.
Syntax: boolean variable=Character.isWhiteSpace(character);
Example:
boolean b=Character.isWhiteSpace(' ');
It returns true to the boolean variable b as the given character is a blank
boolean b=Character.isWhiteSpace('*' );
It returns false to the boolean variable b as the given character is not a blank.
JAVA Page 10
V. Character.isUpperCase(): This function will return true if the given argument is an upper case
letter otherwise false.
Syntax: boolean variable = Character.isUpperCase(character);
Example:
boolean p=Character.isUpperCase('A');
It returns true to the variable p.
boolean p=Character.isUpperCase('g'); It returns false to the variable p.
VI. Character.isLowerCase( ): This function will return true if the given argument is a lower case
letter otherwise false.
Syntax: boolean variable = Character.isLowerCase(character);
Example:
boolean p=Character.isLowerCase('LP); It returns false to the variable p.
boolean p=Character.isLowerCase('g'); It returns true to the variable p.
VII. Character.toUpperCase( ): This function returns the given argument in upper case character.
The given character remains same if it is already in upper case. It returns the same character if the
character used with the function is non-alphabet.
Syntax: char variable = Character.toUpperCase(character);
Example:
char c=Character.toUpperCase('a'); It returns letter A to the variable c.
char c=Character.toUpperCase('G'); It returns G to the variable c.
char c=Character.toUpperCase('?');
It will return the same character because the given character is non-alphabet.
VIII. Character.toLowerCase( ): This function returns the given argument in lower case character.
The given character remains same if it is already in lower case. It returns the same character if the
character used with the function is non-alphabet.
Syntax: char variable = Character.toLowerCase(character);
Example:
char c=Character.toLowerCase('A); It returns letter a to the variable c.
char c=Character.toLowerCase('g'); It returns g to the variable c.
char c=Character.toLowerCase('*');
It will return the same character as the given character is non-alphabet.
i. Math.sqrt(): This function is used to find the square root of a positive number. It returns a double
type value.
Syntax: <Return Data type><variable> = Function name (Positive number);
e.g.,
double n=Math.sqrt(4.0);
It returns a double type value for n as 2.0
double n=Math.sqrt(6.25);
It returns a double type value of n as 2.5
JAVA Page 11
II. Math.min( ): This function returns minimum of two numbers. The return value depends on the
values used as the arguments of the function (i.e., if the arguments are integer numbers the result
is integer number and so on).
Syntax: <Return Data type><variable> = Function name (argument 1, argument 2);
e.g.:
int n=Math.min(4, 6);
It returns an integer type value of n as 4, which is minimum of 4 and 6.
double n= Math.min(4.6, 2.8);
This will return a double type minimum value of n as 2.8 double x=Math.min(-3.5, -9.5);
It returns the double type minimum value for x as -9.5
III. Math.max( ): This function is used to find the maximum of two given arguments. It returns a
value depending upon the arguments (i.e., if the two arguments are integer types then return value
is integer).
Syntax: <Return Data type><variable> = Function name (argument 1, argument 2);
e.g.:
int n=Math.max(4, 8);
It will return an integer type maximum value for n as 8.
double n=Math.max(12.7, 8.4);
This will return a double type maximum value for n as 12.7
double x=Math.max(-67.66, -97.45);
This function returns a double type value for x as -67.66
IV. Math.pow(): This function is used to find the power raised to a specified base (number). It
always returns a double type value.
Syntax: <Return Data type><variable> = Function name (number 1, number 2);
e.g.:
double d= Math.pow(2.0, 3.0);
The function returns a double type value to d as 2.03.0= 8.0 double d= Math.pow(5.0, -2.0);
The value of d will be returned as a double value as 0.04
V. Math.log(): This function returns natural logarithmic value of a given argument. It always returns
a double type value.
Syntax: <Return Data type><variable> = Function name (Positive number);
e.g.:
double x = Math.log(6.25);
It returns a double type value to x as 1.8325
VI. Math.abs(): This function is used to return absolute value i.e., only magnitude of the
number. It returns int/long/double value depending upon the arguments supplied.
Syntax: <Retura Data type><variable> = Function name (number);
e.g:
int n = Math.abs(3); It returns an integer value to n as 3.
int n= Math. abs(-8); It returns an integer value to the variable n as 8.
double d=Math.abs(3.66); It returns a double type value to d as 3.66
double d=Math.abs(-9.99); It returns a double type value to d as 9.99
JAVA Page 12
VII. Math.round(): This function returns the value in rounded form. It always returns an integer data
type. If the fractional part of the number is below 0.5 it returns the same integer of the argument
otherwise, it returns the next integer value.
Syntax: <Return Data type><variable> = Function name (argument);
e.g.:
int n=Math.random(6.25); It will return an integer value to n as 6.
int n=Math.random(6.85); It will return an integer value to n as 7.
int n=Math.random(-8.92); It will return an integer value for n as -9.
VIII. Math.floor(): This function is also used round the given number. It returns a number down to
the nearest integer. The outcome is always a double type number.
Syntax: <Return Data type><variable> = Function name (argument);
e.g.:
double n=Math.floor(6.25); It returns a number for n as 6.0
int n=Math.floor(6.82); It returns a number for n as 6.0 only,
int n=Math.floor(-6.25); It will return a value for n as -7.0
int n=Math.floor(-6.85); It returns a value for n as -7.0
IX. Math.ceil(): This function also provides the rounded value to the next higher integer. It returns a
double type value.
Syntax: <Return Data type><variable> = Function name (argument);
e.g.:
double n=Math.ceil(6.25); It returns a value for n as 7.0
double n=Math.ceil(6.82); It returns a value for n as 7.0 only
double n=Math.ceil(-6.25) It returns a double value for n as -6.0
double n=Math.ceil(-6.85); It returns a double value for n as -6.0
X. Math.sin(), Math.cos(), Math.tan(): These are the trigonometrical functions. They are used to
find the sin, cos, tan values respectively of a given angle in radian as an argument.
Syntax: <Return Data type><variable> = Function name (Value in Radian);
e.g.:
double d = Math.sin(x);
double d = Math.cos(x);
double d = Math.tan(x);
Here, the argument x is an angle provided in radian. These functions return double type values.
Generally, the angles are measured in degrees. Thus, it is necessary to convert them from degree
to radian to perform the above task.
XI. Math.exp(): This function provides exponential value i.e. ex. it returns a double type value.
Syntax: <Return Data type><variable> = Function name (number);
e.g.:
double d= Math.exp(6.25); d results in 518.0128.
JAVA Page 13
XII. Math.rint(): It returns the truncated value of the number (i.e., the integer part of the number by
removing fractional part).
Syntax: <Return Data type><variable> = Function name (number);
e.g.:
double d=Math.rint(6.25); it returns a double value to d as 6.0
double d=Math.rint(8.92); it returns a double value to d as 8.0
XIII. Math.random(): This function returns a random number between 0 and 1. It returns a double
type value. Normally, the return value is a fractional number.
Syntax: <Return Data type><variable> = Function name ( ) only;
e.g.:
double d=Math.random( ); It will return any double value to d between 0 and 1.
Access Specifier
19. What is Access Specifier / Access Modifier? Describe its types with examples.
Java provides a number of access modifiers to set access levels for classes, variables, methods, and
constructors.
The four access levels are – private, public, protected, default
Example
In same Package In other Packages
Member Inside own
Type Class Inside sub Inside non Inside sub Inside non
classes sub classes classes sub classes
public Yes Yes Yes Yes Yes
private Yes No No No No
protected Yes Yes Yes Yes No
Default Yes Yes Yes No No
JAVA Page 14
Consider the following class definitions :
package P1;
class A {
public int x; // declared as public data member and can be used anywhere
public void disp( ) { // declared as public function
System.out.println(“I am in class A”);
}}
Protected Access Modifier – protected
Members are accessible inside their own class in the same package as well as in all subclasses of
their class exist in the same package or any other package.
Variables, methods, and constructors, which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the protected
members' class.
The protected access modifier cannot be applied to class and interfaces.
Example
Consider the following class definitions:
package P1;
class A {
protected int x; // declared as protected data member and can’t be used outside of
package P1
protected void disp( ) { // declared as protected function
System.out.println(“I am in class A”);
}
}
Default Access Modifier - No Keyword
When the members of a class are declared without any access specifier then an java automatically
attach an access specifier to it called as default access specifier.
These members are accessible within their own class as well as in the same package where it is
declared.
These members are not accessible outside their package.
The default modifier is more restrictive than protected.
Example
Consider the following class definitions :
package P1;
class A {
int x; // declared as default data member
void disp( ) { // declared as default function
System.out.println(“I am in class A”); }
}
}
INHERITANCE
20. What is Inheritance?
The Mechanism of creating new classes from existing classes is called inheritance.
The old class is known as base class or parent class or super class.
The new class is known as derived class or child class or sub class
Need for Inheritance?
Inheritance is a wonderful concept of object oriented languages. There are several reasons why
inheritance was introduced into OOPs languages.
1. Code Reusability
JAVA Page 15
Inheritance allows the addition of additional features to an existing class without modifying it.
We can derive a new class from an existing class and also we can add new features to it if
required.
2. Transitive nature of Inheritance
If a new class “C” has been declared as a sub class of “B” which is itself a sub class of “A”
then “C” will automatically inherit the properties of “B” as well as “A” . This property is
called transitive nature of inheritance.
JAVA Page 16
22. Program on Single Inheritance
public class A { // Creating a Base Class named A
int x;
public void disp()
{
System.out.println("Class A");
}
} //end of class A
public class B extends A{ // Creating a Derieved Class named B
int y;
void show()
{
System.out.println("Class B");
}
} //end of class B
class Trial
{
public static void main(String args[])
{
B ob =new B();
ob.x=10;
ob.y=5;
System.out.println("x = "+ob.x);
System.out.println("y = "+ob.y);
ob.show();
ob.disp();
}
}
JAVA Page 17
Output :
x = 10
y=5
Class B
Class A
Class Trial
{
public static void main(String args[ ])
{
C oc =new C( );
oc.x=10;
oc.y=5;
oc.z=20;
System.out.println("x = "+oc.x);
System.out.println("y = "+oc.y);
System.out.println("a = "+oc.z);
oc.showA( );
oc.showB( );
oc.showC( );
}
} // end of class Trial
Output
x = 10
y=5
a = 20
Class A
Class B
Class C
JAVA Page 18
public class A { // Creating a Base Class named A
int x;
public void disp()
{
System.out.println("Class A");
}
} // end of class A
int y;
void showB()
{
System.out.println("Class B");
}
} // end of class B
int z;
void showC()
{
System.out.println("Class C");
}
} // end of class C
class Trial
{
public static void main(String args[])
{
B ob =new B( );
C oc= new C( );
ob.x=10;
ob.y=15;
oc.x=20;
oc.z=25;
System.out.println("x = "+ob.x);
System.out.println("y = "+ob.y);
ob.showA( );
ob.showB( );
System.out.println("x = "+oc.x);
System.out.println("z = "+oc.z);
oc.showA( );
oc.showC( );
}
}
// end of class Trial
Output
x = 10
y=5
Class A
Class B
JAVA Page 19
x = 20
y = 25
Class A
Class C
To avoid the ambiguity (confusion) java does not support multiple inheritance.
Suppose there is a classes B which is inherited from class A and C (as shown in the figure).
A C
Assume that both the class A and C contains a method called display(), and it needs to be
overridden in derived class B.
Then which class’s method will be overridden?
To avoid such confusions java does not support multiple inheritance.
Extra Read
JAVA Page 20
The aim of interfaces in Java is to dictate common behavior among objects from different
classes.
The syntax for defining an interface is very similar to that for defining a class. The general
form of an interface definition is;
interface interface_name{
interface_body;
}
The keyword interface begins the definition.
The interface body can only declare two things:
1. Abstract Methods: The methods with an empty body(Only the signature of the methods
is declared).
2. Constants: Variables which cannot be modified; they have to be declared with the
modifier public static final.
POLYMORPHISM
The word “Polymorphism” originates from Greek language and means many forms.
Polymorphism is the capability of an action or method to do different things based on the
object that it is acting upon.
Polymorphism are of two types. Such as compile time polymorphism and runtime
polymorphism.
Compile time polymorphism is also called as Static binding or early binding (e.g Method
Overloading).
Rum time polymorphism is also called as Dynamic binding or Late binding (e.g Method
Overriding).
Method Overloading
It simply refers to the ability to define several methods to have the same name within a particular
class with different signatures (arguments and return type) so that the JVM can easily calls the
appropriate methods. Following are the examples of overloaded methods.
long Math.max(long a, long b)
long Math.max(int a, int b)
long Math.max(double a, double b)
long Math.max(float a, float b)
Method Overriding
Method Overriding means whenever a subclass has a method with the same signature as a method in
one of its super class then the method in the derived class is said to be overrides the method of its
super class.
JAVA Page 21