100% found this document useful (1 vote)
1K views133 pages

Java Notes (Nep Syllabus)

Java is an object-oriented programming language developed in 1995. It is used to develop web applications, mobile apps, desktop apps, and more. A Java program consists of classes and objects that communicate via methods. The Java compiler produces bytecode that can run on any system with a Java Virtual Machine (JVM). The JVM executes the bytecode and handles running the program across different platforms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
1K views133 pages

Java Notes (Nep Syllabus)

Java is an object-oriented programming language developed in 1995. It is used to develop web applications, mobile apps, desktop apps, and more. A Java program consists of classes and objects that communicate via methods. The Java compiler produces bytecode that can run on any system with a Java Virtual Machine (JVM). The JVM executes the bytecode and handles running the program across different platforms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 133

1

OOC WITH JAVA

BASICS OF JAVA PROGRAMMING

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:

• Java is an object-oriented programming language developed by Sun


Microsystems, and it was released in 1995.
• James Gosling initially developed Java in Sun Microsystems (which was
later merged with Oracle Corporation).
• Java is a set of features of C and C++. It has obtained its format from C, and
OOP features from C++.
• Java programs are platform independent which means they can be run on
any operating system with any processor as long as the Java interpreter is
available on that system.
• Java code that runs on one platform does not need to be recompiled to run on
another platform; it's called write once, run anywhere(WORA).
• Java Virtual Machine (JVM) executes Java code, but it has been written in
platform-specific languages such as C/C++/ASM, etc. JVM is not written in
Java and hence cannot be platform independent, and Java interpreter is a part
of JVM.

Where is Java Being Used?


Earlier Java was only used to design and program small computing devices, but it
was later adopted as one of the platform-independent programming languages, and
now according to Sun, 3 billion devices run Java.

1
2

Java is one of the most important programming languages in today's IT industries.

• 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.

Types of Java Applications

1. Web Application - Java is used to create server-side web applications.


Currently, Servlet, JSP, Struts, JSF, etc. technologies are used.
2. Standalone Application - It is also known as the desktop application or
window-based application. An application that we need to install on every
machine or server such as media player, antivirus, etc. AWT and Swing are
used in java for creating standalone applications.
3. Enterprise Application - An application that is distributed in nature, such
as banking applications, etc. It has the advantage of high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.
4. Mobile Application - Java is used to create application software for mobile
devices. Currently, Java ME is used for building applications for small
devices, and also Java is a programming language for Google Android
application development.

Features of Java Programming

• Object-Oriented - Java supports the features of object-oriented


programming. Its object model is simple and easy to expand.
• Platform independent - C and C++ are platform dependency languages
hence the application programs written in one Operating system cannot run
in any other Operating system, but in platform independence language like

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.

Java Popular Editors

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/

Basic Syntax of Java Program

When we consider a Java program, it can be defined as a collection of objects


that communicate via invoking each other's methods. Let us now briefly look
into what do class, object, methods and instance variables mean.

Object - Objects have states and behaviors. Example: A dog has states-color,

3
4

name, breed as well as behaviors -wagging, barking, eating. An object is an


instance of a class.

Class - A class can be defined as a template/blue print that describes the


behaviors/states that object of its type support.

Methods - A method is basically a behavior. A class can contain many


methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.

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.

First Java Program:

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 notepad and add the code as above.

Save the file as: MyFirstJavaProgram.java.

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).

Now, type ' java MyFirstJavaProgram ' to run your program.

4
5

You will be able to see ' Hello World ' printed on the window.

C :> javac MyFirstJavaProgram.java C :> java MyFirstJavaProgram HelloWorld


Basic Syntax:

About Java programs, it is very important to keep in mind the following


points.

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 ?

• JVM, i.e., Java Virtual Machine.


• JVM is the engine that drives the Java code.
• Mostly in other Programming Languages, compiler produce code for a
particular system but Java compiler produce Bytecode for a Java Virtual
Machine.
• When we compile a Java program, then bytecode is generated. Bytecode is
the source code that can be used to run on any platform.
• Bytecode is an intermediary language between Java source and the host
system.
• It is the medium which compiles Java code to bytecode which gets
interpreted on a different machine and hence it makes it Platform/Operating
system independent.

JVM's work can be explained in the following manner

• Reading Bytecode.
• Verifying bytecode.
• Linking the code with the library

2) What is JDK ?

JDK (Java SE Development Kit) Includes a complete JRE (Java Runtime


Environment) plus tools for developing, debugging, and monitoring Java
applications. JDK is required to build and run Java applications and applets.

JDK tools divided into five categories:

• Basic Tools
• Remote Method Invocation (RMI) Tools
• Internationalization Tools
• Security Tools
• Java IDL Tools

6
7

BASIC JDK TOOLS

These tools are the foundation of the Java Development Kit.

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 ?

JRE stands for Java Runtime Environment, which provides an environment at


runtime. It is the cause of the implementation of JVM (as discussed earlier). It
contains a set of supporting libraries combined with core classes and various other
files that JVM uses at runtime. JRE is a part of JDK (Java Development
Toolkit) but can be downloaded separately.

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

