S3 Java Full Notes
S3 Java Full Notes
Module I: A simple Java Application, a simple Java Applet , Brief History of Java,
Special Features of Java, Data Type & Operators in Java, Arrays, Objects, the
Assignment Statement, Arithmetic Operators, Relational and Logical Operators in Java,
control Structures, The Java Class, Constructor, Finalizers, Classes inside classes:
composition
OVERVIEW OF JAVA
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first
working version. This language was initially called “Oak” but was renamed “Java” in
1994 as the Web emerged.
HotJava
Basic features
The Java team has summed up the basic features of Java with the following list of
buzzwords :
• Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. Assuming that you have some programming experience, you will not find
Java hard to master. If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier. Best of all, if you are an experienced
C++ programmer, moving to Java will require very little effort. Because Java inherits the
C/C++ syntax and many of the object-oriented features of C++, most programmers have
little trouble learning Java.
• Object-oriented
the Java development kit, which also has classes to support networking, common
Internet protocols, and user interface toolkit functions.
• Robust
• Secure
Prior to Java, most users did not download executable programs frequently from
Internet, and those who did scanned them for viruses prior to execution. Even so, most
users still worried about the possibility of infecting their systems with a virus. In
addition to viruses, another type of malicious program exists that must be guarded
against. This type of program can gather private information, such as credit card
numbers, bank account balances, and passwords, by searching the contents of your
computer’s local file system. Java answers both of these concerns by providing a
“firewall” between a networked application and your computer. When you use a Java-
compatible Web browser you can safely download Java applets without fear of viral
infection or malicious intent. Java achieves this protection by confining a Java program
to the Java execution environment and not allowing it access to other parts of the
computer.
• Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows
you to write programs that do many things simultaneously. The Java run-time system
comes with an elegant yet sophisticated solution for multiprocessor synchronization that
enables you to construct smoothly running interactive systems.
• Architecture-neutral
A central issue for the Java designers was that of code longevity and portability. One of
the main problems facing programmers is that no guarantee exists that if you write a
program today, it will run tomorrow— even on the same machine. Operating system
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 2
CP1344: PROGRAMMING IN JAVA
upgrades, processor upgrades, and changes in core system resources can all combine to
make a program malfunction. The Java designers made several hard decisions in the
Java language and the Java Virtual Machine in an attempt to alter this situation. Their
goal was “write once; run anywhere, any time, forever.” To a great extent, this goal was
accomplished.
• Portable
• Distributed
Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not much different from
accessing a file. The original version of Java (Oak) included features for intra-address
space messaging. This allowed objects on two different computers to execute procedures
remotely. Java has recently revived these interfaces in a package called Remote Method
Invocation (RMI). This feature brings an unparalleled level of abstraction to client/server
programming.
• Dynamic
Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time. This makes it possible to
dynamically link code in a safe and expedient manner. This is crucial to the robustness
of the applet environment, in which small fragments of bytecode may be dynamically
updated on a running system.
The Java development environment has two parts: a Java compiler and a Java
interpreter. In the Java programming language, all source code is first written in plain
text files ending with the .java extension. Those source files are then compiled into
.class files by the javac compiler. With the compiler, first you translate a program into an
inter-mediate code called Java bytecodes. Bytecodes are not machine instructions and
therefore, in the second stage, Java interpreter generates machine code that can be
directly executed by the machine that is running the Java program. The interpreter parses
and runs each Java bytecode instruction on the computer. Compilation happens just
once; interpretation occurs each time the program is executed.
Java Virtual Machine (JVM) Java compiler produces an intermediate code known as
bytecode for a machine that does not exist. This machine is called the JVM and it exists
only inside the computer memory. The bytecodes are also known as virtual machine
code which are not the actual machine code. The actual machine codes are generated by
the Java interpreter only.
JAVA ENVIRONMENT
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java development
Kit (JDK) and the classes and methods are part of the Java Standard Library (JSL), also
known as the Application Programming Interface (API). Java development Kit the Java
development Kit comes with a collection of tools that are used for development and
running Java programs. Some of them are :
java The loader for Java applications. This tool is an interpreter and can interpret the
class files generated by the javac compiler.
javac The compiler, which converts source code into Java bytecode
jar The archiver, which packages related class libraries into a single JAR file.
jps The process status tool, which displays process information for current Java
processes
appletviewer This tool can be used to run and debug Java applets without a web
browser.
javah The C header and stub generator, used to write native methods
• Create a source file. A source file contains text, written in the Java programming
language, that you and other programmers can understand. You can use any text editor
(e.g. Notepad) to create and to edit source files.
• Compile the source file into a bytecode file. The compiler takes your source file and
translates the text into instructions that the Java VM can understand. The compiler
converts these instructions into a bytecode file.
• Run the program contained in the bytecode file. The Java interpreter installed on your
computer implements the Java VM. This interpreter takes your bytecode file and carries
out the instructions by translating them into instructions that your computer can
understand.
}
}
After typing the program, save it in a folder by giving the file name same as the class
name (here it is Test) with the extension .java.
for compiling the source file i.e. [Link] enter the following
command at Command Prompt - javac [Link]
Class Declaration
Every Java program must include the main() function declared like this:
public static void main(String[] args)
Conceptually, this is similar to the main() function in C / C++ and it's the entry point for
your application and will subsequently invoke all the other methods required by your
program. The main method declaration starts with three modifiers whose
meanings are given below :
public : means allows any class to call the main method
static : means that the main method is associated with the Test class as a whole instead
of operating on an instance or object of the class
void : indicates that the main method does not return a value As you can see from the
declaration of the main() function,
public static void main(String[] args)
it accepts a single argument i.e. String[] means an array of elements of type String. The
name of this array is args (for “arguments”).This array is the mechanism through which
the Java Virtual Machine passes information to your application.
The Output Line
The only executable statement in the program is
[Link]("I am A Simple Program!");
This is similar to the “printf()” statement of C or “cout <<“ of C++.
The printIn method is a member of the out object, which is a static
data member of System class. This line prints the string - I am A Simple Program!
to the screen. The method printIn always appends a newline character to the end of the
string. This means that every output will be start on a new line. Always remember that
every java statement must end with a semicolon.
JAVA TOKENS
The smallest individual units in a program are known as tokens. A Java program is
basically a collection of classes. There are five types of tokens in Java language. They
are: Keywords, Identifiers, Literals, Operators and Separators.
• Keywords: Keywords are some reserved words which have some definite meaning.
Java language has reserved 60 words as keywords. They cannot be used as variable
name and they are written in lower-case letter. Since Java is case-sensitive, one can use
thse word as identifiers by changing one or more letters to upper-case. But generally it
should be avoided. Java does not use many keywords of C/C++ language but it has some
new keywords which are not present in C/C++. A list of Java keywords are given in the
following table:
• Identifiers : Java Identifers are used for naming classes, methods, variables, objects,
labels in a program. These are actually tokens designed by programmers. There are a
few rules for naming the identifiers. These are:
• Identifier name may consists of alphabets, digits, dolar ($) character, underscore(_).
• Identifier name must not begin with a digit
• Upper case and lowercase letters are distinct.
• Blank space is not allowed in a identifier name.
• They can be of any length. While writing Java programs, the following naming
conventions should be followed by programmers :
∗ All local and private variables use only lower-case letters. Underscore is combined if
required. For example, total_marks average
∗ When more than one word are used in a name, the second and subsequent words are
marked with a leading upper-case letter. For example, dateOfBirth, totalMarks,
studentName
∗ Names of all public methods and interface variables start with a leading lower-case
letters. For example, total, average
∗ All classes and interfaces start with a leading upper-case letter. For example,
HelloJava Employee ComplexNumber
∗ Variables that represent constant values use all upper-case letters and underscore
between word if required. For example, PI RATE MAX_VALUE
• Literals: Literals in Java are a sequence of characters such as digits, letters and other
characters that represent constant values to be stored in a variable.
• Operators: An operator is a symbol that takes one or more arguments and opeates on
them to produce a result.
• Separators: Separators are symbols used to indicate where groups of code are
arranged and divided. Java separators are as follows: { } Braces ( ) Parentheses [ ]
Brackets ; Semicolon , Comma . Period
VARIABLES
A variable is an identifier that denotes a storage location where a value of data can be
stored. The value of a variable in a particular program may change during the execution
of the program.
In addition to the name and the type that we explicitly give to a variable, a variable has
scope. The section of code where the variable’s simple name can be used is the
variable’s scope. The variable’s scope is determined implicitly by the location of the
variable declaration, that is, where the declaration appears in relation to other code
elements. We will learn more about the scope of Java variables in this section. Java
variables are categorized into three groups according to their scope. These are: local
variable , instance variable and class variable.
• Local variables are variables which are declared and used inside [Link] the
method definition they are not available for use and so they are called local variables.
Local variables can also be declared inside program blocks that are defined between an
opening { and a closing brace }. These variables are visible to the program only.
• Instance variables are created when the class objects are instantiated. They can take
different values for each object.
• Class variables are global to a class and belong to the entire set of object that class
creates. Only one memory location is reserved for each class variable. Instance and class
variables are declared inside a class.
CONSTANTS
While a program is running, different values may be assigned to a variable at different
times (thus the name variable, since the values it contains can vary), but in some cases
we donot want this to happen. If we want a value to remain fixed, then we use a
constant. Constants in Java refer to fixed values that donot change during the execution
of a program. A constant is declared in a manner similar to a variable but with additional
reserved word final. A constant must be assigned a value at the time of its declaration.
Thus, the general syntax is:
Java supports several types of contants such as Integer constants, Real constants, Single
Character constants, String constants, Backslash Character constants.
• Integer constant : An integer constant refers to a sequence of dig its. For example,
Decimal integer constants: 5, -5, 0, 254321 Octal: 0, 025, 0125 Hexadecimal: 0X2,
0X9F, Ox etc.
Unicode System
DATA TYPES
Every variable must have a data type. A data type determines the values that the variable
can contain and the operations that can be performed on it. A variable’s type also
determined how its value is stored in the computer’s memory.
• Integer type Integer type can hold whole numbers like 1,2, 3,.... -4, 1996 etc. Java
supports four types of integer types: byte, short, int and long. It does not support
unsigned types and therefore all Java values are signed types. This means that they can
be positive or negative. For example, the int value 1996 is actually stored as the bit
pattern 00000000000000000000011111001100 as the binary equivalent of 1996 is
11111001100. Similary, we must use a byte type variable for storing a number like 20
instead of an int type. It is because that smaller data types require less time for
manipulation. We can specify a long integer by putting an ‘L’ or ‘l’ after the number. ‘L’
is preferred, as it cannot be confused with the digit ‘1’.
• Floating Point type Floating point type can hold numbers contaning fractorial parts
such as 2.5, 5.75, -2.358. i.e., a series of digits with a decimal point is of type floating
point. There are two kinds of floating point storage in Java. They are: float (Single-
precision floating point) and double(Doubleprecision floating point). In general, floating
point numbers are treated as double-precision quantities. To force them to be in single-
precision mode, we must append ‘f’ or ‘F’ to the numbers. For example, 5.23F, 2.25f
• Character type Java provides a character data type to store character constants in
memory. It is denoted by the keyword char. The size of char type is 2 bytes.
• Boolean type Boolean type can take only two values: true or false. It is used when we
want to test a particular condition during the execution of the program. It is denoted by
the keyword boolean and it uses 1 byte of storage.
The memory size and range of all eight primitive data types are given
In addition to eight primitive types, there are also three kinds of non-primitive types in
JAVA. They are also termed as reference or derived types. The non-primitive types are:
arrays, classes and interfaces. The value of a non-primitive type variable, in contrast to
that of a primitive type, is a reference to (an address of) the value or set of values
represented by the variable. These are discussed later as and when they are encountered.
Operators are special symbols that are commonly used in expressions. An operator
performs a function on one, two, or three operands. An operator that requires one
operand is called a unary operator. For example, ++ is a unary operator that increments
the value of its operand by 1. An operator that requires two operands is a binary
operator. For example, = is a binary operator that assigns the value from its righthand
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 12
CP1344: PROGRAMMING IN JAVA
operand to its left-hand operand. And finally, a ternary operator is one that requires three
operands. The Java programming language has one ternary operator (?:) .
Expressions are the simplest form of statement in Java that actually accomplishes
something. Expressions are statements that return a value. Many Java operators are
similar to those in other programming languages. Java supports most C++ operators. In
addition, it supports a few that are unique to it.
//Program 1: [Link]
public class OperatorDemo
{
public static void main(String[ ] args){
int a = 5, b =3;
double x = 25.50, y = 5.25;
[Link]("Variable values are :\n");
[Link](" a = " + a);
[Link](" b = " + b);
[Link](" x = " + x);
[Link](" y = " + y);
//Addition
[Link]("\nAddition...");
[Link](" a + b = " + (a + b));
Assignment Operators :
Assignment operators are used to assign the value of an expression to a variable. The
usual assignment operator is ‘=’. The general syntax is:
variableName = value;
For example, sum = 0; // 0 is assigned to the variable sum
x = x + 1;
Like C/C++, Java aslo supports the shorthand form of assignments. For example, the
statement x = x + 1; can be written as x += 1; in shorthand form.
These two expressions give very different results because of the difference between
prefix and postfix. When we use postfix operators (x++ or x--), y gets the value of x
before before x is incremented; using prefix, the value of x is assigned to y after the
increment has occurred.
Relational Operators :
Java has several expressions for testing equality and magnitude. All of these expressions
return a boolean value (that is, true or false). the relational operators:
Logical Operators :
Expressions that result in boolean values (for example, the Relational operators) can be
combined by using logical operators that represent the logical combinations AND, OR,
XOR, and logical NOT.
For AND operation, the && symbol is used. The expression will be true only if both
operands tests are also true; if either expression is false, the entire expression is false.
For OR expressions, the || symbol is used. OR expressions result in true if either or both
of the operands is also true; if both operands are false, the expression is false.
In addition, there is the XOR operator ^, which returns true only if its operands are
different (one true and one false, or vice versa) and false otherwise (even if both are
true).
For NOT, the ! symbol with a single expression argument is used. The value of the NOT
expression is the negation of the expression; if x is true, !x is false.
Bitwise Operators :
Bitwise operators are used to perform operations on individual bits in integers. Table 2.5
summarizes the bitwise operators available in the JAVA programming language. When
both operands are boolean, the bitwise AND operator (&) performs the same operation
as logical AND (&&). However, & always evaluates both of its operands and returns
true if both are true. Likewise, when the operands are boolean, the bitwise OR (|)
performs the same operation as is similar to logical OR (||). The | operator always
evaluates both of its operands and returns true if at least one of its operands is true.
When their operands are numbers, & and | perform bitwise manipulations
A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left. For example if op1 and op2 are two operands, then the statement
op1 << op2;
shift bits of op1 left by distance op2; fills with zero bits on the righthand side and op1 >>
op2; shift bits of op1 right by distance op2; fills with highest (sign) bit on the left-hand
side.
op1 >>> op2;
shift bits of op1 right by distance op2; fills with zero bits on the lefthand side. Each
operator shifts the bits of the left-hand operand over by the number of positions
indicated by the right-hand operand. The shift occurs in the direction indicated by the
operator itself. For example, the statement 25 >> 1; shifts the bits of the integer 25
to the right by one position. The binary representation of the number 25 is 11001. The
result of the shift operation of 11001 shifted to the right by one position is 1100, or 12 in
decimal
if (boolean_expression)
{
statement-block ;
}
statement;
The statement-block may be a single statement or a group of statements. If the boolean-
expression evaluates to true, then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement(after the closing
curly brace) will be executed. For example,
if (percentage>=40)
{
[Link](“Pass“);
}
In this case, if percentage contains a value that is greater than or equal to 40, the
expression is true, and println( ) will execute. If percentage contains a value less than 40,
then the println( ) method is bypassed. What if we want to perform a different set of
statements if the expression is false? We use the else statement for that.
The general syntax of if-else statement is:
if ( Boolean_expression )
statement; //executes when the expression is true
else
statement; //executes when the expression is false
Let us consider the same example but at this time the output should be Pass or Fail
depending on percentage of marks. i.e., if percentage is equal to or more than 40 then the
output should be Pass; otherwise Fail. This can be done by using an if statement along
with an else statement. Here is the segment of code :
if (percentage>=40)
[Link](“Pass”);
else
[Link](“Fail”);
When a series of decisions are involved, we may have to use more than one if-else
statements in nested form. The switch statement We have seen that when one of the
many alternatives is to be selected, we can design a program using if statements to
control the selection. However, the program becomes difficult to read and follow when
the number of alternatives increases. Like C/C++, JAVA has a built-in multiway
decision statement known as a switch. The switch statement provides variable entry
points to a block. It tests the value of a given variable or expression against a list of case
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 18
CP1344: PROGRAMMING IN JAVA
values and when a match is found, a block of statements associated with that case is
executed. The general form of switch statement is as follows :
switch( expression )
{
case value : statements;
break;
case value : statements
break;
...
default : statements // optional default section
break;
}
The expression is evaluated and compared in turn with each value prefaced by the case
keyword. The values must be constants (i.e., determinable at compile-time) and may be
of type byte, char, short, int, or long.
Looping
In looping, a sequence of statements are executed until some conditions for the
termination of the loop are satisfied. The process of repeatedly executing a block of
statements is known as looping. At this point, we should remember that Java does not
support goto statement. Like C/C++, Java also provides the three different statements for
looping. These are:
• while
• do-while
• for
The while and do-while statements We use a while statement to continually execute a
block while a condition remains true. The general syntax of the while statement is:
while(expression)
{
statement(s);
}
First, the while statement evaluates expression , which must return a boolean value. If
the expression returns true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression returns false. The Java programming language provides another statement
that is similar to the while statement : the do-while statement. The general syntax of do-
while is:
do
{
statement(s);
}while (expression);
Statements within the block associated with a do-while are executed at least once.
Instead of evaluating the expression at the top of the loop, do-while evaluates the
expression at the bottom. Here is the previous program rewritten to use do-while loop
A program of while loop is shown below :
class Fibo
{
public static void main(String args[])
{
[Link]("0\n1");
int n0=0,n1=1,n2=1;
while(n2<50)
{
[Link](n2);
n0=n1;
n1=n2;
n2=n1+n0;
}
[Link](n2);
}
}
The for statement The for statement provides a compact way to iterate over a range of
values. The general form of the for statement can be expressed like this:
for (initialization; termination_condition; increment)
{
statement(s);
}
The initialization is an expression that initializes the loop. It is executed once at the
beginning of the loop. The termination_condition determines when to terminate the loop.
This condition is evaluated at the top of each iteration of the loop. When the condition
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 20
CP1344: PROGRAMMING IN JAVA
evaluates to false, the loop terminates. Finally, increment is an expression that gets
invoked after each iteration through the loop. All these components are optional. In fact,
to write an infinite loop, we can omit all three expressions: for ( ; ; )
{
// infinite loop
}
Often, for loops are used to iterate over the elements in an array or the characters in a
string. The following program segment uses a for loop to calculate the summation of 1 to
50: for (i =1; i <= 50 ; i + +)
{
sum = sum + i ;
}
BRANCHING STATEMENTS
The Java programming language supports three branching statements:
• The break statement
• The continue statement
• The return statement
Break
The break statement In JAVA, the break statements has two forms: unlabelled and
labelled. We have seen the unlabelled form of the break statement used with switch
earlier. As noted there, an unlabelled break terminates the enclosing switch statement,
and the flow of control transfers to the statement immediately following the switch. It
can be used to terminate a for, while, or do-while loop. A break (unlabelled form)
statement, causes an immediate jump out of a loop to the first statement after its end.
When the break statement is encountered inside a loop, the loop is immediately exited
and the program continues with the statement immediately following the loop. When the
loop is nested, the break would only exit from the loop containing it. This means, the
break will exit only a single loop.
continue ;
A continue does not cause an exit from the loop. Instead, it immediately initiates the
next iteration. We can use the continue statement to skip the current iteration of a for,
while, or do-while loop. In Java, we can give a label to a block of statements. A label is
any valid Java variable name. To give a label to a loop, we have to place the label name
before the loop with a colon at the end. For example,
loop1: for( ...............)
{
.................
................
} ............... We have seen that a simple break statement causes the control to jump
outside the nearest loop and a simple continue statement returns the current loop. If we
want to jump outside a nested loop or to continue a loop that is outside the current one,
then we may have to use the labelled break and labelled continue statement. The labelled
form of break and continue can be used as follows:
[Link]
class breakDemo
{
public static void main(String[] args)
{
outer: for(int i=1;i<100;i++)
{
[Link](" ");
if(i>=10)
break;
for( int j=1;j<100;j++)
{
[Link]("* ");
if(j==i)
continue outer; //labelled continue
}
}
}
}
The return statement
The last of the branching statements is the return statement. We can use return to exit
from the current method. The flow of control returns to the statement that follows the
original method call. The return statement has two forms: one that returns a value and
one that does not.
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 22
CP1344: PROGRAMMING IN JAVA
To return a value, simply put the value (or an expression that calculates the value) after
the return keyword: return sum; The data type of the value returned by return must
match the type of the method’s declared return value. When a method is declared void,
use the form of return that does not return a value:
return;
Java Comments
The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
Comments are used to make the program more readable by adding the details of the
code.
It makes easy to maintain the code and to find the errors easily.
The comments can be used to provide information or explanation about the variable
, method, class , or any statement.
It can also be used to prevent the execution of program code while testing the alternative
code.
Types of Java Comments
There are three types of comments in Java.
CLASS FUNDAMENTALS
Classes provide a convenient method for grouping together logically related data items
and functions that work on them. A class can contain methods or functions, variables,
initialization code etc. In case of Java, the data items are termed as fields and the
functions are termed as methods.
Class serves as a blueprint for making class instances, which are runtime objects that
implement the class structure. Thus, an object is defined to be an instance of a class. An
object consists of attributes and behaviors. An attribute is a feature of the object,
something the object “has.” A behavior is something the object “does”.
Here, we can see that, there is no semicolon after closing brace of class in Java. But in
case of C++ language, class definition ends with a semicolon. The data or variables,
defined within a class are called fields or instance variables as each instance of the class
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 24
CP1344: PROGRAMMING IN JAVA
(that is, each object of the class) contains its own copy of these variables. Thus, the data
for one object is separate and unique from the data for another. The methods are used
for manipulating the instance variables(data items) contained in the class. The methods
and variables defined within a class are collectively called members of the class. A class
may contain three kinds of members: fields, methods and constructors. Constructor
specify how the objects are to be created. Java classes do not need to have a main( )
method. The general form of a class does not specify a main( ) method. We only specify
one if that class is the starting point for our program. The fields and methods of a class
appear within the curly brackets of the class declaration. A class may not contain
anything inside the curly brace { and }. Thus we can have empty classes in Java. An
empty class cannot do anything as it does not contain any properties. But it is possible to
create objects of such classes. The structure of an empty class is as follows:
class classname
{
}
Let us consider another class Triangle which has two float type instance variables base
and height.
class Triangle
{
float base; //instance variable base
float height; //instance variable height
}
Until object of Triangle class is created, there is no storage space has been created in the
memory for these two variables base and height. When an object of Triangle class is
created, memory will be allocated for each of these two fields.
The meaning of the keywords public, static etc. are already outlined in Unit-1. void
indicates that the main() method has no return value. In Java, the definition (often
referred to as the body) of a method must appear within the curly brackets that follow
the method declaration. For example, let us add two methods in the Triangle class.
class Triangle
{
float base, height;
void readData(float b, float h) //definition of method
{
base=b;
height=h;
}
float findArea( )//definition of another method
{
float area = 0.5*(base *height);
return area;
}
}
In the above code, the Triangle class demonstrates how to add methods to a class. In the
above class there are two methods, readData( ) and findArea( ). The method readData()
has a return type of void because it does not return any value. We pass two float type
values to the method which are then assigned to the instance variables base and height.
The method findArea() calculates area of the triangle and returns the result. Here, we can
directly use base and height inside the method readData() and findArea(). Let us
consider another method primeCheck() for the illustration of method. The following
program tests a boolean method that checks its arguments for primality. The main()
method prints those integers for which the checkPrime() returns true:
[Link]
class checkPrime
{
public static void main(String [ ] args)
{
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 26
CP1344: PROGRAMMING IN JAVA
for(int i=0;i<50;i++)
if(isPrime(i))
[Link](i+ " ");
[Link]();
}
static boolean isPrime(int n) //static method
{
if(n<2)
return false;
if(n==2)
return true;
if(n%2==0)
return false;
for(int j=3;j<=[Link](n);j=j+2)
if(n%j==0)
return false;
return true;
}
}
CREATING OBJECTS
It is important to remember that a class declaration only creates a template; it does not
create an actual object. Java allocates storage for an object when we create it with the
new operator. Creating an object is also referred to as instanting an object. The new
operator creates an object of the specified class and returns a reference to that object.
Thus, the preceding code does not cause any objects of type Triangle to come into
existence. To create a Triangle object, we will use a statement like the following:
Triangle t1 = new Triangle( ); //t1 is an object of Triangle class
Here, the Triangle( ) is the default constructor of the class. The above statement can also
be written by splitting it into to two statements. This can be written as follows :
Again, each time we create an instance of a class, we are creating an object that contains
its own copy of each instance variable defined by the class. Thus, every Triangle object
will contain its own copies of the instance variables base and height.
For example, suppose we have created t1 object with the following statement
: [Link]
class Triangle
{
double base, height;
void readData(double b, double h) //definition of method
{
base=b;
height=h;
}
double findArea( )//definition of another method
{
double a = 0.5*(base *height);
return a;
}
}
class Area //class with the main() method
{
public static void main(String args[ ])
{
double area1, area2;
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 28
CP1344: PROGRAMMING IN JAVA
If we write these two classes Triangle and Area into two separate files namely
[Link] and [Link], then these two files should be saved in the same folder in
the computer. To compile [Link] program, we must first compile the Triangle class
as:
javac [Link]
This will create the bytecode file [Link] in the same folder. Now, we can compile
and execute the [Link] file with the following statements:
javac [Link]
java Area
If we look at the contents of the folder, we will find four files: the source code and
bytecode for Triangle and the source code and bytecode for Area. The statements
Triangle t1=new Triangle();
Triangle t2=new Triangle();
will create two Triangle objects t1 and t2 in memory, which reserves memory for two
base fields , two height fields, two readData() methods and two findArea() methods.
They are distinguished by which reference we use. Each of the fields is initialized in
both objects using the dot operator with the following statements:
[Link]=20.5;
[Link]=15.5;
The Triangle reference t1 points to the Triangle object whose base is 20.5 and height is
15.5. The base and height field of t2 object is initialized to 30.0 and 15.0 with the
statement [Link](30.0,15.0); To compute the area of the triangle t1, we can use any
one of the following statements:
area1= [Link] * [Link];
area1=[Link]();
Similarly, for t2, we can use
area2=[Link] * [Link];
area2=[Link]();
CONSTRUCTORS
It would be simpler and more concise to initialize an object when it is first created. Java
supports constructors that enable an object to initialize itself when it is created. This
section provides a brief introduction about the Constructor and how constructors are
overloaded in Java. Constructor is always called by new operator. Constructors are
declared just like as we declare methods, except that the constructor does not have any
return type. The name of the constructors must be the same with the class name where it
is declared. It is called when a new class instance is created, which gives the class an
opportunity to set up the object for use. Constructors, like other methods, can accept
arguments and can be overloaded but they cannot be inherited. For example, let us
consider the same Triangle class. We can replace the readData() method by a
constructor. This can be accomplished as follows:
[Link]
class Triangle
{
double base, height;
Triangle(double b, double h) //constructor with two arguments
{
base=b;
height=h;
}
double findArea( ) //definition of method findArea()
{
double area = 0.5*(base *height);
return area;
}
}
class TriangleArea //class with the main() method
{
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 30
CP1344: PROGRAMMING IN JAVA
The Triangle class contains a single constructor. We can recognize a constructor because
its declaration uses the same name as the class and it has no return type. The constructor
in the Triangle class takes two arguments. The statement Triangle t1= new
Triangle(20.5, 15.5); provides 20.5 and 15.5 as values for those arguments.
{
double area = 3.14 *radius *radius;
return area;
}
}
class CircleArea //class with the main() method
{
public static void main(String args[ ])
{
double p_area,q_area;
Circle p = new Circle(); //invokes the default constructor
Circle q = new Circle(p); //invokes copy constructor
p_area= [Link]();
q_area =[Link]();
[Link]("Area of circle p = "+p_area);
[Link]("\nArea of circle q = "+q_area);
}
}
The statement Circle p = new Circle(); invokes the default constructor and it creates a
Circle object p with radius 10.0. The statement Circle q = new Circle(p); invokes the
copy constructor and it also creates another Circle object q with the same radius value
10.0. The object p and q are two separate but equal objects. In the output we can see that
the area of both the circles are same. All fields in a class will automatically be initialized
with their type’s default values unless the constructor explitcitly uses other values.
OVERLOADING OF CONSTRUCTORS
Overloading of constructors means multiple constructors in a single class. Program 3.4 is
also an example of constructor overloading as there are two constructors in that program.
Constructor can be overloaded provided they should have different arguments because
Java compiler differentiates constructors on the basis of arguments passed in the
constructor. Let us consider the following Rectangle class for the demonstration of
constructor overloading. After you going through it the concept of constructor
overloading will be more clear. to you. In the example below we have written four
constructors each having different arguments types.
[Link]
class Rectangle
{
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 32
CP1344: PROGRAMMING IN JAVA
int area2=[Link]();
[Link](“\nArea in second constructor: “ + area2);
Rectangle r3=new Rectangle(2.0f);
float area3=[Link]();
[Link](“\nArea in third constructor: “ + area3);
Rectangle r4=new Rectangle(3.0f,2.0f);
float area4=[Link]();
[Link](“\nArea in fourth constructor: “ + area4);
}
}
Constructor can also invoke other constructors with the this and super keywords. We
will discuss the first case here, and return to that of the superclass constructor after we
have talked more about subclassing and inheritance. A constructor can invoke another,
overloaded constructor in its class using the reference this() with appropriate arguments
to select the desired constructor. If a constructor calls another constructor, it must do so
as its first statement: this() calls another constructor in same class. Often a constructor
with few parameters will call a constructor with more parameters, giving default values
for the missing parameters. We can use this to call other constructors in the same class.
class Triangle
{
double base, height;
Triangle(double b,double h) {
base = b;
height=h;
}
Triangle(double b)
{
this(b, 20.50 );
}
}
In the above code, the class Triangle has two constructors. The first, accepts arguments
specifying the triangles’s base and height. The second constructor takes just the base as
an argument and, in turn, calls the first constructor with a default value 20.50 for height.
We have considered a simple example for clear understanding but the advantage of this
approach is that we can have a single constructor do all the complicated setup work;
other auxiliary constructors simply feed the appropriate arguments to that constructor.
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 34
CP1344: PROGRAMMING IN JAVA
The call to this() must appear as the first statement in our second constructor. It should
be remembered that we can invoke a second constructor only as the first statement of
another constructor.
• Formal and Actual parameter : We use the term formal parameters to refer to the
parameters in the definition of the method. In the example, width and height are the
formal parameters. We use the term actual parameters to refer to variables in the method
call. They are called “actual” because they determine the actual values that are sent to
the method. Let us consider what happens when we pass arguments to a method. In Java,
all primitive data types (e.g., int, char, float) are passed by value. The reference types
(i.e., any kind of object, including arrays and strings) are used through references. An
important distinction is that the references themselves (the pointers to these objects) are
actually primitive types and are passed by value too.
• Pass-by-Value Pass-by-value means that when we call a method, a copy of the value of
each actual parameter is passed to the method. We can change that copy inside the
method, but this will have no effect on the actual parameter. Unlike many other
languages, Java has no mechanism for changing the value of an actual parameter. Java
has eight primitive data types. Let us consider the following example for the
demonstration of pass-by-value:
[Link]
class PassPrimitiveByValue
{
public static void main(String[ ] args)
{
int p = 3;
[Link]("Before calling passValue, p = " + p);
passValue(p); //call passValue() with p as argument
[Link]("\nAfter calling passValue, p = " + p);
}
public static void passValue(int p) //passValue() definition to
{ //change the value of parameter
p = 10;
}
}
Here, we can see that the outputs are same before and after calling the method
passValue(). When Java calls a method, it makes a copy of its actual parameters’ values
and sends the copies to the method where they become the values of the formal
parameters. Then when the method returns, those copies are discarded and the actual
parameters have remained unchanged. Passing variables by value affords the
programmer some safety. Methods cannot unintentionally modify a variable that is
outside of its scope. However, we often want a method to be able to modify one or more
of its arguments. In the passValue() method, the caller wants the method to change the
value through its arguments. However, the method cannot modify its arguments, and,
furthermore, a method can only return one value through its return value. So, it is
necessary to learn how a method can return more than one value, or have an effect
(modify some value) outside of its scope. To allow a method to modify a argument, we
must pass in an object. Objects in Java are also passed by value; however, the value of
an object is a reference. So, the effect is that the object is passed in by reference. When
passing an argument by reference, the method gets a reference to the object. A reference
to an object is the address of the object in memory. Now, the local variable within the
method is referring to the same memory location as the variable within the caller. For
example, if a parameter to a method is an object reference. We can manipulate the object
in any way, but we cannot make the reference refer to a different object.
The first print statement displays “Rahul 2”. The second print statement displays “Anuj
1”. Thus the object has been changed in this case. The reference to obj is the parameter
to the method, so the method cannot be used to change that reference; i.e., it cannot
make obj reference a different Record. But the method can use the reference to perform
any allowed operation on the Record that it already references. It is often not good
programming style to change the values of instance variables outside an object.
Normally, the object would have a method to set the values of its instance variables
that allows a method to call itself. A method that calls itself is said to be recursive
method. One of the suitable examples of recursion is the computation of the factorial of
a number. The factorial of a number N is the product of all the whole numbers between 1
and N. for example, 4 factorial is 1×2×3×4, or 24. Here is how a factorial can be
computed by use of a recursive method.
[Link]
class findFactorial
{
public static void main(String [] args)
{
for(int i=1;i<=10;i++)
[Link]("Factorial("+ i +") =" + fact(i)); //method call
}
static long fact(int n)//method definition
{
if(n<2)
return 1;
return n*fact(n-1); //Recursive call
}
}
When fact() is called with an argument of 1, the function returns 1; otherwise it returns
the product of n* fact(n-1). To evaluate this expression, fact() is called with n-1. The
main advantage of recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives.
The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static keyword
belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
It makes program memory efficient (i.e., it saves memory).
o A static method can access static data member and can change the value of it.
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}}
class A{
void m(){[Link]("hello m");}
void n(){
[Link]("hello n");
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 41
CP1344: PROGRAMMING IN JAVA
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.
class A{
A(){[Link]("hello a");}
A(int x){
this();
[Link](x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Module II: Inheritance & Interface, Deriving Classes, Method Over-riding, Method
Overloading, Access Modifiers, Abstract Class and Method, Interfaces, Packages,
Imports and Class Path.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 43
CP1344: PROGRAMMING IN JAVA
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
In Java, a class can inherit attributes and methods from another class. The class that
inherits the properties is known as the sub-class or the child class. The class from which
the properties are inherited is known as the superclass or the parent class.
class Base
{
public void M1()
{
[Link](“ Base Class Method ”);
}
}
class Derived extends Base
{
public void M2()
{
[Link](“ Derived Class Methods “);
}
}
class Test
{
public static void main(String[] args)
{
Derived d = new Derived(); // creating object
d.M1(); // print Base Class Method
d.M2(); // print Derived Class Method
}
}
Derived Class/Sub-class: Derived class is a class that inherits from a base class. It is
also known as subclass or child class.
Base Class/Superclass: The base class is the main class where derived classes inherit
the features. It is also known as the superclass or parent class.
Reusability: The name itself says reuse the repeated code in the programs. It is a
mechanism to reuse existing code when you are creating new classes.
In Inheritance, we can access superclass methods and variables. We can also access
subclass methods and variables through subclass objects only. We have to take care of
superclass and subclass methods, and variable names shouldn’t conflict.
class A
{
int a, b;
void display()
{
[Link](“Inside class A values =”+a+” ”+b);
}
}
class B extends A
{
int c;
void show()
{
[Link](“Inside Class B values=”+a+” “+b+” “+c); }
}
class SingleInheritance
{
public static void main(String args[])
{
B obj = new B(); //derived class object
obj.a=10;
obj.b=20;
obj.c=30;
[Link]();
[Link]();
}
}
Java developers want to use multiple inheritances in some cases. Fortunately, Java
developers have interface concepts expecting the developers to achieve multiple
inheritances by using multiple interfaces.
We can take an example of three classes, class Vehicle, class Car, and class SUV. Here,
the class Vehicle is the grandfather class. The class Car extends class Vehicle and the
class SUV extends class Car.
In Hierarchical Inheritance in Java, more than one derived class extends a single base
class. In simple words, more than one child class extends a single parent class or a single
parent class has more than one child class.
class A {
public void print_A() { [Link]("Class A"); }
}
class B extends A {
public void print_B() { [Link]("Class B"); }
}
class C extends A {
public void print_C() { [Link]("Class C"); }
}
class D extends A {
public void print_D() { [Link]("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
inheritance is also not possible with classes. In java, hybrid inheritance can be achieved
only through Interfaces.
• Default superclass: Except Object class, which has no superclass, every class has
one and only one direct superclass (single inheritance). In the absence of any other
explicit superclass, every class is implicitly a subclass of the Object class.
• Superclass can only be one: A superclass can have any number of subclasses.
But a subclass can have only one superclass. This is because Java does not
support multiple inheritances with classes. Although with interfaces, multiple
inheritances are supported by java.
• Private member inheritance: A subclass does not inherit the private members of
its parent class. However, if the superclass has public or protected methods(like
getters and setters) for accessing its private fields, these can also be used by the
subclass.
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program
In this example, we have created two methods, first add() method performs addition of
two numbers and second add method performs addition of three numbers.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
class Animal{
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 54
CP1344: PROGRAMMING IN JAVA
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class
[Link]();
Polymorphism in Java
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and
method overriding.
In this example, we are creating two classes Bike and Splendor. Splendor class extends
Bike class and overrides its run() method. We are calling the run method by the
reference variable of Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method is invoked at runtime.
class Bike{
void run(){[Link]("running");}
[Link]();
static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.
If there is any private, final or static method in a class, there is static binding.
class Dog{
[Link]();
Dynamic binding
class Animal{
[Link]();
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false. If we apply the instanceof operator
with any variable that has null value, it returns false.
class Simple1{
A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Abstraction in Java
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.
Points to Remember
o It cannot be instantiated.
o It can have final methods which will force the subclass not to change the body of
the method.
A method which is declared as abstract and does not have implementation is known as
an abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Java Interface also represents the IS-A relationship.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
to declare an interface
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
Example
Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java 8, it
can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
8) A Java abstract class can have class Members of a Java interface are
members like private, protected, etc. public by default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){[Link]("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest
of the methods
class M extends B{
public void a(){[Link]("I am a");}
public void b(){[Link]("I am b");}
public void d(){[Link]("I am d");}
}
Java Package
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
2) Using [Link]
If you import [Link] then only declared class of this package will be
accessible.
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
It is generally used when two packages have same class name e.g. [Link] and
[Link] packages contain Date class.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
class A{
private A(){}//private constructor
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 68
CP1344: PROGRAMMING IN JAVA
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit, for example, a capsule which is mixed of several medicines.
A fully encapsulated class in Java can be created by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.
It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is
easy and fast to create an encapsulated class in Java.
Module III: Exception Handling, The Try-Catch Statement, Catching more than one
Exception, The Finally Clause, Generating Exceptions, Threads: Introduction, Creating
Threads in Applications, Method in Thread Class, Threads in Applets.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. In Java, an exception
is an event that disrupts the normal flow of the program. It is an object which is thrown
at runtime. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc. The
core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application.
The [Link] class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.
If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute.
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
[Link]
public class TryCatchExample3 {
{
[Link](e);
}
if an exception occurs in the try block, the rest of the block code will not execute.
try{
int a[]=new int[5];
a[5]=30/0;
}
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 77
CP1344: PROGRAMMING IN JAVA
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Example 2
try{
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 78
CP1344: PROGRAMMING IN JAVA
In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception is
pushed onto the stack.
}
catch(Exception e1)
{
//exception message
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 79
CP1344: PROGRAMMING IN JAVA
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
an example where we place a try block within another try block for two different
exceptions.
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
Here the try block within nested try block (inner try block 2) do not handle the
exception. The control is then transferred to its parent try block (inner try block 1). If it
does not handle the exception, then the control is transferred to the main try block (outer
try block) where the appropriate catch block handles the exception. It is termed as
nesting.
[Link]
[Link](arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
[Link]("Arithmetic exception");
[Link](" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
[Link]("Arithmetic exception");
[Link]("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
[Link](e4);
[Link](" outer (main) try block");
}
catch (Exception e5) {
[Link]("Exception");
[Link](" handled in main try-block");
}
}
}
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
[Link](data);
}
//catch won't be executed
catch(NullPointerException e){
[Link](e);
}
//executed regardless of exception occurred or not
finally {
[Link]("finally block is always executed");
}
try {
try {
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related to
user inputs, server, etc.
The syntax of the Java throw keyword is given below.
[Link]
the validate method that takes integer value as a parameter. If the age is less than
18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.
21) static boolean interrupted() It tests whether the current thread has
been interrupted.
Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the other
is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant of
time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 89
CP1344: PROGRAMMING IN JAVA
slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other
threads can also run for their slice of time. Whenever such a scenario occurs, all those
threads that are willing to run, waiting for their turn to run, lie in the runnable state. In
the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running
and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using the
printer to print some data. Therefore, thread A has to wait for thread B to use the printer.
Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform
any execution and thus never consume any cycle of the Central Processing Unit (CPU).
Hence, we can say that thread A remains idle until the thread scheduler reactivates
thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in
the waiting state. The main thread then waits for the child threads to complete their
tasks. When the child threads complete their job, a notification is sent to the main thread,
which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and the
chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the time
runs out, the thread wakes up and start its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 90
CP1344: PROGRAMMING IN JAVA
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.
It represents the runnable [Link] means a thread is waiting in the queue to run.
It represents the blocked state. In this state, the thread is waiting to acquire a lock.
It represents the waiting state. A thread will go to this state when it invokes the
[Link]() method, or [Link]() method with no timeout. A thread in the waiting
state is waiting for another thread to complete its task.
5. public static final [Link] TIMED_WAITING
It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has
the time constraint. A thread invoking the following method reaches the timed waiting
state.
o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
}
}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
Hierarchy of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
To execute the applet by html file, create an applet and compile it. After that create an
html file and place the applet code in html file. Now click the html file.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color
to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.
import [Link];
import [Link].*;
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 97
CP1344: PROGRAMMING IN JAVA
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Image picture;
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the Component
class.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.
Example of animation in applet:
import [Link].*;
import [Link].*;
public class AnimationExample extends Applet {
Image picture;
try{[Link](100);}catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the Component
class.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on the
button.
Example of EventHandling in applet:
import [Link].*;
import [Link].*;
import [Link].*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
b=new Button("Click");
[Link](80,150,60,50);
add(b);add(tf);
[Link](this);
setLayout(null);
}
}
}
In the above example, we have created all the controls in init() method because it is invoked only
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Module IV: Java APIs – overview of APIs, IO Packages, Java Input Stream Classes,
Java Output Stream Classes, File Class, Graphic & Sound: AWT and Swing, Graphic
methods, Fonts, Loading and Viewing Images, Loading and Playing Sound, AWT &
Event Handling, Layouts, JDBC.
Java APIs
Java APIs are integrated pieces of software that come with JDKs. APIs in Java provides
the interface between two different applications and establish communication.
Java Scanner
Scanner class in Java is found in the [Link] package. Java provides various ways to
read input from the keyboard, the [Link] class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.
The Java Scanner class is widely used to parse text for strings and primitive types using
a regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call
next().charAt(0) method which returns a single character.
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package
contains all the classes required for input and output operations.
Stream
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Java Output
[Link](); or
[Link](); or
[Link]();
Here,
class AssignmentOperator {
Output:
println() - It prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
Java Input
Java provides different ways to get input from the user. However, in this tutorial, you
will learn to get input from user using the object of Scanner class.
import [Link];
// create an object of Scanner
Scanner input = new Scanner([Link]);
class Input {
public static void main(String[] args) {
The BufferedReader class of the [Link] package can be used with other readers to read
data (in characters) more efficiently.
Working of BufferedReader
During the read operation in BufferedReader, a chunk of characters is read from the disk
and stored in the internal buffer. And from the internal buffer characters are read
individually.
Hence, the number of communication to the disk is reduced. This is why reading
characters is faster using BufferedReader.
Create a BufferedReader
// Creates a FileReader
FileReader file = new FileReader(String file);
// Creates a BufferedReader
BufferedReader buffer = new BufferedReader(file);
In the above example, we have created a BufferedReader named buffer with the
FileReader named file.
Here, the internal buffer of the BufferedReader has the default size of 8192 characters.
However, we can specify the size of the internal buffer as well.
class Main {
try {
// Creates a FileReader
FileReader file = new FileReader("[Link]");
// Creates a BufferedReader
BufferedReader input = new BufferedReader(file);
// Reads characters
[Link](array);
[Link]("Data in the file: ");
[Link](array);
catch(Exception e) {
[Link]();
}
}
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The [Link] package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to
place every component in a particular position on a screen, we need to add them to a
container.
Container
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known as
container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.
Types of containers:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window. We need to create an instance of
Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text
field etc. An instance of Panel class creates a container, in which we can add
components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It
can have other components like button, text field, scrollbar etc. Frame is most widely
used container while developing an AWT application.
To create simple AWT example, you need a frame. There are two ways to create a GUI
using Frame in AWT.
// creating a button
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 111
CP1344: PROGRAMMING IN JAVA
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
}
}
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The [Link] package provides many event classes and
Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
[Link](this);//passing current instance
new AEvent();
}
}
2. Button (String text) It constructs a new button with given string as its
label.
1. void setText (String text) It sets the string message on the button
3. void setLabel (String label) It sets the label of button with the
specified string.
In the following example, we are handling the button click events by implementing
ActionListener Interface.
[Link]
[Link](50,50, 150,20);
// create instance of button with label
Button b=new Button("Click Here");
// set the position for the button in frame
[Link](50,100,60,30);
[Link](new ActionListener() {
public void actionPerformed (ActionEvent e) {
[Link]("Welcome to Java programming.");
}
});
// adding button the frame
[Link](b);
// adding textfield the frame
[Link](tf);
// setting size, layout and visibility
[Link](400,400);
[Link](null);
[Link](true);
}
}
Java AWT Label
The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a
user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To create
a label, we need to create the object of Label class.
AWT Label Class Declaration
1. public class Label extends Component implements Accessible
[Link]
import [Link].*;
4. TextField(String text, int It constructs a new text field with the given
columns) text and given number of columns (width).
Class constructors:
2. TextArea (int row, int column) It constructs a new text area with
specified number of rows and columns
and empty string as text.
4. TextArea (String text, int row, int It constructs a new text area with the
column) specified text in the text area and
specified number of rows and columns.
5. TextArea (String text, int row, int It construcst a new text area with
column, int scrollbars) specified text in text area and specified
number of rows and columns and
visibility.
[Link]
// class constructor
ChoiceExample2() {
// creating a frame
Frame f = new Frame();
// creating a button
Button b = new Button("Show");
[Link](400, 400);
[Link](null);
[Link](true);
// main method
public static void main(String args[])
{
new ChoiceExample2();
}
}
2. void add(String item, int index) It adds the specified item into list at
the given index position.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
3 Scrollbar(int orientation, int value, int Constructs a new scroll bar with the
visible, int minimum, int maximum) specified orientation, initial value,
visible amount, and minimum and
maximum values.
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the
registered component.
1. public abstract void actionPerformed(ActionEvent e);
to write ActionListener
The common approach is to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps:
[Link](instanceOfListenerclass);
3) Override the actionPerformed() method:
The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent. The MouseListener interface is found in [Link]
package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 130
CP1344: PROGRAMMING IN JAVA
import [Link].*;
import [Link].*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
File: [Link]
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
JButton class declaration
the declaration for [Link] class.
Constructor Description
Methods Description
button.
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.
JLabel class declaration
Let's see the declaration for [Link] class.
1. public class JLabel extends JComponent implements SwingConstants, Accessibl
e
Constructor Description
Methods Description
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
JTextField class declaration
Let's see the declaration for [Link] class.
1. public class JTextField extends JTextComponent implements SwingConstants
Constructor Description
Methods Description
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();
int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
c=a-b;
}
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
JTextArea class declaration
Let's see the declaration for [Link] class.
1. public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
initially.
JTextArea(int row, int column) Creates a text area with the specified number
of rows and columns that displays no text
initially.
JTextArea(String s, int row, int Creates a text area with the specified number
column) of rows and columns that displays specified
text.
Methods Description
void insert(String s, int position) It is used to insert the specified text on the
specified position.
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password
entry. It allows the editing of a single line of text. It inherits JTextField class.
Constructor Description
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on
(true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or
from "off" to "on ".It inherits JToggleButton class.
JCheckBox class declaration
Let's see the declaration for [Link] class.
1. public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query
with the database. But, ODBC API uses ODBC driver which is written in C language
(i.e. platform dependent and unsecured). That is why Java has defined its own API
(JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the
following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
API
API (Application programming interface) is a document that contains a description of
all the features of a product or software. It represents classes and interfaces that
software programs can follow to communicate with each other. An API can be
created for applications, libraries, operating systems, etc.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with
the database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
Bachelor in Computer Applications, UNIVERSITY OF KERALA Page 140
CP1344: PROGRAMMING IN JAVA
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
Advantage:
o No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException
throws SQLException
Example to establish connection with the Oracle database
1. Connection con=[Link](
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method
1. public void close()throws SQLException
Example to close connection
1. [Link]();
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may also use
IP address, 3306 is the port number and sonoo is the database name. We may use
any database, in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.