Java Notes (Nep Syllabus)
Java Notes (Nep Syllabus)
What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language used to develop all kind of
applications.
History:
1
2
• JSP - In Java, JSP (Java Server Pages) is used to create dynamic web pages,
such as in PHP and ASP.
• Applets - Applets are another type of Java programs that are implemented on
Internet browsers and are always run as part of a web document.
• J2EE - Java 2 Enterprise Edition is a platform-independent environment that
is a set of different protocols and APIs and is used by various organizations
to transfer data between each other.
• JavaBeans - This is a set of reusable software components that can be easily
used to create new and advanced applications.
• Mobile - In addition to the above technology, Java is widely used in mobile
devices nowadays, many types of games and applications are being made in
Java.
2
3
Java application programs written in one Operating system can able to run
on any Operating system.
• Simple - Java has included many features of C / C ++, which makes it easy
to understand.
• Secure - Java provides a wide range of protection from viruses and
malicious programs. It ensures that there will be no damage and no security
will be broken.
• Portable - Java provides us with the concept of portability. Running the
same program with Java on different platforms is possible.
• Robust - During the development of the program, it helps us to find possible
mistakes as soon as possible.
• Multi-threaded - The multithreading programming feature in Java allows
you to write a program that performs several different tasks simultaneously.
• Distributed - Java is designed for distributed Internet environments as it
manages the TCP/IP protocol.
You will need a text editor to write Java programs. There is even more
sophisticated IDE available in the market. But for now, you can consider one of the
following:
• Notepad - On Windows machine, you can use any simple text editor like
Notepad (Recommended for this tutorial), TextPad.
• Netbeans - is a Java IDE that is open source and free which can be
downloaded from http://www.netbeans.org/index.html
• Eclipse - is also a java IDE developed by the Eclipse open source
community and can be downloaded from http://www.eclipse.org/
Object - Objects have states and behaviors. Example: A dog has states-color,
3
4
Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram
{
public static void main(String[]args)
{
System.out.println("Hello World"); // prints Hello World
}
}
Please follow the steps given below to compile and run java program:
Open a command prompt window and go o the directory where you saved the
class. Assume it's C:\.
Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next
line(Assumption : The path variable is set).
4
5
You will be able to see ' Hello World ' printed on the window.
Case Sensitivity - Java is case sensitive, which means identifier Hello and
hello would have different meaning in Java.
Class Names - For all class names, the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first
letter should be in Upper Case. Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case. Example public void myMethodName()
Program File Name - Name of the program file should exactly match the class
name. When saving the file, you should save it using the class name
(Remember Java is case sensitive) and append '.java' to the end of the name (if
the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name, then the file should
be saved as'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program processing starts from
the main() method, which is a mandatory part of every Java program.
5
6
JAVA ENVIRONMENT
1) What is JVM ?
• Reading Bytecode.
• Verifying bytecode.
• Linking the code with the library
2) What is JDK ?
• Basic Tools
• Remote Method Invocation (RMI) Tools
• Internationalization Tools
• Security Tools
• Java IDL Tools
6
7
Javac
javac is the compiler for the Java programming language; it's used to compile .java
file. It creates a class file which can be run by using java command.
c: javac TestFile.java
Javadoc
JavaDoc is an API documentation generator for the Java language, which generates
documentation in HTML format from Java source code.
Appletviewer
appletviewer run and debug applets without a web browser, its standalone
command-line program to run Java applets.
Jar
The jar is (manage Java archive) a package file format that contains class, text,
images and sound files for a Java application or applet gathered into a single
compressed file.
3) What is JRE ?
You need JRE to execute your program, which includes two things:
• JVM
• Java Library
o Static - Functions that are required at compile time.
7
8
In detail, the JRE consists of various components; these are listed below:
User Interface Toolkit includes Abstract Window Toolkit (AWT), Swing, Image
Input / Output, Accessibility, drag and drop, etc.
Lang and util base libraries, including lang and util, management, versioning,
collections, etc.
JAVA FUNDAMENTALS
JAVA TOKENS
Java Tokens are the smallest individual building block or smallest unit of a Java
program; the Java compiler uses it for constructing expressions and statements.
Java program is a collection of different types of tokens, comments, and white
spaces.
Reserved Keywords
Identifiers
Literals
8
9
Operators
Separators
White space is also considered as a token
JAVA KEYWORDS
Keywords are words that have already been defined for Java compiler. They have
special meaning for the compiler. Java Keywords must be in your information
because you can not use them as a variable, class or a method name.
You can't use keyword as identifier in your Java programs, its reserved words in
Java library and used to perform an internal operation.
true, false and null are not reserved words but cannot be used as identifiers,
because it is literals of built-in types
9
10
JAVA OPERATORS
Java operators are symbols that are used to perform mathematical or logical
manipulations. Java is rich with built-in operators.
Operators are tokens that perform some calculations when they are applied to
variables.
• Arithmetic Operators
• Unary Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Conditional Operator
• instanceof Operator
ARITHMETIC OPERATOR
The way we calculate mathematical calculations, in the same way, Java provides
arithmetic operators for mathematical operations. It provides operators for all
necessary mathematical calculations.
There are various arithmetic operators used in Java:
10
11
In Java, unary arithmetic operators are used to increasing or decreasing the value
of an operand. Increment operator adds 1 to the value of a variable, whereas the
decrement operator decreases a value.
Syntax
val++;
val--;
These two operators have two forms: Postfix and Prefix. Both do increment or
decrement in appropriate variables. These two operators can be placed before or
after of variables. When it is placed before the variable, it is called prefix. And
when it is placed after, it is called postfix.
Example Description
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".
11
12
RELATIONAL OPERATORS
The Java Relational operators compare between operands and determine the
relationship between them.
• == is the equality operator. This returns true if both the operands are
referring to the same object, otherwise false.
• != is for non-equality operator. It returns true if both the operands are
referring to the different objects, otherwise false.
• < is less than operator.
• >is greater than operator.
• <= is less than or equal to operator.
• >= is greater than or equal to operator..
•
RELATIONAL OPERATORS
The Java Logical Operators work on the Boolean operand. It's also called Boolean
logical operators. It operates on two Boolean values, which return Boolean values
as a result.
Operator Meaning Work
&& Logical AND If both operands
are true then only "logical
AND
operator" evaluate true.
|| Logical OR The logical
OR operator is only
evaluated as true when
one of its operands
evaluates true. If either or
both expressions evaluate
to true, then the result is
true.
! Logical Not Logical NOT is a Unary
Operator, it operates on
single operands. It
12
13
BITWISE OPERATORS
The Java Bitwise Operators allow access and modification of a particular bit inside
a section of the data. It can be applied to integer types and bytes, and cannot be
applied to float and double.
13
14
ASSIGNMENT OPERATORS
The Java Assignment Operators are used when you want to assign a value to the
expression. The assignment operator denoted by the single equal sign =.
In a Java assignment statement, any expression can be on the right side
and the left side must be a variable name. For example, this does not mean that "a"
is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:
Syntax
variable = expression;
operator Description example
= Simple assignment operator, C = A + B will assign
Assigns value of A + B into C
values from right side
operands to left
side operand
+= Add AND assignment C += A is equivalent
operator, It adds to C = C + A
right operand to the left
operand and
assign the result to left
operand
-= Subtract AND assignment C -= A is equivalent
14
15
operator, It to C = C - A
subtracts right operand from
the left
operand and assign the
result to left
operand
*= Multiply AND assignment C *= A is equivalent
operator, It to C = C * A
multiplies right operand
with the left
operand and assign the
result to left
operand
/= Divide AND assignment C /= A is equivalent
operator, It to C = C / A
divides left operand with the
right
operand and assign the
result to left
operand
%= Modulus AND assignment C %= A is equivalent
operator, It to C = C % A
takes modulus using two
operands and
assign the result to left
operand
<<= Left shift AND assignment C <<= 2 is same as C
operator = C << 2
>>= Right shift AND assignment C >>= 2 is same as C
operator = C >> 2
&= Bitwise AND assignment C &= 2 is same as C
operator =C&2
^= bitwise exclusive OR and C ^= 2 is same as C
assignment =C^2
operator
15
16
CONDITIONAL OPERATORS
The Java Conditional Operator selects one of two expressions for evaluation,
which is based on the value of the first operands. It is also called ternary operator
because it takes three arguments.
The conditional operator is used to handling simple situations in a line.
Syntax
expression1 ? expression2:expression3;
The above syntax means that if the value given in Expression1 is true, then
Expression2 will be evaluated; otherwise, expression3 will be evaluated.
Example:
val == 0 ? you are right:you are not right;
INSTANCEOF OPERATOR
The Java instanceof Operator is used to determining whether this object belongs to
this particular (class or subclass or interface) or not.
This operator gives the boolean values such as true or false. If it relates to a
specific class, then it returns true as output. Otherwise, it returns false as output.
Syntax:
object-reference instanceof type;
16
17
Example
class Company {}
System.out.println("Success.");
if (c instanceof Employee) {
Employee b1 = (Employee) c;
b1.check();
Employee.view(c);
precedence than others; for example, the multiplication operator has higher
17
18
assigned 13, not 20 because operator * has higher precedence than +, so it first
gets multiplied with 3*2 and then adds into 7. Here, operators with the highest
precedence appear at the top of the table, those with the lowest appear at the
first.
Category Operator Associativity
Postfix () [] . Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >>>>><< Left to right
Relational >>= <<= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left
>>=
<<= &= ^= |=
Comma , Left to right
18
19
DATA TYPES
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory
assigning different data types to variables, you can store integers, decimals, or
There are eight primitive data types supported by Java. Primitive data types
are predefined by the language and named by a keyword. Let us now look into
detail about the eight primitive data types.
byte:
Byte data type is an 8-bit signed two's complement integer.
19
20
short:
Short data type is a 16-bit signed two's complement integer.
int:
• int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• Int is generally used as the default data type for integral values unless
• there is a concern about memory.
• The default value is 0.
• Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
20
21
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
• This data type is generally used as the default data type for decimal
• values, generally the default choice.
• Double data type should never be used for precise values such as
• currency.
• Default value is 0.0d.
• Example: double d1 = 123.4
boolean:
boolean data type represents one bit of information.
char:
char data type is a single 16-bit Unicode character.
21
22
• Class objects and various types of array variables come under reference
• data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared
• type or any compatible type.
• Example: Animal animal = new Animal("giraffe");
JAVA VARIABLES
Variables are the identifier of the memory location, which used to save data
temporarily for later use in the program. During execution of a program, values can
be stored in a variable, and the stored value can be changed. In Java programming,
it is necessary to declare the variable before being used.
Declaration of variables
Declaring a variable means what kind of data it will store. Variables
display named storage locations, whose values can be changed during the
execution of the program. It is the basic unit of storage in a Java program.
Syntax:
type variable_name;
or
type variable_name, variable_name, variable_name;
22
23
Here's the meaning of type is a data type. It specifies what type of data the
variable will hold.
Example:
// variable definition
int width, height=5;
char letter='C';
float age, area;
double d;
INITIALIZATION OF VARIABLES
Static - This means that the memory is determined for variables when the
program starts.
Dynamic - Dynamic means that in Java, you can declare variables anywhere
in the program, because when the statement is executed the memory is
assigned to them.
Example:
// actual initialization
width = 10;
age = 26.5;
23
24
• A variable name can consist of Capital letters A-Z, lowercase letters a-z,
digits 0-9, and two special characters such as underscore and dollar Sign.
• The first character must be a letter.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• Variable names are case-sensitive.
SCOPE OF VARIABLES
Variable Scope means - That limit, as far as the variable can be used.
In Java there are various types of variable scope:
• Local variables
• Instance variables
• Class/Static variables
LOCAL VARIABLES
A variable that is declared within the method that is called local variables. It is
defined in method or other statements, such as defined and used within the cache
block, and outside the block or method, the variable cannot be used.
INSTANCE VARIABLES
A non-static variable that is declared within the class but not in the method is
called instance variable. Instance variables are related to a specific object; they can
access class variables
CLASS/STATIC VARIABLES
A variable that is declared with static keyword in a class but not in the method is
called static or class variable.
Example:
class A {
24
25
Example1:
salary = 10000;
eg.show();
25
26
class A{
A obj=new A();
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. If you don't use any modifier, it is treated as default by
default.
26
27
/save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
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.
//save by A.java
package pack;
public class A{
27
28
//save by B.java
package mypack;
import pack.*;
class B extends A{
obj.msg();
package pack;
public class A{
28
29
package mypack;
import pack.*;
class B{
obj.msg();
29
30
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java. Like C/C++, we can also
create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
2) Multidimensional Array
30
31
dataType arr[];
arrayRefVar=new datatype[size];
class Testarray{
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
31
32
System.out.println(a[i]);
}}
In such case, data is stored in row and column based index (also known as matrix
form).
dataType []arrayRefVar[];
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
32
33
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class Testarray3{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
System.out.println();
}}
33
34
provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements. It is one of the fundamental features
of Java, which provides a smooth flow of program.
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
34
35
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression
and control the program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the If
statement gives a Boolean value, either true or false. In Java, there are four types of
if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of code if
the expression evaluates to true.
if(condition) {
35
36
Consider the following example in which we have used the if statement in the java
code.
//Student.java
int x = 10;
int y = 12;
}
2) if-else statement
is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax:
if(condition) {
else{
36
37
3) if-else-if ladder:
if(condition 1) {
else if(condition 2) {
else {
4. Nested if-statement
37
38
if(condition 1) {
if(condition 2) {
else{
}
Consider the following example.
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
}else if(address.contains("Noida")) {
}else {
System.out.println(address.split(",")[0]);
}else {
38
39
Output:
Delhi
5) Switch Statement:
In Java, Switch statements
are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
Break statement terminates the switch block when the condition is satisfied.
While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
39
40
case value1:
statement1;
break;
case valueN:
statementN;
break;
default:
default statement;
Consider the following example to understand the flow of the switch statement.
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
40
41
break;
default:
System.out.println(num);
While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value. The switch
permits only int, string, and Enum type variables to be used.
LOOP STATEMENTS
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the
set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. for-each loop
3. while loop
4. do-while loop
41
42
is similar to C
and C++
//block of statements
Consider the following example to understand the proper functioning of the for
loop in java.
int sum = 0;
sum = sum + j;
42
43
Consider the following example to understand the functioning of the for-each loop
in Java.
for(String name:names) {
System.out.println(name);
43
44
is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
while(condition){
//looping statements
} .
int i = 0;
44
45
while(i<=10) {
System.out.println(i);
i = i + 2;
checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
do
//statements
} while (condition);
Consider the following example to understand the functioning of the do-while loop
in Java.
45
46
int i = 0;
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e.,
break and continue.
is used to break the current flow of the program and transfer the control to the next
statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.
46
47
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement
with the for loop.
BreakExample.java
System.out.println(i);
if(i==6) {
break;
47
48
a:
b:
for(int j = 0; j<=15;j++) {
c:
System.out.println(k);
if(k==5) {
break a;
} }}}}
doesn't break the loop, whereas, it skips the specific part of the loop and jumps to
the next iteration of the loop immediately.
48
49
if(j == 4) {
continue;
System.out.println(j);
Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same results.
This relaxation permits implementation with better-performance where strict
reproducibility is not required.
If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an
ArithmeticException.
For other arithmetic operations like increment, decrement, divide, absolute value,
and negation overflow occur only with a specific minimum or maximum value. It
should be checked against the maximum and minimum value as appropriate. Java
Math Methods
49
50
The java.lang.Math class contains various methods for performing basic numeric
operations such as the logarithm, cube root, and trigonometric functions etc. The
various java math methods are as follows:
Math.abs()
Math.max()
Math.min()
Math.round()
Math.sqrt()
Math.cbrt()
Math.pow()
It returns the value of first argument raised to the power to second argument.
Math.signum()
Math.ceil()
50
51
It is used to find the smallest integer value that is greater than or equal to the
argument or mathematical integer.
Math.copySign()
It is used to find the Absolute value of first argument along with sign specified in
second argument.
Math.nextAfter()
It is used to return the floating-point number adjacent to the first argument in the
direction of the second argument.
Math.nextUp()
Math.nextDown()
Math.floor()
It is used to find the largest integer value which is less than or equal to the
argument and is equal to the mathematical integer of a double value.
Math.floorDiv()
It is used to find the largest integer value that is less than or equal to the algebraic
quotient.
Math.random()
It returns a double value with a positive sign, greater than or equal to 0.0 and less
than 1.0.
Math.rint()
It returns the double value that is closest to the given argument and equal to
mathematical integer.
51
52
Java Methods
In general, a method is a way to perform some task. Similarly, the method in Java
is a collection of instructions that performs a specific task. It provides the
reusability of code. We can also easily modify code using methods. In this section,
we will learn what is a method in Java, types of methods, method declaration, and
how to call a method in Java.
The most important method in Java is the main() method. If you want to read more
about the main() method, go through the link https://www.javatpoint.com/java-
main-method
Syntax
modifier returnType NameofMethod(Parameter List) {
// method body
}
52
53
Example:
public static int funie(int g, int d) {
// body of the method
}
Here, public static are modifiers where: public sets the visibility of the method,
statics used so that this method is shared among all instances of the class it belongs
to; int specifies the type of value method will return, i.e. the return type; funie is
the name of method used here, g and d is the formal parameters' list of type integer.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must be
subtraction(). A method is invoked by its name.
Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.
53
54
Types of Method
There are two types of methods in Java:
1. Predefined Method
2. User-defined Method
Predefined Methods
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them
in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the
background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method
is defined in the java.io.PrintStream class. It prints the statement that we write
inside the method. For example, print("Java"), it prints Java on the console.
Example
54
55
User-defined Method
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we
will define the method.
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
We have defined the above method named findevenodd(). It has a parameter num
of type int. The method does not return any value that's why we have used void.
The method body contains the steps to check the number is even or odd. If the
number is even, it prints the number is even, else prints the number is odd.
55
56
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
5. Classes
6. Objects
7. Message Parsing
1) Object
Java Object
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
2) Class
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
3) Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
4) Polymorphism
56
57
5) Abstraction
6) Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here
7) Message Passing
OBJECTS
In real-world an entity that has state and its behavior is known as an object.
For Example:
A Car is an object. It has states (name, color, model) and its behavior (changing
gear, applying brakes).
A Pen is an object. Its name is Parker; color is silver etc. known as its state. It is
used to write, so writing is its behavior.
57
58
SYNTAX OF OBJECT
CLASSES
The member functions determine the behavior of the class, i.e. provide a
definition for supporting various operations on data held in the form of an
object.
SYNTAX
Data Members;
Methods;
58
59
EXAMPLE
public:
The members that are declared private can be accessed only from within the class.
CLASS MEMBERS
Data Members and methods must be declared within the class definition.
EX:
59
60
Constructors in Java:
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
60
61
In this example, we are creating the no-arg constructor in the Bike class. It
will be invoked at the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
61
62
62
63
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
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its name
differs.
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{
63
64
class TestOverloading1{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
In this example, we have created two methods that differs in data type
. The first add method receives two integer arguments and second add method
receives two double arguments.
class Adder{
class TestOverloading2{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
64
65
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of
the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.
class Vehicle{
//defining a method
65
66
obj.run();//calling method
1. variables
2. methods
3. initialization - block
4. nested class
66
67
• Class
• Constructor
• Local inner classes
• Inner class methods
• Instance variables
• Local Variables
• Interfaces
RULES FOR USING STATIC VARIABLES
• For referring current class instance variable, this keyword can be used
• To invoke current class constructor, this() is used
• this can be passed as message argument in a method call
• In a constructor call, this can be passed as argument
• For returning current class instance, this keyword is used.
67
68
Example
class Emp {
int e_id;
String name;
super and final keywords are two popular and useful keywords in Java. They
also play a significant role in dealing with Java programs and their classes. In this
chapter, you will learn about how to use super and final within a Java program.
SUPER KEYWORD
68
69
Super is a keyword of Java which refers to the immediate parent of a class and is
used inside the subclass method definition for calling a method defined in the
superclass. A superclass having methods as private cannot be called. Only the
methods which are public and protected can be called by the keyword super. It is
also used by class constructors to invoke constructors of its parent class.
SYNTAX:
super.<method-name>();
Final is a keyword in Java that is used to restrict the user and can be used in many
respects. Final can be used with:
• Class
• Methods
• Variables
NOTE
69
70
1. By string literal
2. By new keyword
1) String Literal
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool"
first. If the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
String s1="Welcome";
2) By new keyword
70
71
will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to
the object in a heap (non-pool).
char ch[]={'s','t','r','i','n','g','s'};
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
In Java
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
71
72
72
73
73
74
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can
be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Constructor Description
STRINGBUFFER METHODS
Modifier AND Type Method
public synchronized StringBuffer append(String s)
public synchronized StringBuffer insert(int offset, String s)
public synchronized StringBuffer replace(int startIndex, int endIndex,
String str)
public synchronized StringBuffer delete(int startIndex, int endIndex)
74
75
All the fields, methods, and constructors of the class Character are specified by the
Unicode Data file which is particularly a part of Unicode Character Database and
is maintained by the Unicode Consortium.
Character Methods
Following is the list of the important instance methods that all the subclasses of the
Character class implement −
75
76
FILE IN JAVA
To use the File class, create an object of the class, and specify the filename or
directory name:
Example
import java.io.File; // Import the File class
The File class has many useful methods for creating and getting information about
files. For example:
76
77
Operations on file
Create a File
To create a file in Java, you can use the createNewFile() method. This method
returns a boolean value: true if the file was successfully created, and false if the file
already exists. Note that the method is enclosed in a try...catch block. This is
necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):
Write To a File
In the following example, we use the FileWriter class together with its write()
method to write some text to the file we created in the example above. Note that
when you are done writing to the file, you should close it with the close() method:
Read a File
we use the Scanner class to read the contents of the text file we created
Delete a File
To delete a file in Java, use the delete() method:
POLYMORPHISM
The word polymorphism means having multiple forms. The term Polymorphism
gets derived from the Greek word where poly + morphos where poly means many
and morphos means forms.
77
78
➢ Method Overriding
➢ Method Overloading
This is known as method overloading in Java. Here, the same method will perform
different operations based on the parameter.
For example, think of a superclass called Animal that has a method called
animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they
also have their own implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
Example
class Animal {
public void animalSound() {
78
79
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)
The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
79
80
➢ can be achieved).
➢ For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
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.
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.
Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous
class.
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.
80
81
81
82
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
82
83
Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.
83
84
Points to Remember
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors
o and static methods also.
• It can have final methods which will force the subclass not to change the body of the method.
84
85
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
obj.run();
85
86
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.
There are mainly three reasons to use interface. They are given below.
86
87
Syntax:
interface <interface_name>{
// by default.
interface Printable{
void print();
87
88
interface Showable{
void print();
obj.print();
88
89
Java Package
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined
packages
89
90
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
90
91
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
import package.*;
import package.classname;
fully qualified name.
Subpackage in java
Example of Subpackage
package com.javatpoint.core;
class Simple{
System.out.println("Hello subpackage");
91
92
instanceof operator
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
Let's see the simple example of instance operator where it tests the current class.
class Simple1{
92
93
GUI Components
Introduction to GUI programming in java
So far, we have covered the basic programming constructs (such as variables, data types,
decision, loop, array and method) and introduced the important concept of Object-Oriented
Programming (OOP). As discussed, OOP permits higher level of abstraction than traditional
Procedural-Oriented languages (such as C and Pascal). You can create high-level abstract data
types called classes to mimic real-life things. These classes are self-contained and are reusable.
Now we will discuss how we can reuse the graphics classes provided in JDK for constructing our
own Graphical User Interface (GUI) applications. Writing your own graphics classes (and re-
inventing the wheels) is mission impossible! These graphics classes, developed by expert
programmers, are highly complex and involve many advanced design patterns. However, re-
using them is not so difficult, if you follow the API documentation, samples and templates
provided.
There are current three sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit), Swing and JavaFX.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have become
obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT,
was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC
consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-
Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.
3. The latest JavaFX, which was integrated into JDK 8, is meant to replace Swing.
/*Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other organizations/vendors
have also provided graphics APIs that work with Java, such as Eclipse's Standard Widget Toolkit
(SWT) (used in Eclipse), Google Web Toolkit (GWT) (used in Android), 3D Graphics API such
as Java bindings for OpenGL (JOGL) and Java3D.
You need to check the JDK 9 API (https://docs.oracle.com/javase/9/docs/api/overview-
summary.html) for the AWT/Swing APIs (under module java.desktop) and JavaFX (under
modules javafx.*) while reading this chapter. The best online reference for Graphics
programming is the "Swing Tutorial" @ http://docs.oracle.com/javase/tutorial/uiswing/. For
advanced 2D graphics programming, read "Java 2D Tutorial"
@ http://docs.oracle.com/javase/tutorial/2d/index.html. For 3D graphics, read my 3D articles.*/
Containers and Components
93
94
Event handling mechanisms: The way in which events are handled changed significantly
between the original version of java1.0 and modern versions of java. The java1.0 method of
event handling is still supported but it is not recommended for new programs.
Delegation event model: The modern approach to handling events is based on the delegation
event model; According to this a source generates an event and sends it to one or more listeners.
In this scheme, the listener simply waits until it receives an event, once an event is received; the
listener processes the event and then returns. In delegation event model, listeners must register
with a source in order to receive an event notification. This provides an important benefit.
Notifications are sent only to listeners that want to receive them. This is a more efficient way to
handle events than the design used by the old java1.0 approach. Previously an event was
propagated up the containment hierarchy until it was handled by a component. This required
94
95
components to receive events that they did not process, and it wasted valuable time. The
delegation event model eliminates this disadvantage.
Events: In the delegation model, an event is an object that describes a state change in a source. It
can be generated by a person interacting with the elements in a graphical user interface. Some of
the activities that cause events to be generated are pressing a button, entering a character via the
keyboard, clicking the mouse etc. Events may also occur not directly interaction with a user
interface, for example an event may occurs, when a timer expires, a counter exceeds a value, a
software or hardware failure occurs or an operation is completed.
Event Source: A source is an object that generates an event. Event occurs when the internal
state of that object changes. Sources may generate more than one type of event. A source must
register listener in order for the listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. The general form is
95
96
96
97
97
98
The javax.swing package provides classes for java swing API such as JoptionPane, JLable,
JTextField, JButton, JCheckBox, JTextArea, JComboBox, JList, JPannel etc.
There are two types of java programs in which swing is typically used
• Desktop application i,e swing application
• Swing applet
Sources/Controls/Components
JLable: This component is used to display text and/or an icon. It is passive component in that it
does not respond to user input. JLabel is a class of java Swing . JLabel is used to display a short
string or an image icon. JLabel can display text, image or both . JLabel is only a display of text
or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or
keyboard focus. By default labels are vertically centered but the user can change the alignment
of label.
Constructor of the class are :
1. JLabel() : creates a blank label with no text or image in it.
2. JLabel(String s) : creates a new label with the string specified.
3. JLabel(Icon i) : creates a new label with a image on it.
4. JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a
specified horizontal alignment. It must be one of the following values: LEFT,RIGHT,
CENTER, LEADING, or TRAILING. These constants are defined in the swingConstants
interface. Note that icons are specified by objects of type Icon, which is an interface
defined by swing. The easy way to obtain an icon is use the ImageIcon class. This class
implements Icon and encapsulates an image. An object of type ImageIcon can be passed as
an argument to the Icon parameter of JLable’s constructor.
Commonly used methods of the class are :
1. getIcon() : returns the image that that the label displays
2. setIcon(Icon i) : sets the icon that the label will display to image i
3. getText() : returns the text that the label will display
4. setText(String s) : sets the text that the label will display to string s
98
99
Output
99
100
100
101
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
Drawback of Applet
Hierarchy of Applet
101
102
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
102
103
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
103
104
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.
• By html file.
• By appletViewer tool (for testing purpose).
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body> </html>
104
105
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Java Swing
• Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
105
106
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
106
107
The methods of Component class are widely used in java swing that are given
below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the
m) component.
public void setVisible(boolean b) sets the visibility of the component. It is
by default false
.
Java Swing Examples
There are two ways to create a frame:
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
107
108
Exception Handling
The mistakes which happened while developing and typing a program is called an error. It may
produce an incorrect output or may terminate the execution of the program abruptly
(immediately) or may cause the system to crash. Therefore programmer has to detect and mange
properly all the possible error conditions int he program.
Types of errors
1. Compile time errors
2. Run time errors
Compile time errors: The errors which are detected and displayed by compiler during
compilation of the program are known as compile time errors.
Example: all syntax errors, like missing semicolon, missing double quotes in strings, use of
undeclared variables, etc.
Run time errors: The errors which occur while running the program are called run time errors.
Some of the common run time errors are dividing an integer by zero, accessing the array element
that is out of the bounds of an array, converting invalid string to number etc.
Definition of Exception handling: It is the mechanism to handle runtime errors. We need to
handle such exceptions to prevent abrupt termination of program.
Exception: The term exception means exceptional condition, it is a problem that may arise
during the execution of program. When the java interpreter encounters an error such as dividing
an integer by zero, it creates an exception object and throws it ( i,e informs us that as error has
occurred).
If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program. If we want the program to continue with the
execution of the remaining code, then we should try to catch the exception object thrown by the
error condition and then display an appropriate message for taking corrective actions. This task is
known as exception handling. It performs following tasks
1. Find the problem (Hit the exception).
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (Handle the exception)
Exception in java
Exception type Cause of exception
ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
ArrayStoreException Caused when a program tries to store the wrong type of
data in an array
FileNotFoundExecption Caused by an attempt to access a non existing file
IOException Caused by general I/O failure, such as inability to read
from a file.
NullPointerException Caused by referencing a null object
NumberFormatException Caused when a conversion between strings and number
fails
StringIndexOutOfBoundsException Caused when a program attempts to access a nonexistent
character position in a string.
108
109
Types of exceptions
1. Checked exceptions: These exceptions are explicitly handled n the code itself with the
help of try-catch blocks. Checked exceptions are extended from the java.lang.Exception
class.
2. Unchecked exceptions: These exceptions are not essentially handled in the program code,
instead the JVM handles such exceptions. Unchecked exceptions are extended from the
java.lang.RuntimeException class.
Syntax of exception handling code
The basic concept of exception handling are throwing an exception and catching it as shown in
the below figure.
Java uses a keyword try to preface a block of code that is likely to cause an error condition and
throw an exception. A catch block defined by the key word catch catches the exception thrown
by the try block and handles it appropriately. The catch block is added immediately after the try
block as shown below.
......................
......................
try
{
Statements;
}
catch(Exception-type e)
{
Statements;
109
110
}
......................
......................
The try block can have one or more statements which can generate exception. If anyone
statement generates an exception, the remaining statements in the try block are skipped and
control jumps to the catch block. It can have one or more statements that are necessary to process
the exception. Every try statement should be followed by at least one catch block otherwise
compilation error will be generated. Catch statement works like a method definition. Exception
object thrown by try block is matched with the catch block exception type, if they match with
each other then the statements in the catch block will be executed, otherwise exception is not
caught and the default exception handler will cause the execution to terminate.
Output
110
111
Output
111
112
{
Statements;
}
......................
......................
Java treats the multiple catch statements like cases in a switch statement. When an exception is
thrown by the try block, it tries to find the match with the catch statement exception type. Where
the match is found that catch statement is executed, and the remaining catch statements are
skipped.
Note: We can simply have a catch statement with an empty block to avoid program termination.
Output
112
113
block can be used to handle any exception generated within a try block. It may be added
immediately after the try block or after the last catch statement as shown below.
Finally block after try block
try
{
Statements;
}
finally
{
Statements;
}
try
{
Statements;
}
catch(Exception-type1 e)
{
Statements;
}
catch(Exception-type2 e)
{
Statements;
}
.
.
.
catch(Exception-typen e)
{
Statements;
}
finally
{
Statements;
}
Finally block always executed where the exception is thrown by try block or not. Therefore it is
used to perform certain housekeeping operations such as closing files and releasing system
resources.
Throw and Throws
Throwing our own exceptions (user defined exception type)
113
114
Programmer can create his own type of exception and he can throw it in the program
where it is required. The keyword throw is used to throw the exception explicitly as shown
below
throw new throwable subclass;
Output
114
115
Throws: If method is capable of causing an exception that it does not handle, it must specify this
behaviour so that callers of the method can guard themselves against that exception. To inform
the caller the keyword throws is used in the method declaration. A throws clause lists the types
of exceptions that a method might throw. This is necessary for all exceptions, except those of
type Error or RuntimeException or any of their subclasses. All other exceptions that a method
can throw must be declared in the throws clause. If they are not, a compile time error will result.
The general form of method declaration that includes a throws clause is as shown below.
Return_type method_name(parameter list) throws exception_list
{
}
Where exception_list is the list of exception thrown by the methods, they are separated by
comma.
Output
115
116
MULTITHREADING
What is Multithreading
What is Multitasking
It is the way of executing multiple tasks at a time executing them concurrently over
a specified period. Multitasking is done in two ways. These are:
A thread goes through various stages of its life cycle. Example, first of all, a thread
is born, started its tasks, run a sequence of tasks concurrently, and then dies. Here
is the diagram of the various stages of a life cycle.
116
117
he following diagram shows the different states involved in the life cycle of a
thread.
Waiting: When the thread is put on hold or it is waiting for the other thread
to complete, then that state will be known as “waiting” state.
Thread class:
Thread class provide constructors and methods to create and perform operations on
a thread.Thread class extends Object class and implements Runnable interface.
117
118
System.out.println("thread is running...");
t1.start();
Thread()
Thread(String name)
Thread(Runnable r)
2)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().
The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:
118
119
System.out.println("thread is running...");
t1.start();
Thread Methods:
Join() – Stop the current thread until the called thread gets terminated.
119
120
Synchronization: At times when more than one thread try to access a shared
resource, we need to ensure that resource will be used by only one thread at a time.
The process by which this is achieved is called synchronization. The
synchronization keyword in java creates a block of code referred to as critical
section.
Syntax
Synchronized(Object)
Statements to be synchronized;
If we do not use synchronization, and let two or more threads access a shared
resource at the same time, it will lead to distorted results.
Consider as example, suppose we have two different threads T1 and T2, T1 starts
execution and save certain values in a file temporary.txt which will be used to
calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns,
T2 change the values saved by T1 will return wrong result. To prevent such
problems, synchronization was introduced. With synchronization in above case,
once T1 starts using temporary.txt file, this file will be locked and no other thread
will be able to access or modify it until T1 returns.
120
121
Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList
, Vector, LinkedList
, PriorityQueue
Let us see the hierarchy of Collection framework. The java.util package contains all the classes
and interfaces
121
122
122
123
123
124
Java Networking
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources.
• Sharing resources
• Centralize software management
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket
124
125
1) IP Address
2) Protocol
• TCP
• FTP
• Telnet
• SMTP
• POP etc.
3) Port Number
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
125
126
6) Socket
java.net package
A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections
to the resource pointed by URLs.
The java.net package provides many classes to deal with networking applications
in Java. A list of these classes is given below:
o Authenticator o ProxySelector
o CacheRequest o ResponseCache
o CacheResponse o SecureCacheResponse
o ContentHandler o ServerSocket
o CookieHandler o Socket
o CookieManager o SocketAddress
o DatagramPacket o SocketImpl
o DatagramSocket o SocketPermission
o DatagramSocketImpl o StandardSocketOptions
o InterfaceAddress o URI
o JarURLConnection o URL
o MulticastSocket o URLClassLoader
126
127
o InetSocketAddress o URLConnection
o InetAddress o URLDecoder
o Inet4Address o URLEncoder
o Inet6Address o URLStreamHandler
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
CookiePolicy
CookieStore
DatagramSocketImplFactory
FileNameMap
SocketOption<T>
SocketOptions
SocketImplFactory
URLStreamHandlerFactory
ProtocolFamily
127
128
//Employee.java
package mypack;
public Employee(){}
128
129
To access the JavaBean class, we should use getter and setter methods.
package mypack;
System.out.println(e.getName());
}}
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define.
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
129
130
Advantages of JavaBean
Disadvantages of JavaBean
Java I/O
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 java.io 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.
130
131
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
OutputStream vs InputStream
OutputStream
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given below.
131
132
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
132
133
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1
IOException at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException from the current input stream.
InputStream Hierarchy
133