o Dynamic - Functions that are required at runtime and not at compile


time.

In detail, the JRE consists of various components; these are listed below:

Java Web Start and Java Plug-in.

User Interface Toolkit includes Abstract Window Toolkit (AWT), Swing, Image
Input / Output, Accessibility, drag and drop, etc.

Other different base libraries, including Input/Output, extension mechanisms,


beans, JMX, JNI, networking, override mechanisms, etc.

Lang and util base libraries, including lang and util, management, versioning,
collections, etc.

Integration libraries include Interface Definition Language (IDL), Java Database


Connectivity (JDBC), Java Naming and Directory Interface (JNDI), and Remote
Method Invocation (RMI).

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.

When we write a program, we need different important things. We require


language tokens, white spaces, and formats.

There are various tokens used in Java:

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.

JAVA RESERVED KEYWORDS LIST

You can't use keyword as identifier in your Java programs, its reserved words in
Java library and used to perform an internal operation.

abstract assert boolean break


byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while true false
null

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.

There are many types of operators available in Java such as:

• 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:

Operator Meaning Work


+ Addition To add two operands.
- Subtraction To subtract two operands.
* Multiplication To multiply two operands.
/ Division To divide two operands.
% Modulus To get the area of the division of two operands.

10
11

UNARY ARITHMETIC OPERATOR

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.

Increment and decrement unary operator works as follows:

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.

Following example table, demonstrates the work of Increment and decrement


operators with postfix and prefix:

Example Description

val = a++; Store the value of "a" in "val" then increments.

val = a--; Store the value of "a" in "val" then decrements.

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.

There are six types of relational operators in Java, these are:

• == 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

reverses the value of


operands, if the value is
true, then it gives false,
and if it is false, then it
gives true

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.

Operator Description Example

& Binary AND Operator (A & B) will give 12


copies a bit A the result if which is 0000 1100
it exists in both operands
| Binary OR Operator (A | B) will give 61
copies a bit if it which is 0011 1101
exists in either operand.
^ Binary XOR Operator A ^ B) will give 49
copies the bit if it which is 0011 0001
is set in one operand but
not both.
~ Binary Ones Complement (~A ) will give -60
Operator is which is 1100 0011
unary and has the effect
of 'flipping'
bits.
<< Binary Left Shift A << 2 will give 240
Operator. The left which is 1111 0000
operands value is moved
left by the
number of bits specified
by the right
operand

13
14

>> Binary Right Shift A >> 2 will give 15 which


Operator. The left is 1111
operands value is moved
right by the
number of bits specified
by the right
operand.
>>> Shift right zero fill A >>>2 will give 15
operator. The left which is 0000 1111
operands value is moved
right by the
number of bits specified
by the right
operand and shifted
values are filled
up with zeros.

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

!= bitwise inclusive OR and C |= 2 is same as C


assignment =C|2
operator

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 {}

public class Employee extends Company {

public void check() {

System.out.println("Success.");

public static void view(Company c) {

if (c instanceof Employee) {

Employee b1 = (Employee) c;

b1.check();

public static void main(String[] args) {

Company c = new Employee();

Employee.view(c);

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This

affects how an expression is evaluated. Certain operators have higher

precedence than others; for example, the multiplication operator has higher

precedence than the addition operator: For example, x = 7 + 3 * 2; here, x is

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

bottom. Within an expression, higher precedence operators will be evaluated

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

Basic 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

and decides what can be stored in the reserved memory. Therefore, by

assigning different data types to variables, you can store integers, decimals, or

characters in these variables.

There are two data types available in Java:

• Reference/Object Data Types


• Primitive Data Types:

PRIMITIVE DATA TYPES

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.

• Minimum value is -128 (-2^7)


• Maximum value is 127 (inclusive)(2^7 -1)
• msrprasad@kluniversity.in 15
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of

19
20

• integers, since a byte is four times smaller than an int.


• Example: byte a = 100, byte b = -50

short:
Short data type is a 16-bit signed two's complement integer.

• Minimum value is -32,768 (-2^15)


• Maximum value is 32,767(inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A
• short is 2 times smaller than an int
• Default value is 0.
• Example: short s= 10000, short r = -20000

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.

• Minimum value is -9,223,372,036,854,775,808.(-2^63)


• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
• Example: int a = 100000L, int b = -200000L

20
21

float:
Float data type is a single-precision 32-bit IEEE 754 floating point.

• Float is mainly used to save memory in large arrays of floating point


• numbers.
• Default value is 0.0f.
• Float data type is never used for precise values such as currency.
• Example: float f1 = 234.5f

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.

• There are only two possible values: true and false.


• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true

char:
char data type is a single 16-bit Unicode character.

• Minimum value is '\u0000' (or 0).


• Maximum value is '\uffff' (or 65,535 inclusive).
• Char data type is used to store any character.
• Example: char letterA ='A'

21
22

Reference Data Types:


Reference variables are created using defined constructors of the classes.
They are used to access objects. These variables are declared to be of a specific
type

that cannot be changed. For example, Employee, Puppy, etc.

• 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

This means assigning a value to variables. In Java, you can assign a


value to variables in two ways:

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

RULES OF DECLARING VARIABLES

• 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 {

int amount = 100; //instance variable

static int pin = 2315; //static variable

24
25

public static void main(String[] args) {

int age = 35; //local variable

Example1:

public class Example {

int salary; // Instance Variable

public void show() {

int value = 2; // Local variable

value = value + 10;

System.out.println("The Value is : " + value);

salary = 10000;

System.out.println("The salary is : " + salary);

public static void main(String args[]) {

Example eg = new Example();

eg.show();

25
26

Access Modifiers in Java


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.

There are four types of Java access modifiers:


Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

class A{

private int data=40;

private void msg(){System.out.println("Hello java");}

public class Simple{

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

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{

public void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error

obj.msg();//Compile Time Error

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

protected void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();

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.

package pack;

public class A{

public void msg(){System.out.println("Hello");}

28
29

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within class within outside outside


Modifier package package by package
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

29
30

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set
of elements in a Java array.

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.

Types of Array in java

There are two types of array.

1) Single Dimensional Array

2) Multidimensional Array

30
31

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array

//Java Program to illustrate how to declare, instantiate, initialize

//and traverse the Java array.

class Testarray{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

//traversing array

for(int i=0;i<a.length;i++)//length is the property of array

31
32

System.out.println(a[i]);

}}

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix
form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

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;

Example of Multidimensional Java Array

//Java Program to illustrate the use of multidimensional array

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

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

Java Control Statements | Control Flow in Java


Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java

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.

Java provides three types of control flow statements.


Decision Making statements
if statements
switch statement

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

Let's understand the if-statements one by one.

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.

Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

35
36

Consider the following example in which we have used the if statement in the java
code.

//Student.java

public class Student {

public static void main(String[] args) {

int x = 10;

int y = 12;

if(x+y > 20) {

System.out.println("x + y is greater than 20");

}
2) if-else statement

The 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) {

statement 1; //executes when condition is true

else{

statement 2; //executes when condition is false

36
37

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if-else statements that
create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

else if(condition 2) {

statement 2; //executes when condition 2 is true

else {

statement 2; //executes when all the conditions are false


}

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.

37
38

Syntax of Nested if-statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

else{

statement 2; //executes when condition 2 is false

}
Consider the following example.

public class Student {

public static void main(String[] args) {

String address = "Delhi, India";

if(address.endsWith("India")) {

if(address.contains("Meerut")) {

System.out.println("Your city is Meerut");

}else if(address.contains("Noida")) {

System.out.println("Your city is Noida");

}else {

System.out.println(address.split(",")[0]);

}else {

38
39

System.out.println("You are not living in India");

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.

Points to be noted about switch statement:

The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java

Cases cannot be duplicate

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.

It is optional, if not used, next case is executed.

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.

public class Student implements Cloneable {

public static void main(String[] args) {

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

Let's understand the loop statements one by one.

41
42

Java for loop


In Java, for loop

is similar to C

and C++

. It enables us to initialize the loop variable, check the condition, and


increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.

for(initialization, condition, increment/decrement) {

//block of statements

The flow chart for the for-loop is given below.

Control Flow in Java

Consider the following example to understand the proper functioning of the for
loop in java.

public class Calculattion {

public static void main(String[] args) {

// TODO Auto-generated method stub

int sum = 0;

for(int j = 1; j<=10; j++) {

sum = sum + j;

42
43

System.out.println("The sum of first 10 natural numbers is " + sum);

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The
syntax to use the for-each loop in java is given below.

for(data_type var : array_name/collection_name){


//statements

Consider the following example to understand the functioning of the for-each loop
in Java.

public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

String[] names = {"Java","C","C++","Python","JavaScript"};

System.out.println("Printing the content of the array names:\n");

for(String name:names) {

System.out.println(name);

43
44

Java while loop


The while loop

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.

The syntax of the while loop is given below.

while(condition){

//looping statements

} .

Control Flow in Java

Consider the following example.

public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

44
45

while(i<=10) {

System.out.println(i);

i = i + 2;

Java do-while loop


The do-while loop

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);

Control Flow in Java

Consider the following example to understand the functioning of the do-while loop
in Java.

45
46

public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

int i = 0;

System.out.println("Printing the list of first 10 even numbers \n");

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.

Java break statement


As the name suggests, the break statement

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.

The break statement example with for loop

Consider the following example in which we have used the break statement
with the for loop.

BreakExample.java

public class BreakExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 10; i++) {

System.out.println(i);

if(i==6) {

break;

break statement example with labeled for loop

public class Calculation {

47
48

public static void main(String[] args) {

// TODO Auto-generated method stub

a:

for(int i = 0; i<= 10; i++) {

b:

for(int j = 0; j<=15;j++) {

c:

for (int k = 0; k<=20; k++) {

System.out.println(k);

if(k==5) {

break a;

} }}}}

Java continue statement


Unlike break statement, the continue statement

doesn't break the loop, whereas, it skips the specific part of the loop and jumps to
the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

public class ContinueExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

48
49

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

if(j == 4) {

continue;

System.out.println(j);

Java Math class


Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

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:

Basic Math methods

Method AND Description

Math.abs()

It will return the Absolute value of the given value.

Math.max()

It returns the Largest of two values.

Math.min()

It is used to return the Smallest of two values.

Math.round()

It is used to round of the decimal numbers to the nearest value.

Math.sqrt()

It is used to return the square root of a number.

Math.cbrt()

It is used to return the cube root of a number.

Math.pow()

It returns the value of first argument raised to the power to second argument.

Math.signum()

It is used to find the sign of a given value.

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()

It returns the floating-point value adjacent to d in the direction of positive infinity.

Math.nextDown()

It returns the floating-point value adjacent to d in the direction of negative infinity.

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.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability
of code. We write a method once and use it many times. We do not require to write
code again and again. It also provides the easy modification and readability of
code, just by adding or removing a chunk of code. The method is executed only
when we call or invoke it.

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.

Parameter List: It is the list of parameters separated by a comma and enclosed in


the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.

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

public class Demo

public static void main(String[] args)

// using the max() method of Math class

System.out.print("The maximum number is: " + Math.max(9,7));

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.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we
will define the method.

//user defined method

public static void findEvenOdd(int num)

//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

OBJECTS AND CLASSES


This is mainly focused on Java object and class and described the features of Java
object-oriented programming.

Java has following OOPS features:

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

Collection of objects is called class. It is a logical entity.

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

If one task is performed in different ways, it is known as polymorphism. For


example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.

5) Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example phone call, we don't know the internal processing.

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

Message Passing in terms of computers is communication between processes. It is


a form of communication used in object-oriented programming as well as parallel
programming. Message passing in Java is like sending an object i.e. message from
one thread to another thread

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.

In real-world object and software object have conceptually similar characteristics.


In terms of object-oriented programming, software objects also have a state and
behavior.

57
58

SYNTAX OF OBJECT

CLASS_NAME OBJ_NAME=NEW CLASSNAME();

CLASSES

• A class is a template or blueprint that is used to create objects.


• Class representation of objects and the sets of operations that can be
applied to such objects.
• A class consists of Data members and methods.

The primary purpose of a class is to hold data/information. This is achieved


with attributes which are also known as data members.

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

public class class_name

Data Members;

Methods;

58
59

EXAMPLE

public class Car

public:

double color; // Color of a car

double model; // Model of a car

Private, Protected, Public is called visibility labels.

The members that are declared private can be accessed only from within the class.

Public members can be accessed from outside the class also.

CLASS MEMBERS

Data and functions are members.

Data Members and methods must be declared within the class definition.

EX:

public class Cube

int length; // length is a data member of class Cube

int breadth; // breadth is a data member of class Cube

int length ; // Error redefinition of length

A member cannot be redeclared within a class.

No member can be added elsewhere other than in the class definition.

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.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

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.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

60
61

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any


parameter.

Syntax of default constructor:


<class_name>(){}

Example of default constructor

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();
}
}

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a


parameterized constructor.

Why use the parameterized constructor?


The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.

61
62

Syntax of paramerized constructor:


<class_name>(PARAMETERS){}

Example of parameterized constructor


In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

62
63

Method Overloading in Java


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

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.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments

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.

In this example, we are creating static methods

so that we don't need to create instance for calling methods.

class Adder{

63
64

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){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

2) Method Overloading: changing data type of arguments

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{

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){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

64
65

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

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

Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.

Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

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).

Example of method overriding

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.

//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{

//defining a method

void run(){System.out.println("Vehicle is running");}

65
66

//Creating a child class

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2();//creating object

obj.run();//calling method

static and this keyword


static keyword
Static is a keyword that acts as a non-access modifier in Java that is used
mainly to manage memory. The variable or Method that are marked static belongs
to the Class rather than to any particular instance. A Static method cannot access
an instance variable. If a Class contains any static blocks, then that block will be
executed only when the Class is loaded in JVM. Programmers can apply the Java
keyword static with different programming objects like:

1. variables
2. methods
3. initialization - block
4. nested class

66
67

STATIC KEYWORD IS UNACCEPTABLE TO THE FOLLOWING

• Class
• Constructor
• Local inner classes
• Inner class methods
• Instance variables
• Local Variables
• Interfaces
RULES FOR USING STATIC VARIABLES

• Variables or methods belong to class rather than to any particular instance


• A static method cannot access a non-static variable of a class nor can
directly invoke non-static method
• Static members can be applied without creating or referencing an instance of
the class
• A static variable will be shared by all instances of that class which will result
in only one copy

this KEYWORD IN JAVA

this is another Java keyword which as a reference to the current object


within an instance method or a constructor — the object whose method or
constructor is being called. By the use of this keyword, programmers can refer to
any member of the current object within an instance method or a constructor. This
keyword can be used to refer to the current object, and it always acts as a reference
to an object in which method was invoked. There are the various uses of this
keyword in Java. These are:

• 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;

Emp(int e_id, String name) {


this.e_id = e_id;
this.name = name;
}
void show() {
System.out.println(e_id + " " + name);
}
public static void main(String args[]) {
Emp e1 = new Emp(1006, "Karlos");
Emp e2 = new Emp(1008, "Ray");
e1.show();
e2.show();
}
}

SUPER AND FINAL KEYWORD IN JAVA

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 KEYWORD IN JAVA

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

➢ When a class is declared as final, it cannot be extended further. Here is an


example what happens within a program
➢ A method declared as final cannot be overridden; this means even when a
child class can call the final method of parent class without any issues, but
the overriding will not be possible. Here is a sample program showing what
is not valid within a Java program when a method is declared as final.
➢ Once a variable is assigned with the keyword final, it always contains the
same exact value.

69
70

STRING CLASS IN JAVA

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object


that represents a sequence of characters. The java.lang.String class is used to create
a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

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";

String s2="Welcome";//It doesn't create a new instance

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM

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).

Java String Example

public class StringExample{

public static void main(String args[]){

String s1="java";//creating string by Java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string

String s3=new String("example");//creating Java string by new keyword

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

}}

In Java

, string is basically an object that represents sequence of char values. An array

of characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

71
72

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Method Description Return Type
charAt() Returns the character at char
the specified index
(position)
compareTo() Compares two strings int
lexicographically
compareToIgnoreCase() Compares two strings int
lexicographically,
ignoring case differences
concat() Appends a string to the String
end of another string
endsWith() Checks whether a string boolean
ends with the specified
character(s)
equals() Compares two strings. boolean
Returns true if the strings
are equal, and false if not
equalsIgnoreCase() Compares two strings, boolean
ignoring case
considerations
getChars() Copies characters from a void
string to an array of chars
hashCode() Returns the hash code of a int
string
indexOf() Returns the position of the int
first found occurrence of
specified characters in a
string
intern() Returns the canonical String
representation for the
string object
isEmpty() Checks whether a string is boolean
empty or not
lastIndexOf() Returns the position of the int

72
73

last found occurrence of


specified characters in a
string
length() Returns the length of a int
specified string
regionMatches() Tests if two string regions boolean
are equal
replace() Searches a string for a String
specified value, and
returns a new string where
the specified values are
replaced
replaceFirst() Replaces the first String
occurrence of a substring
that matches the given
regular expression with
the given replacement
replaceAll() Replaces each substring String
of this string that matches
the given regular
expression with the given
replacement
split() Splits a string into an String[]
array of substrings
subSequence() Returns a new character CharSequence
sequence that is a
subsequence of this
sequence
substring() Returns a new string String
which is the substring of a
specified string
toCharArray() Converts this string to a char[]
new character array
toLowerCase() Converts a string to lower String
case letters
toString() Returns the value of a String
String object
toUpperCase() Converts a string to upper String
case letters

73
74

trim() Removes whitespace from String


both ends of a string
valueOf() Returns the string String
representation of the
specified value

Java StringBuffer Class

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.

Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with


the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the
specified string..
StringBuffer(int capacity) It creates an empty String buffer with
the specified capacity as length.

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

Java Character class


The Character class generally wraps the value of all the primitive type char into an
object. Any object of the type Character may contain a single field whose type is
char.

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 −

Sr.No. Method & Description


1 isLetter()
Determines whether the specified char value is a letter.
2 isDigit()
Determines whether the specified char value is a digit.
3 isWhitespace()
Determines whether the specified char value is white space.
4 isUpperCase()
Determines whether the specified char value is uppercase.
5 isLowerCase()
Determines whether the specified char value is lowercase.
6 toUpperCase()
Returns the uppercase form of the specified char value.
7 toLowerCase()
Returns the lowercase form of the specified char value.
8 toString()
Returns a String object representing the specified character value that
is, a one-character string.

75
76

FILE IN JAVA

File handling is an important part of any application.


Java has several methods for creating, reading, updating, and deleting files.

Java File Handling


The File class from the java.io package, allows us to work with files.

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

File myObj = new File("filename.txt"); // Specify the filename


If you don't know what a package is, read our Java Packages Tutorial.

The File class has many useful methods for creating and getting information about
files. For example:

Method Type Description


canRead() Boolean Tests whether the file is
readable or not
canWrite() Boolean Tests whether the file is
writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file
exists
getName() String Returns the name of the
file

76
77

getAbsolutePath() String Returns the absolute


pathname of the file
length() Long Returns the size of the file
in bytes
list() String[] Returns an array of the
files in the directory
mkdir() Boolean Creates a directory

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

Two types of Polymorphism


1. Static Polymorphism
2. Dynamic Polymorphism.

We can achieve polymorphism in Java using the following ways:

➢ Method Overriding
➢ Method Overloading

Java Method Overriding


During inheritance in Java, if the same method is present in both the superclass and
the subclass. Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.

2. Java Method Overloading


In a Java class, we can create methods with the same name if they differ in
parameters. For example,

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

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

System.out.println("The animal makes a sound");


}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

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.

Inheritance represents the IS-A relationship which is also known as a parent-child


relationship.
Why use inheritance in java
➢ For Method Overriding
➢ (so runtime polymorphism

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 syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//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.

Java Inheritance Example

80
81

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

81
82

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Single Inheritance Example

82
83

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you


can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

Why multiple inheritance is not possible in Java in case of class?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

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.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

➢ Abstract class (0 to 100%)


➢ Interface (100%)

83
84

Abstract class in Java


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
• 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

Example of abstract class

abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract

Example of Abstract class that has 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.

abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){System.out.println("running safely");}

public static void main(String args[]){

Bike obj = new Honda4();

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.

Java Interface also represents the IS-A relationship

• It cannot be instantiated just like the abstract class.


• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
Why use Java interface?

There are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

86
87

How 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>{

// declare constant fields

// declare methods that abstract

// by default.

Multiple inheritance is not supported through class in java, but it is possible


by an interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not


supported in the case of class

because of ambiguity. However, it is supported in case of an interface because


there is no ambiguity. It is because its implementation is provided by the
implementation class. For example:

interface Printable{

void print();

87
88

interface Showable{

void print();

class TestInterface3 implements Printable, Showable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

TestInterface3 obj = new TestInterface3();

obj.print();

Difference between abstract class and interface

Important Reasons For Using Interfaces

• Interfaces are used to achieve abstraction.


• Designed to support dynamic method resolution at run time
• It helps you to achieve loose coupling.
• Allows you to separate the definition of a method from the inheritance
hierarchy

Important Reasons For Using Abstract Class

• Abstract classes offer default functionality for the subclasses.


• Provides a template for future specific classes
• Helps you to define a common interface for its subclasses
• Abstract class allows code reusability.

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

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

89
90

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename


For example

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).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

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.

How to access package from another package?


There are three ways to access the package from outside the package.

import package.*;
import package.classname;
fully qualified name.

Subpackage in java

Package inside the package is called the subpackage. It should be created to


categorize the package further.

Example of Subpackage

package com.javatpoint.core;

class Simple{

public static void main(String args[]){

System.out.println("Hello subpackage");

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

91
92

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive.
For example:

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).

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.

Simple example of java instanceof

Let's see the simple example of instance operator where it tests the current class.

class Simple1{

public static void main(String args[]){

Simple1 s=new Simple1();

92
93

System.out.println(s instanceof Simple1);//true

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

There are two types of GUI elements:


1. Component: Components are elementary GUI entities, such as Button, Label,
and TextField.
2. Container: Containers, such as Frame and Panel, are used to hold components in a specific
layout (such as FlowLayout or GridLayout). A container can also hold sub-containers.
In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-level
container of an AWT program. A Frame has a title bar (containing an icon, a title, and the
minimize/maximize/close buttons), an optional menu bar and the content display area. A Panel is
a rectangular area used to group related GUI components in a certain layout. In the above
figure, the top-level Frame contains two Panels. There are five components: a Label (providing
description), a TextField (for users to enter text), and three Buttons (for user to trigger certain
programmed actions).
Common GUI event types and listener interfaces

Event handling: State change of control/component is called event. Event handling is


fundamental to java programming because it is integral to the creation of applets and other types
of GUI based programs.

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

public void addTypeListener(TypeListener el)

ex: addkeyListener(keyEvent ke)

Event listeners: A listener is an object that is notified when an event occurs.


• Listeners must have been registered with one or more sources to receive notifications
about specific type of events.
• It must implement methods and process events are defined in a set of interfaces found in
java.awt.event.

95
96

Common GUI event types and listener interfaces


The classes that represent events are as follows
EventObject: This class is the root of the java event class hierarchy. It is defined in java.util
package. It is super class for all events.
AWTEvent: It is sub class of EventObject. It is defined in java.awt package.
ActionEvent: The ActionEvent class object is generated when button is clicked or the item of a
list is double clicked or a menu item is selected.
AdjustmentEvent: This class object is generated when a scroll bar is manipulated.
ComponentEvent: This class object is generated when a component is hidden, moved, resized
or becomes visible.
ContainerEvent: This class object is generated when a component is added or removed from a
container.
FocusEvent: This class object is generated when a component gains or losses keyboard focus.
ItemEvent: This class object is generated when a check box or list item is clicked, when a
choice selection is made or a checkable menu item is selected or deselected.
KeyEvet: This class object is generated when input received from the keyboard.
MouseEvent: This class object is generated when the mouse is dragged, moved, clicked, pressed
or released also generated when the mouse enters or exits a component.
MouseWheelEvent: This class object is generated when the mouse wheel is moved.
TextEvent: This class object is generated when the value of a text area or text field is changed.
WindowEvent: This class object is generated when a window is activated, closed, deactivated,
deiconified, iconified, opened or quit.
Sources of events: Following are the some of the user interface components that can generate
the events.
Button: Generates action events when the button is pressed.
Check box: Generates item events when check box is selected or deselected.
Choice: Generates item events when the choice is changed.
List: Generated action events when an item is double clicked, and generates item events when an
item is selected or deselected.
Menu item: Generates action events when a menu item is selected, generates item event when a
checkable menu item is selected or deselected.
Scroll bar: Generates adjustment events when the scroll bar is manipulated.
Text components: Generates text events when the user enters a character.
Window: Generates window events when a window is activated, closed, deactivated,
deiconified, iconified, opened or quit.
Event listener interface: The delegation event model has two parts: source and listeners.
Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package. When an event occurs, the event source invokes the appropriate method
defined by the listener and provides an event object as its argument. Following are commonly
used listener interfaces.
Interface Description
ActionListener Defines one method to receive action events.
void actionPerformed(ActionEvent ae)
AdjustmentListener Defines one method to receive adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)

96
97

ComponentListener Defines four methods to recognize when a component is hidden,


moved, resized or shown.
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Defines two methods to recognize when a component is added or
removed from a container
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemListener Defines one method to recognize when the state of an item changes.
void itemStateChanged(ItemEvent ie)
KeyListener Defines three methods to recognize when a key is pressed, released,
or typed.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Defines five methods to recognize when the mouse is clicked, enters
a component, exits a component, is pressed, or is released.
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
void mouseWheelMoved(MouseWheelEvent me)
TextListener Defines one method to recognize when a text value changes.
void textChanged(TextEvent te)
WindowFocusListener Defines two methods to recognize when a window gains or losses
input focus.
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened or quit.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)

97
98

void windowDeiconified(WindowEvent we)


void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

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

JTextField: It is a part of javax.swing package. The class JTextField is a component that


allows editing of a single line of text. JTextField inherits the JTextComponent class and uses
the interface SwingConstants.

The constructor of the class are :


1. JTextField() : constructor that creates a new TextField
2. JTextField(int columns) : constructor that creates a new empty TextField with specified
number of columns.
3. JTextField(String text) : constructor that creates a new empty text field initialized with
the given string.
4. JTextField(String text, int columns) : constructor that creates a new empty TextField
with the given string and a specified number of columns .
5. JTextField(Document doc, String text, int columns) : constructor that creates a
TextField that uses the given text storage model and the given number of columns.
Methods of the JTextField are:
1. setColumns(int n) :set the number of columns of the text field.
2. setFont(Font f) : set the font of text displayed in text field.
3. addActionListener(ActionListener l) : set an ActionListener to the text field.
4. int getColumns() :get the number of columns in the textfield.
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.
Constructors of the class are:
JButton():It creates a button with no text and icon.
JButton(String s): It creates a button with the specified text.
JButton(Icon i): It creates a button with the specified icon object.
Methods of the class are:

void setText(String s): It is used to set specified text on button

100
101

String getText() It is used to return the text of the button.


void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void It is used to add the action listener to this object.
addActionListener(ActionListener
a)

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

There are many advantages of applet. They are as follows:

• It works at client side so less response time.


• Secured
• It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.

Drawback of Applet

• Plugin is required at client browser to execute applet.

Hierarchy of Applet

101
102

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

102
103

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class


provides 1 life cycle methods for an applet.

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

The Component class provides 1 life cycle method of applet.

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.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

• By html file.
• By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


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.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
} }

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

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag
in comment and compile it. After that run it by: appletviewer First.java. Now Html
file is not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

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.

• Unlike AWT, Java Swing provides platform-independent and lightweight


components.

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.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

106
107

Commonly used Methods of Component class

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:

• By creating the object of Frame class (association)


• By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it
on the JFrame object inside the main() method.

File: FirstSwingExample.java

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible }}

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

Multiple catch statements


We can have more than one catch statement in the catch block as shown below
......................
try
{
Statements;
}
catch(Exception-type1 e)
{
Statements;
}
catch(Exception-type2 e)
{
Statements;
}
.
.
catch(Exception-typen e)

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

Using finally statement


Exception handling mechanism uses another statement known as finally statement that can be
used to handle an exception that is not caught by any of the previous catch statements, finally

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;
}

Finally block after last catch statement

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

The process of executing multiple tasks (also called threads) simultaneously is


called multithreading. The primary purpose of multithreading is to provide
simultaneous execution of two or more parts of a program to make maximum use
of CPU time. A multithreaded program contains two or more parts that can run
concurrently. It enables programmers to write in a way where multiple activities
can proceed simultaneously within a single application.

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:

Process-based multitasking: It is also called multiprocessing where each process


has its address in memory, i.e., each process allocates separate memory area.

Thread-based multitasking: This thread-based multitasking is also termed as


multithreading where threads share the same address space.

Life Cycle of Thread

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.

New: When the thread instance is created, it will be in “New” state.

Runnable: When the thread is started, it is called “Runnable” state.

Running: When the thread is running, it is called “Running” state.

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.

Terminated: When the thread is dead, it will be known as “terminated”


state.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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

1) Java Thread Example by extending Thread class

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Commonly used Constructors of Thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

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().

public void run(): is used to perform action for a thread.

The start() method of Thread class is used to start a newly created thread. It
performs the following tasks:

118
119

• A new thread starts(with new callstack).


• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.

2) Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)

t1.start();

Thread Methods:

start() – Starts the thread.

getState() – It returns the state of the thread.

getName() – It returns the name of the thread.

getPriority() – It returns the priority of the thread.

sleep() – Stop the thread for the specified time.

Join() – Stop the current thread until the called thread gets terminated.

isAlive() – Check if the thread is alive.

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;

Why we use synchronization?

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.

Using Synchronized methods: Using synchronized methods is the way to


accomplish synchronization. But let’s first see what happens when we do not use
synchronization in our program.

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

, HashSet, LinkedHashSet, TreeSet)

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group

What is a framework in Java

• It provides readymade architecture.


• It represents a set of classes and interfaces.
• It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

• Interfaces and its implementations, i.e., classes


• Algorithm

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package contains all the classes

and interfaces

for the Collection framework.

121
122

Methods of Collection interface


Method Name Method Description
boolean add(Object object) This method adds the specified object to the
collection calling this method. It returns true if the
object was added to the collection otherwise
returns false if the object is already a part of the
collection or if the collection does not allow
duplicates elements.
boolean addAll(Collection This method adds all the elements of the specified
collection) collection to the collection calling this method. It

122
123

returns true if the addition is successful, otherwise,


it returns false.
boolean contains(Object This method returns true if the specified object is a
object) part of the collection calling this method;
otherwise, it returns false.
void clear( ) This method removes all elements from the
collection calling this method.
boolean This method returns true if the collection calling
containsAll(Collection this method contains all specified collection
collection) elements; otherwise, it returns false.
boolean equals(Object This method returns true if the collection calling
object) this method and the specified object are equal;
otherwise, it returns false.
int hashCode( ) This method returns the hash code for the
collection calling this method.
boolean isEmpty( ) This method returns true if the collection calling
this method contains no elements; otherwise, it
returns false.
Iterator iterator( ) This method returns an iterator for the collection
calling this method.
boolean remove(Object This method removes the specified object from the
object) collection calling this method. Returns true if the
specified object was removed, otherwise returns
false.
boolean This method removes all elements available in a
removeAll(Collection specified collection from the collection calling this
collection) method. Returns true if there is a change in
collection calling this method; otherwise, it returns
false.
boolean retainAll(Collection This method removes all elements from the
collection) collection calling this method except those
available in the specified collection. This method
returns true if there is a change in collection calling
this method; otherwise, it returns false.
int size( ) This method returns the number of elements
available in the collection calling this method.
Object[ ] toArray( ) This method returns an array that contains all the
elements stored in the collection calling this
method. The array elements are, in fact, copies of

123
124

the elements available in the calling collection.


Object[ ] toArray(Object This method returns an array containing only those
array[ ]) collection elements of the calling collection whose
type matches the type of elements in the specified
array.

Java Networking
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources.

Java socket programming provides facility to share data between different


computing devices.

Advantage of Java Networking

• Sharing resources
• Centralize software management

The java.net package supports two protocols,

TCP: Transmission Control Protocol provides reliable communication between the


sender and receiver. TCP is used along with the Internet Protocol referred as
TCP/IP.

UDP: User Datagram Protocol provides a connection-less protocol service by


allowing packet of data to be transferred along two or more nodes

Java Networking Terminology

• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket

124
125

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It


is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For


example:

• TCP
• FTP
• Telnet
• SMTP
• POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a


communication endpoint between applications.

The port number is associated with the IP address for communication between two
applications.

4) MAC Address

MAC (Media Access Control) address is a unique identifier of NIC (Network


Interface Controller). A network node can have multiple NIC but each with unique
MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is


reliable but slow. The example of connection-oriented protocol is TCP.

125
126

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it


is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.

Visit next page for Java socket programming.

java.net package

The java.net package can be divided into two sections:

A Low-Level API: It deals with the abstractions of addresses i.e. networking


identifiers, Sockets i.e. bidirectional data communication mechanism and
Interfaces i.e. network interfaces.

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

List of interfaces available in java.net package:


ContentHandlerFactory

CookiePolicy

CookieStore

DatagramSocketImplFactory

FileNameMap

SocketOption<T>

SocketOptions

SocketImplFactory

URLStreamHandlerFactory

ProtocolFamily

127
128

JavaBean class in Java


JavaBean

A JavaBean is a Java class that should follow the following conventions:

• It should have a no-arg constructor.


• It should be Serializable.
• It should provide methods to set and get the values of the properties, known
as getter and setter methods.

Why use JavaBean?

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class

//Employee.java

package mypack;

public class Employee implements java.io.Serializable{

private int id;

private String name;

public Employee(){}

public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

128
129

How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;

public class Test{

public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

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.

A JavaBean property may be read, write, read-only, or write-only. JavaBean


features are accessed through two methods in the JavaBean's implementation class:

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

• The following are the advantages of JavaBean:/p>


• The JavaBean properties and methods can be exposed to another application.
• It provides an easiness to reuse the software components.

Disadvantages of JavaBean

• The following are the disadvantages of JavaBean:


• JavaBeans are mutable. So, it can't take advantages of immutable objects.
• Creating the setter and getter method for each property separately may lead
to the boilerplate code.

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.

We can perform file handling in Java by Java I/O API.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a


stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached
with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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");

Let's see the code to get input from console.

int i=System.in.read();//returns ASCII code of 1st character

System.out.println((char)i);//will print the character

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a


file, an array, peripheral device or socket.

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.

Useful methods of OutputStream

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.

3) public void flush()throws IOException flushes the current output 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.

Useful methods of InputStream

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.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy

133

You might also like