0% found this document useful (0 votes)
11 views210 pages

Java Notes

The document provides an introduction to Java, detailing its development by Sun Microsystems and its key features such as platform independence, object-oriented programming, and robustness. It explains the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with data types, variables, and their declarations. Additionally, it covers the concepts of primitive and non-primitive data types, variable types, and arrays in Java.

Uploaded by

upendrareddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views210 pages

Java Notes

The document provides an introduction to Java, detailing its development by Sun Microsystems and its key features such as platform independence, object-oriented programming, and robustness. It explains the Java Virtual Machine (JVM), Java Development Kit (JDK), and Java Runtime Environment (JRE), along with data types, variables, and their declarations. Additionally, it covers the concepts of primitive and non-primitive data types, variable types, and arrays in Java.

Uploaded by

upendrareddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

B.

SC-V JAVA_NOTES

UNIT-I

Introduction to Java

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It
was developed by James Gosling and Patrick Naughton. It is a simple programming language.
Writing, compiling and debugging a program is easy in java. It helps to create modular
programs and reusable code.

Java terminology
Before we start learning Java, lets get familiar with common java terms.

Java Virtual Machine (JVM)


This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program
execution. Phases are as follows: we write the program, then we compile the program and at last
we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates java
bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run
phase.

So, now that we understood that the primary function of JVM is to execute the bytecode
produced by compiler. Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating systems. That is why we call
java as platform independent language.

BYTECODE
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that
it can be executed by JVM. The bytecode is saved in a .class file by compiler.

Java Development Kit(JDK)


While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the
name suggests this is complete java development kit that includes JRE (Java Runtime
Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your
computer.

1
[Link]-V JAVA_NOTES

Java Runtime Environment(JRE)


JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your
system, you can run a java program however you won’t be able to compile it. JRE includes JVM,
browser plugins and applets support. When you only need to run a java program on your
computer, you would only need JRE.

Main Features of JAVA

Java is a platform independent language

Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned
above, JVM executes the bytecode produced by compiler. This byte code can run on any
platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on
windows can run on Linux and vice-versa. Each operating system has different JVM, however
the output they produce after execution of bytecode is same across all operating systems. That is
why we call java as platform independent language.

Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each of


which represents an instance of a class.

4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Simple

Java is considered as one of simple language because it does not have complex features like
Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.

Robust Language

Robust means reliable. Java programming language is developed in a way that puts a lot of
emphasis on early checking for possible errors, that’s why java compiler is able to detect errors
that are not easy to detect in other programming languages. The main features of java that makes
it robust are garbage collection, Exception Handling and memory allocation.

2
[Link]-V JAVA_NOTES

Secure

We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws
like stack corruption or buffer overflow is impossible to exploit in Java.

Java is distributed

Using java programming language we can create distributed applications. RMI(Remote Method
Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java.
In simple words: The java programs can be distributed on more than one systems that are
connected to each other using internet connection. Objects on one JVM (java virtual machine)
can execute procedures on a remote JVM.

Multithreading

Java supports multithreading. Multithreading is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilisation of CPU.

Portable

As discussed above, java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that makes java
code portable.

Data Types in Java

Data type defines the values that a variable can take, for example if a variable has int data type,
it can only take integer values. In java we have two categories of data type: 1) Primitive data
types 2) Non-primitive data types – Arrays and Strings are non-primitive data types, we will
discuss them later in the coming tutorials. Here we will discuss primitive data types and literals
in Java.

Java is a statically typed language. A language is statically typed, if the data type of a variable is
known at compile time. This means that you must specify the type of the variable (Declare the
variable) before you can use it.
In the last tutorial about Java Variables, we learned how to declare a variable, lets recall it:

int num;

3
[Link]-V JAVA_NOTES

So in order to use the variable num in our program, we must declare it first as shown above. It is
a good programming practice to declare all the variables ( that you are going to use) in the
beginning of the program.

1) Primitive data types


In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double.
Java developers included these data types to maintain the portability of java as the size of these
primitive data types do not change from one operating system to another.

byte, short, int and long data types are used for storing whole numbers.

float and double are used for fractional numbers.

char is used for storing characters(letters).

boolean data type is used for variables that holds either true or false.

byte:

This can hold whole number between -128 and 127. Mostly used to save memory and when you
are certain that the numbers would be in the limit specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:

class JavaExample {
public static void main(String[] args) {
byte num;
num = 113;
[Link](num);
}
}
Output:
113

4
[Link]-V JAVA_NOTES

By trying the same program by assigning value assigning 150 value to variable num, you would
get type mismatch error because the value 150 is out of the range of byte data type. The range of
byte as I mentioned above is -128 to 127.

short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767.
Default size of this data type: 2 byte

short num = 45678;


int: Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:

class JavaExample {
public static void main(String[] args) {

short num;

num = 150;
[Link](num);
}
}
Output:
150
The byte data type couldn’t hold the value 150 but a short data type can because it has a wider
range.

long:
Used when int is not large enough to hold the value, it has wider range than int data type, ranging
from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:

5
[Link]-V JAVA_NOTES

class JavaExample {
public static void main(String[] args) {

long num = -12332252626L;


[Link](num);
}
}
Output:
-12332252626

double: Sufficient for holding 15 decimal digits


size: 8 bytes
Example:

class JavaExample {
public static void main(String[] args) {

double num = -42937737.9d;


[Link](num);
}
}
Output:
-4.29377379E7

float: Sufficient for holding 6 to 7 decimal digits


size: 4 bytes

class JavaExample {
public static void main(String[] args) {

float num = 19.98f;


[Link](num);

6
[Link]-V JAVA_NOTES

}
} Output:19.98
boolean: holds either true of false.

class JavaExample {
public static void main(String[] args) {

boolean b = false;
[Link](b);
}
}
Output:
false
char: holds characters.
size: 2 bytes

class JavaExample {
public static void main(String[] args) {

char ch = 'Z';
[Link](ch);
}
}
Output:
Z

Literals in Java
A literal is a fixed value that we assign to a variable in a Program.

int num=10;
Here value 10 is a Integer literal.

char ch = 'A';
7
[Link]-V JAVA_NOTES

Here A is a char literal

Integer Literal

Integer literals are assigned to the variables of data type byte, short, int and long.

byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;

Float Literals

Used for data type float and double.

double num1 = 22.4;


float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.

Char and String Literal

Used for char and String type.

char ch = 'Z';
String str = "BeginnersBook";

Variables in Java

A variable is a name which is associated with a value that can be changed. For example when I
write int i=10; here variable name is i which is associated with value 10, int is a data type that
represents that this variable can hold integer values. We will cover the data types in the next
tutorial. In this tutorial, we will discuss about variables.

8
[Link]-V JAVA_NOTES

How to Declare a variable in Java


To declare a variable follow this syntax:

data_type variable_name = value;


here value is optional because in java, you can declare the variable first and then later assign the
value to it.

For example: Here num is a variable and int is a data type. We will discuss the data type in next
tutorial so do not worry too much about it, just understand that int data type allows this num
variable to hold integer values. You can read data types here but I would recommend you to
finish reading this guide before proceeding to the next one.

int num;
Similarly we can assign the values to the variables while declaring them, like this:

char ch = 'A';
int number = 100;
or we can do it like this:

char ch;
int number;
...
ch = 'A';
number = 100;

Variables naming convention in java


1) Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid
because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case letter, for
example int number; For lengthy variables names that has more than one words do it like this: int
smallNumber; int bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.

9
[Link]-V JAVA_NOTES

Types of Variables in Java


There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable

Static (or class) Variable


Static variables are also known as class variable because they are associated with the class and
common for all the instances of class. For example, If I create three objects of a class and access
this static variable, it would be common for all, the changes made to the variable using one of the
object would reflect when you access it through other objects.

Example of static variable

public class StaticVarExample {


public static String myClassVar="class or static variable";

public static void main(String args[]){


StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

//changing the value of static variable using obj2


[Link] = "Changed Text";

//All three will display "Changed Text"


[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}

10
[Link]-V JAVA_NOTES

}
Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
As you can see all three statements displayed the same output irrespective of the instance
through which it is being accessed. That’s is why we can access the static variables without using
the objects like this:

[Link](myClassVar);
Do note that only static variables can be accessed like this. This doesn’t apply for instance and
local variables.

Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike static variable,
instance variables have their own separate copy of instance variable. We have changed the
instance variable value using object obj2 in the following program and when we displayed the
variable using all three objects, only the obj2 value got changed, others remain unchanged. This
shows that they have their own copy of instance variable.

Example of Instance variable

public class InstanceVarExample {


String myInstanceVar="instance variable";

public static void main(String args[]){


InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();

[Link]([Link]);
[Link]([Link]);
11
[Link]-V JAVA_NOTES

[Link]([Link]);

[Link] = "Changed Text";

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
Output:
instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable
These variables are declared inside method of the class. Their scope is limited to the method
which means that You can’t change their values and access them outside of the method.

In this example, I have declared the instance variable with the same name as local variable, this
is to demonstrate the scope of local variables.

Example of Local variable

public class VariableExample {


// instance variable
public String myVar="instance variable";

public void myMethod(){

12
[Link]-V JAVA_NOTES

// local variable
String myVar = "Inside Method";
[Link](myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

/* We are calling the method, that changes the


* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
[Link]("Calling Method");
[Link]();
[Link]([Link]);
}
}
Output:
Calling Method
Inside Method

instance variable
If I hadn’t declared the instance variable and only declared the local variable inside method then
the statement [Link]([Link]); would have thrown compilation error. As you
cannot change and access local variables outside the method.

13
[Link]-V JAVA_NOTES

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.

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.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

o Random access: We can get any data located at an index position.

Disadvantages

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

o Single Dimensional Array

o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

14
[Link]-V JAVA_NOTES

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array

1. arrayRefVar=new datatype[size];

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

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

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

15
[Link]-V JAVA_NOTES

Operators

An operator is a character that represents an action, for example + is an arithmetic operator that
represents addition.

Types of Operator in Java


1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators


Basic arithmetic operators are: +, -, *, /, %
+ is for addition.

– is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0

Example of Arithmetic Operators

public class ArithmeticOperatorDemo {


public static void main(String args[]) {
int num1 = 100;
int num2 = 20;

[Link]("num1 + num2: " + (num1 + num2) );


[Link]("num1 - num2: " + (num1 - num2) );
[Link]("num1 * num2: " + (num1 * num2) );
[Link]("num1 / num2: " + (num1 / num2) );
[Link]("num1 % num2: " + (num1 % num2) );

16
[Link]-V JAVA_NOTES

}
}
Output:

num1 + num2: 120


num1 - num2: 80
num1 * num2: 2000
num1 / num2: 5
num1 % num2: 0
Checkout these java programs related to arithmetic Operators in Java:

2) Assignment Operators
Assignments operators in java are: =, +=, -=, *=, /=, %=
num2 = num1 would assign value of variable num1 to the variable.
num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1

Example of Assignment Operators

public class AssignmentOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
[Link]("= Output: "+num2);

num2 += num1;
[Link]("+= Output: "+num2);

num2 -= num1;
[Link]("-= Output: "+num2);

num2 *= num1;
[Link]("*= Output: "+num2);

num2 /= num1;
[Link]("/= Output: "+num2);

17
[Link]-V JAVA_NOTES

num2 %= num1;
[Link]("%= Output: "+num2);
}
}
Output:

= Output: 10
+= Output: 20
-= Output: 10
*= Output: 100
/= Output: 10
%= Output: 0
3) Auto-increment and Auto-decrement Operators
++ and —
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

public class AutoOperatorDemo {


public static void main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
[Link]("num1++ is: "+num1);
[Link]("num2-- is: "+num2);
}
}
Output:

num1++ is: 101


num2-- is: 199
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional statements
and loops for evaluating a condition.

Logical operators in java are: &&, ||, !

18
[Link]-V JAVA_NOTES

Let’s say we have two boolean variables b1 and b2.

b1&&b2 will return true if both b1 and b2 are true else it would return false.

b1||b2 will return false if both b1 and b2 are false else it would return true.

!b1 would return the opposite of b1, that means it would be true if b1 is false and it would return
false if b1 is true.

Example of Logical Operators

public class LogicalOperatorDemo {


public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;

[Link]("b1 && b2: " + (b1&&b2));


[Link]("b1 || b2: " + (b1||b2));
[Link]("!(b1 && b2): " + !(b1&&b2));
}
}
Output:

b1 && b2: false


b1 || b2: true
!(b1 && b2): true
5) Comparison(Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

19
[Link]-V JAVA_NOTES

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

Example of Relational operators

Note: This example is using if-else statement which is our next tutorial, if you are finding it
difficult to understand then refer if-else in Java.

public class RelationalOperatorDemo {


public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if (num1==num2) {
[Link]("num1 and num2 are equal");
}
else{
[Link]("num1 and num2 are not equal");
}

if( num1 != num2 ){


[Link]("num1 and num2 are not equal");
}
else{
[Link]("num1 and num2 are equal");
}

if( num1 > num2 ){


[Link]("num1 is greater than num2");
}
else{
[Link]("num1 is not greater than num2");
}

if( num1 >= num2 ){


[Link]("num1 is greater than or equal to num2");
}
else{
[Link]("num1 is less than num2");
}

if( num1 < num2 ){


[Link]("num1 is less than num2");
20
[Link]-V JAVA_NOTES

}
else{
[Link]("num1 is not less than num2");
}

if( num1 <= num2){


[Link]("num1 is less than or equal to num2");
}
else{
[Link]("num1 is greater than num2");
}
}
}
Output:

num1 and num2 are not equal


num1 and num2 are not equal
num1 is not greater than num2
num1 is less than num2
num1 is less than num2
num1 is less than or equal to num2
Check out these related java programs related to relational operators:

6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */

Bitwise operator performs bit by bit processing.


num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits are
equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the binary
form of num1 and num2 only second last bits are matching.

num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is 1,
else it returns 0. In our case it would return 31 which is 00011111

num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not
equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101

21
[Link]-V JAVA_NOTES

~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example
it would return -12 which is signed 8 bit equivalent to 11110100

num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100

Note: In the example below we are providing 2 at the right side of this shift operator that is the
reason bits are moving two places to the left side. We can change this number and bits would be
moved by the number of bits specified on the right side of the operator. Same applies to the right
side operator.

num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and
assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010

Example of Bitwise Operators

public class BitwiseOperatorDemo {


public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;

result = num1 & num2;


[Link]("num1 & num2: "+result);

result = num1 | num2;


[Link]("num1 | num2: "+result);

result = num1 ^ num2;


[Link]("num1 ^ num2: "+result);

result = ~num1;
[Link]("~num1: "+result);

result = num1 << 2;


[Link]("num1 << 2: "+result); result = num1 >> 2;
[Link]("num1 >> 2: "+result);
}
}

22
[Link]-V JAVA_NOTES

Output:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:

variable num1 = (expression) ? value if true : value if false


If the expression results true then the first value before the colon (:) is assigned to the variable
num1 else the second value is assigned to the num1.

Example of Ternary Operator

public class TernaryOperatorDemo {

public static void main(String args[]) {


int num1, num2;
num1 = 25;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
[Link]( "num2: "+num2);

/* num1 is equal to 25 that's why


* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 25) ? 100: 200;
[Link]( "num2: "+num2);
}
}
Output:

num2: 200
num2: 100

23
[Link]-V JAVA_NOTES

Operator
This determines which operator needs to be evaluated first if an expression has more than one
operator. Operator with higher precedence at the top and lower precedence at the bottom.
Unary Operators
++ – – ! ~

Multiplicative
* /%

Additive
+ –

Shift
<< >> >>>

Relational
> >= < <=

Equality
== !=

Bitwise AND
&

Bitwise XOR
^

Bitwise OR
|

Logical AND
&&

Logical OR
||

24
[Link]-V JAVA_NOTES

Ternary
?:

Assignment
= += -= *= /= %= > >= < <= &= ^= |=

Control Statements:

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.

1. Decision Making statements

o if statements

o switch statement

2. Loop statements

o do while loop

o while loop

o for loop

o for-each loop

3. Jump statements

o break statement

o continue statement

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.

25
[Link]-V JAVA_NOTES

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.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

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

[Link]

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {

26
[Link]-V JAVA_NOTES

6. [Link]("x + y is greater than 20");


7. }
8. }
9. }

Output:

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:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {

27
[Link]-V JAVA_NOTES

8. [Link]("x + y is greater than 20");


9. }
10. }
11. }
Output: x + y is greater than 20

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.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";

28
[Link]-V JAVA_NOTES

4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }

Output:

Delhi

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.

Syntax of Nested if-statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }

29
[Link]-V JAVA_NOTES

Consider the following example.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";

4. if([Link]("India")) {
5. if([Link]("Meerut")) {
6. [Link]("Your city is Meerut");
7. }else if([Link]("Noida")) {
8. [Link]("Your city is Noida");
9. }else {
10. [Link]([Link](",")[0]);
11. }
12. }else {
13. [Link]("You are not living in India");
14. }
15. }
16. }

Output:

Delhi

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:

30
[Link]-V JAVA_NOTES

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

o Cases cannot be duplicate

o Default statement is executed when any of the case doesn't match the value of expression.
It is optional.

o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.

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

1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }

31
[Link]-V JAVA_NOTES

Consider the following example to understand the flow of the switch statement.

[Link]

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }

Output:

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.

32
[Link]-V JAVA_NOTES

1. for loop

2. while loop

3. do-while loop

Let's understand the loop statements one by one.

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.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

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

33
[Link]-V JAVA_NOTES

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

[Link]

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. [Link]("The sum of first 10 natural numbers is " + sum);
9. }
10. }

Output:

The sum of first 10 natural numbers is 55

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.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

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

[Link]

1. public class Calculation {


2. public static void main(String[] args) {

34
[Link]-V JAVA_NOTES

3. // TODO Auto-generated method stub


4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

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.

1. while(condition){
2. //looping statements
3. }

35
[Link]-V JAVA_NOTES

The flow chart for the while loop is given in the following image.

Calculation .java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

36
[Link]-V JAVA_NOTES

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.

1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.

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

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;

37
[Link]-V JAVA_NOTES

5. [Link]("Printing the list of first 10 even numbers \n");


6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
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.

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.

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.

38
[Link]-V JAVA_NOTES

[Link]

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

[Link]

1. public class Calculation {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:

39
[Link]-V JAVA_NOTES

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


7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. [Link](k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }

Output:

0
1
2
3
4
5

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.

40
[Link]-V JAVA_NOTES

1. public class ContinueExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. [Link](j);
14. }
15. }
16. }
17.
18. }

Output:

0
1
2
3
5
1
2
3
5
2
3
5

41
[Link]-V JAVA_NOTES

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the
classes required for input and output operations.

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

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

1) [Link]: standard output stream

2) [Link]: standard input stream

3) [Link]: standard error stream

Let's see the code to print output and an error message to the console.

1. [Link]("simple message");
2. [Link]("error message");

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

1. int i=[Link]();//returns ASCII code of 1st character


2. [Link]((char)i);//will print the character

42
[Link]-V JAVA_NOTES

OutputStream vs InputStream

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.

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.

43
[Link]-V JAVA_NOTES

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.

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 at
IOException the end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException the current input stream.

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


IOException

44
[Link]-V JAVA_NOTES

1. [Link]: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. [Link]: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
• print(): This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method prints the
text on the console and the cursor remains at the end of the text at the console. The
next printing takes place from just here.
Syntax:
[Link](parameter);
Example:

// Java code to illustrate print()


import [Link].*;
class Demo_print {
public static void main(String[] args)
{
// using print()
// all are printed in the
// same line
[Link]("GfG! ");
[Link]("GfG! ");
[Link]("GfG! ");
}
}

Output:
GfG! GfG! GfG!
• println(): This method in Java is also used to display a text on the console. It prints
the text on the console and the cursor moves to the start of the next line at the
console. The next printing takes place from the next line.
Syntax:
[Link](parameter);

45
[Link]-V JAVA_NOTES

Example:

// Java code to illustrate println()


import [Link].*;
class Demo_print {
public static void main(String[] args)
{ // using println()
// all are printed in the
// different line
[Link]("GfG! ");
[Link]("GfG! ");
[Link]("GfG! ");
}
}

Output:
GfG!
GfG!
GfG!

• printf(): This is the easiest of all methods as this is similar to printf in C. Note that
[Link]() and [Link]() take a single argument, but printf() may
take multiple arguments. This is used to format the output in Java.
Example:

46
[Link]-V JAVA_NOTES

// A Java program to demonstrate working of printf() in Java


class JavaFormatter1 {
public static void main(String args[])
{
int x = 100;
[Link](
"Printing simple"
+ " integer: x = %d\n",
x);
// this will print it upto
// 2 decimal places
[Link](
"Formatted with"
+ " precision: PI = %.2f\n",
[Link]);

float n = 5.2f;
// automatically appends zero
// to the rightmost part of decimal
[Link](
"Formatted to "
+ "specific width: n = %.4f\n",
n);
n = 2324435.3f;
// here number is formatted from
// right margin and occupies a
// width of 20 characters
[Link]("Formatted to + "right margin: n =
%20.4f\n", n);
}
}

Output:
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500

47
[Link]-V JAVA_NOTES

3. [Link]: This is the standard error stream that is used to output all the error data
that a program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
• print()
• println()
• printf()
Example:

// Java code to illustrate standard


// input output streams

import [Link].*;
public class SimpleIO {

public static void main(String args[])


throws IOException
{

// InputStreamReader class to read input


InputStreamReader inp = null;

// Storing the input in inp


inp = new InputStreamReader([Link]);

[Link]("Enter characters, "


+ " and '0' to quit.");
char c;
do {
c = (char)[Link]();
[Link](c);
} while (c != '0');
}
}

Input:
GeeksforGeeks0

Output:
Enter characters, and '0' to quit.
G
e
e

48
[Link]-V JAVA_NOTES

k
s
f
o
r
G
e
e
k
s
0

Java Scanner

Scanner class in Java is found in the [Link] package. Java provides various ways to read input
from the keyboard, the [Link] class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular
expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double, byte, float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.21505OOPs Concepts in Java

The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(),
etc. To get a single character from the scanner, you can call next().charAt(0) method which
returns a single character.

49
[Link]-V JAVA_NOTES

Java Scanner Class Declaration

1. public final class Scanner


2. extends Object
3. implements Iterator<String>

How to get Java Scanner

To get the instance of Java Scanner which reads input from the user, we need to pass the input
stream ([Link]) in the constructor of Scanner class. For Example:

Scanner in = new Scanner([Link]);

To get the instance of Java Scanner which parses the strings, we need to pass the strings in the
constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");

System Class

The System class of java contains several useful class fields and methods. It also provides
facilities like standard input, standard output, and error output Streams. It can't be instantiated.

The Java System class comes in the module of "[Link]" & in the package of "[Link]".

In Java System Class, we have 3 different types of field and 28 different types of method.

50
[Link]-V JAVA_NOTES

Java System Class consists of following fields:-19.2M406

HTML Tutorial

SN Modifier and Type Field Description

1 static PrintStrean err The "standard" error output stream.

2 static InputStream in The "standard" input stream.

3 static PrintStream out The "standard" output stream.

Java System class Methods:

Java System Class consists of following methods:-

SN Method Description

1 arraycopy(object src, int srcPos, object dest, This method copies subsequence components of a
int destPos, int length) specified source array to the specified destination
array.

2 clearProperty(String key) This method removes the system property indicated


by the specified key.

3 console() This method returns the Console object only if any


Console object is associated with the java virtual
machine.

4 currentTimeMillis() This method returns the current time in the format


of a millisecond. Millisecond will be returned as a
unit of time.

51
[Link]-V JAVA_NOTES

5 exit(int status) This method terminates the current Java virtual


machine running on the system. This method takes
the status code as an argument.

6 gc() This method runs the garbage collector

7 getenv() This method returns a string map view of the


current system environment. Here string map is
unmodifiable, and the environment is system
dependent.

8 getLogger(String name, RecourseBundle This method returns the localizable instance of a


bundle logger. Further, this instance can be used for caller's
use.

9 getLogger(String name) This method returns an instance of a logger.


Further, this instance can be used for caller's use.

10 getenv(String name) This method returns the value of environment


variable which is specified and system dependent
external named value.

11 getProperties() This method returns the properties of the current


system. Here properties are the properties that our
JVM gets from our operating system

12 getProperty(String key) This method returns the property of a system which


is indicated by a specified key.

13 getProperty(String key,String def) This method returns the property of a system which
is indicated by a specified key.

52
[Link]-V JAVA_NOTES

14 getSecurityManager() This method returns an interface of System


Security.

15 identityHashCode(Object x) This method returns hash code for the specified


object. It is returned by the default method
hashCode().

16 inheritedChannel() throws IOException This method returns channel inherited from an


entity that created this Java virtual machine.

17 lineSeparator() This method returns line separator string which is


system dependent. It returns the same value every
time.

18 load(String filename) This method loads file specified by the filename


argument. Here argument must be an absolute path
name.

19 mapLibraryName(String libname) This method maps a library name into the platform-
specific string which represents a native library.

20 nanoTime() This method returns high-resolution time source in


nanoseconds of running Java virtual machine. It
returns the current value of JVM.

21 runFinalizersOnExit(boolean value) This method runs finalization methods which can


be of any objects pending finalization.

53
[Link]-V JAVA_NOTES

22 runFinalization() This method runs finalization methods which can


be of any objects pending finalization.

23 setErr(PrintStream err) This method reassigns the "standard" error output


stream.

24 setIn(PrintStream in) This method reassigns the "standard" input stream.

25 setOut(PrintStream out) This method reassigns the standard output stream.

26 setSecurityManager(SecurityManager s) This method sets the system security.

27 setProperties(Properties props) This method sets the properties of the system to the
argument of properties.

28 setProperty(String key, String value ) This method sets the property of a system which is
indicated by a key.

54
[Link]-V JAVA_NOTES

The print() and println() methods in Java are used to print text on the console for the user
to see. Both of these methods are identical in terms of functionality except for one minor
difference that will be highlighted below. But first, let’s have a look at each function
individually.

1 . print()

The print() method has various overloaded forms that take different data types as parameters;
hence, the print() method can print strings, integers, floats, objects, and other supported data
types in Java.

print() keeps the cursor at the end of the text after printing; the next print takes place from there.

2 . println()

println() has the same overloaded forms as print() and is, thus, able to deal with several
supported data types. println() is only different from print() in the way that println() shifts the
cursor on the console to the beginning of the next line when it is done printing. This is why,
in println(), the subsequent print is printed in the next line. Have a look at the difference below:

55
[Link]-V JAVA_NOTES

UNIT-II

What is an object

An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc. It can be physical or logical (tangible
and intangible). The example of an intangible object is the banking
system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object
such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique
ID. The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify each object
uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white,


known as its state. It is used to write, so writing is its behavior.

56
[Link]-V JAVA_NOTES

An object is an instance of a class. A class is a template or blueprint


from which objects are created. So, an object is the instance(result) of
a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class

A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created. It is a logical
entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

57
[Link]-V JAVA_NOTES

CONSTRUCTOR:

Constructor is a block of code that initializes the newly created object. A constructor resembles
an instance method in java but it’s not a method as it doesn’t have a return type. In short
constructor and method are different(More on this at the end of this guide). People often refer
constructor as special type of method in Java.
Constructor has same name as the class and looks like this in a java code.
public class MyClass{
//This is the constructor
MyClass(){
}
..
}
Note that the constructor name matches with the class name and it doesn’t have a return type.
How does a constructor work
To understand the working of constructor, let's take an example. lets say we have a
class MyClass.
When we create the object of MyClass like this:
MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and invokes the constructor to
initialize this newly created object.

A simple constructor program in java


Here we have created an object obj of class Hello and then we displayed the instance
variable name of the object. As you can see that the output is Beginners which is what we have
passed to the name during initialization in constructor. This shows that when we created the
object obj the constructor got invoked. In this example we have used this keyword, which refers
to the current object, object obj in this example. We will cover this keyword in detail in the next
tutorial.
public class Hello {
String name;

58
[Link]-V JAVA_NOTES

//Constructor
Hello(){
[Link] = "Beginners";
}
public static void main(String[] args) {
Hello obj = new Hello();
[Link]([Link]);
}
}

Types of Constructors:
There are three types of constructors: Default, No-arg constructor and Parameterized.

59
[Link]-V JAVA_NOTES

DEFAULT CONSTRUCTOR:

If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf. This constructor is known as default constructor. You
would not find it in your source code(the java file) as it would be inserted into the code during
compilation and exists in .class file. This process is shown in the diagram below:

If you implement any constructor then you no longer receive a default constructor from Java
compiler.

NO-ARG CONSTRUCTOR:
Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.
Although you may see some people claim that that default and no-arg constructor is same but in
fact they are not, even if you write public Demo() { } in your class Demo it cannot be called
default constructor since you have written the code of it.

60
[Link]-V JAVA_NOTES

Example: no-arg constructor


class Demo
{
public Demo()
{
[Link]("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor

PARAMETERIZED CONSTRUCTOR:

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
Example: parameterized constructor
In this example we have a parameterized constructor with two parameters id and name. While
creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.
public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
[Link] = id;
[Link] = name;
}

61
[Link]-V JAVA_NOTES

void info(){
[Link]("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
[Link]();
[Link]();
}
}
Output:
Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Example2: parameterized constructor


In this example, we have two constructors, a default constructor and a parameterized constructor.
When we do not pass any parameter while creating the object using new keyword then default
constructor is invoked, however when you pass a parameter then parameterized constructor that
matches with the passed parameters list gets invoked.
class Example2
{
private int var;
//default constructor
public Example2()
{
[Link] = 10;
}
//parameterized constructor
public Example2(int num)
{

62
[Link]-V JAVA_NOTES

[Link] = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
[Link]("var is: "+[Link]());
[Link]("var is: "+[Link]());
}
}
Output:
var is: 10
var is: 100

Overloading and Overriding :


Overloading occurs when two or more methods in one class have the same method name but
different parameters.
Overriding occurs when two methods have the same method name and parameters. One of the
methods is in the parent class, and the other is in the child class. Overriding allows a child class
to provide the specific implementation of a method that is already present in its parent class.
The two examples below illustrate their differences:

63
[Link]-V JAVA_NOTES

here key differences:


Overloading:
Must have at least two methods by the same name in the class.
Must have a different number of parameters.
If the number of parameters is the same, then it must have different types of parameters.
Overloading is known as compile-time polymorphism.
Overriding:
Must have at least one method by the same name in both parent and child classes.
Must have the same number of parameters.
Must have the same parameter types.
Overriding is known as runtime polymorphism.

64
[Link]-V JAVA_NOTES

ACCESS CONTROL:
Access control is a mechanism, an attribute of encapsulation which restricts the access of certain
members of a class to specific parts of a program. Access to members of a class can be
controlled using the access modifiers. There are four access modifiers in Java. They are:
public
protected
default
private

If the member (variable or method) is not marked as either public or protected or private, the
access modifier for that member will be default. We can apply access modifiers to classes also.

Among the four access modifiers, private is the most restrictive access modifier and public is the
least restrictive access modifier. Syntax for declaring a access modifier is shown below:

access-modifier data-type variable-name;

65
[Link]-V JAVA_NOTES

What is the use of access modifiers?


access modifiers are used to restrict the access of members of a class, in particular data members
(fields)

STATIC AND FIXED METHODS:

Static Method in java:

Static methods are methods that do not operate on objects. A static method acts related to a class
declare a static method by using the static keyword as a modifier. To declare a method as static is
as follows:
Static returntype methodname(parameter)
{
//body of the method
}

We can call a static method from the outside of a class as follow:


[Link](parameters);

A method declared as static has several restrictions:


-> They can only call the other static method.
->They must only access static data.
->They cannot refer to this in any other way.
Program:
class staticdemo
{
static void print()
{
[Link]("java programming");
}

66
[Link]-V JAVA_NOTES

public static void main(String args[])


{
print();
}
}
Fixed method:
A fixed method is one which cannot be overridden by a subclass. A fixed method can be
declared by prefixing the word-final before a method. We can use the keyword final to donate a
constant.
Program:
class finaldemo
{
public static void main(String args[])
{
double paperwidth=8.5;
double paperheight=11;
[Link]("paper size in centimeter:"
+paperwidth*CM_PER_INCH+"by"+paperheight*CM_PER_INCH);
public static final double CM_PER_INCH=2.45;
}
}
JAVA INNER CLASSES:

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is
to group classes that belong together, which makes your code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create an object of the
inner class:
class OuterClass {
int x = 10;

class InnerClass {

67
[Link]-V JAVA_NOTES

int y = 5;
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}

// Outputs 15 (5 + 10)

Private Inner Class


Unlike a "regular" class, an inner class can be private or protected. If you don't want outside
objects to access the inner class, declare the class as private:
class OuterClass {
int x = 10;

private class InnerClass {


int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);

68
[Link]-V JAVA_NOTES

}
}

If we try to access a private inner class from an outside class, an error occurs:
[Link][Link] error: [Link] has private access in OuterClass
[Link] myInner = [Link] InnerClass();

Static Inner Class


An inner class can also be static, which means that you can access it without creating an object
of the outer class:
Example
class OuterClass {
int x = 10;

static class InnerClass {


int y = 5;
}
}

public class Main {


public static void main(String[] args) {
[Link] myInner = new [Link]();
[Link](myInner.y);
}
}

// Outputs 5

69
[Link]-V JAVA_NOTES

Access Outer Class From Inner Class


One advantage of inner classes, is that they can access attributes and methods of the outer class:
Example
class OuterClass {
int x = 10;

class InnerClass {
public int myInnerMethod() {
return x;
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link]([Link]());
}
}

// Outputs 10

70
[Link]-V JAVA_NOTES

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

String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The [Link] class implements Serializable, Comparable and CharSequence interfaces

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder
classes implement it. It means, we can create strings in Java by using these three classes.

71
[Link]-V JAVA_NOTES

The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.
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 [Link] class is used to create a string object.
How to create a string object?
There are two ways to create String object:
By string literal
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

72
[Link]-V JAVA_NOTES

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
2) By new keyword

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


In such case, JVM
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


[Link]

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
[Link](s1);
[Link](s2);
[Link](s3);
}}

73
[Link]-V JAVA_NOTES

INHERITANCE – TYPES & IMPORTANCE OF INHERITANCE :

Inheritance is one of the most important concepts of Object-Oriented Programming. Inheritance


is the capability of one class to inherit capabilities or properties from another class in Java. For
instance, we are humans.
We inherit certain properties from the class ‘Human’ such as the ability to speak, breathe, eat,
drink, [Link] can also take the example of cars. The class ‘Car’ inherits its properties from the
class ‘Automobiles’ which inherits some of its properties from another class ‘Vehicles’.
The object-oriented languages express this inheritance relationship by allowing one class to
inherit from another. Thus a model of these languages is much closer to the real-world.
The principle behind this kind of division is that each subclass (child-class) shares common
characteristics with the class from which it is derived.

Automobiles and Pulled Vehicles are subclasses of Vehicles.


Vehicles are the base class or superclass of Automobiles and pulled Vehicles.
Car and Bus are sub-classes or derived classes of Automobiles.
Automobiles are the base class or superclass of Car and Bus.
Why we need Java Inheritance?
There are several reasons why inheritance was introduced into Object-oriented languages. We
will discuss some major reasons behind the introduction of inheritance.

74
[Link]-V JAVA_NOTES

The capability to express inheritance relationships ensures the closeness with the real-world
models.
Another reason is the idea of reusability. One can derive a new class (sub-class) from an existing
class and add new features to it without modifying its parent class. There is no need to rewrite
the parent class in order to inherit it.
One reason is the transitive nature. If class A inherits properties from another class B, then all
subclasses of A will automatically inherit properties from B. This property is called the transitive
nature of inheritance.
Note: A subclass defines only those features that are unique to it.
For example, the class Student inherits from the class Person. Then although Student is a person,
the reverse is not true. A Person need not be a Student. The class Student has properties that it
does not share with class Person.
For instance, the Student has a marks-percentage, but the Person does not have.
Important Terms in Java Inheritance
1. Class: Class is a user-defined datatype in Java that is basically a group of objects. It is a
blueprint or template from which we create objects.
2. Super Class: The class whose features and functionalities are being inherited or used is
known as the superclass or a base class or a parent class.
3. Sub Class: The class that inherits the properties and features from another class is known as a
subclass or a derived class or extended class or child class. The subclass can add its own features
and functions in addition to the fields and methods of its superclass or the parent class.
4. The extends keyword: The keyword extends is used by child class while inheriting the parent
class.
5. The super keyword: The super keyword is similar to this keyword. The following are some
cases where we use super keyword :
There are some situations where the members of the superclass and the subclass have the same
names, then the super keyword is used to differentiate the members of the superclass from the
members of the subclass.
To invoke the superclass constructor from the subclass.

75
[Link]-V JAVA_NOTES

Syntax of using Inheritance in Java:


class BaseClass
{
//methods and fields
}
class DerivedClass extends BaseClass
{
//methods and fields
}

Single Inheritance in Java


In single inheritance, there is a single child class that inherits properties from one parent class.
In the following diagram, class A is a base class that is derived from class B. It is also known as
single-level inheritance.

Multilevel Inheritance in Java


In this type of inheritance, the child or derived class inherits the features of the superclass and
simultaneously this child class acts as a superclass for another derived class.
In the following diagram, class A is a base class that is derived from class B, which in turn, acts
as a base class for a derived class C.

76
[Link]-V JAVA_NOTES

Hierarchical Inheritance in Java


In Hierarchical Inheritance, one class acts as a superclass (base class) for more than one subclass.
More than one subclass can inherit the features of a base class.
In the following diagram, class A is a base class for the derived classes B, C, and D.

Multiple Inheritance in Java


In Multiple Inheritance, one child or subclass class can have more than one base class or
superclass and inherit features from every parent class which it inherits.

77
[Link]-V JAVA_NOTES

We have already discussed that Java does not support multiple inheritances with classes. We can
achieve multiple inheritances only with the help of Interfaces.
In the following diagram, Class C inherits from interfaces A and B.

Hybrid Inheritance in Java


It is a combination of two or more types of inheritance. The hybrid inheritance is also not
possible with classes because Java doesn’t support multiple inheritance with classes. We can
achieve hybrid inheritance only through Interfaces.
In the following diagram, class A is the base class for subclasses B and C. And, class D inherits
both the classes B and C.

78
[Link]-V JAVA_NOTES

Abstract class :
A class which is declared with the abstract keyword is known as an abstract class in Java
. It can have abstract and non-abstract methods (method with the body).
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object
does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java

79
[Link]-V JAVA_NOTES

Abstract class (0 to 100%)


Interface (100%)
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
and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
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{

80
[Link]-V JAVA_NOTES

abstract void run();


}
class Honda4 extends Bike{
void run(){[Link]("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
}

Wrapper Classes :

A Wrapper class is a class whose object wraps or contains primitive data types. When we create
an object to a wrapper class, it contains a field and in this field, we can store primitive data types.
In other words, we can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
The classes in [Link] package handles only objects and hence wrapper classes help in this case
also.
Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
An object is needed to support synchronization in multithreading.

81
[Link]-V JAVA_NOTES

Primitive Data types and their Corresponding Wrapper class

Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding


wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.
Example:

// Java program to demonstrate Autoboxing

import [Link];
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object conversion


Character a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();

82
[Link]-V JAVA_NOTES

// Autoboxing because ArrayList stores only objects


[Link](25);

// printing the values from object


[Link]([Link](0));
}
}

Output: 25

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object


of a wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double, etc.

// Java program to demonstrate Unboxing


import [Link];

class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';

// unboxing - Character object to primitive conversion


char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


[Link](24);

// unboxing because get method returns an Integer object

83
[Link]-V JAVA_NOTES

int num = [Link](0);

// printing the values from primitive data types


[Link](num);
}
}

UNIT-III
GUI COMPONENTS
What is Swing in Java?
Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components.
Swing provides a rich set of widgets and packages to make sophisticated GUI components for
Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java
programs that provide GUI.
The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java GUI programming components like
button, textbox, etc. from the library and do not have to create the components from scratch.
Java Swing class Hierarchy Diagram

84
[Link]-V JAVA_NOTES

Java Swing Class Hierarchy Diagram


All components in Java Swing are JComponent which can be added to container classes.
What is a Container Class?
Container classes are classes that can have other components on it. So for creating a Java GUI,
we need at least one container object. There are 3 types of Java Swing containers.
Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to
organize the components on to a window.
Frame: It is a fully functioning window with its title and icons.
Dialog: It can be thought of like a pop-up window that pops out when a message has to be
displayed. It is not a fully functioning window like the Frame.

GUI Components in Java: Definition & Examples


The Graphical User Interface
In the world of computer programming, there is an essential visible display of items that the user
sees and interacts with on the screen, which is known as the graphical user interface (GUI).
Containers and Components
The most basic GUI elements you will be dealing with in Java include what are known as
containers and components. A container is used to store the items the user will see on display,
such as a panel or a frame (main window). These are the very core of what holds everything
together and are the primary skeletal system of the GUI as a whole.
Components can be described as the add-ons or extensions to the containers that help to fill in
the content and make up the rest of the user interface. Examples can include things such as a
textbox, a button, a checkbox, or even a simple label. When you combine both containers and
components, you begin to understand the bigger picture of what the GUI is and why it represents
the core of the user experience for any program or application.
Classes of GUI
The GUI in Java can be broken down into two separate classes known as the Abstract Window
Toolkit (AWT) and Swing. The Abstract Window Toolkit is the older of the two and is mostly
the set of tools or programs that give a programmer the ability to create the components of the

85
[Link]-V JAVA_NOTES

GUI itself, such as the buttons or scroll bars. They are known as the heavyweight
components and are explicitly bound by the platform or operating system they are being used on.
Swing can be described as the newest form of the two, doing the same thing as AWT, but as
extensions to the AWT itself. These are known as the lightweight components and are entirely
independent of the platform or operating system, which give them much more freedom and
flexibility than the AWT. Without these tools in place, it would not be possible to create
anything relating to the GUI, which makes these tools the origin or starting point of what makes
the elements of the user interface become a reality.

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The [Link] package provides many event classes and Listener interfaces
for event handling.
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change in state of any object. For Example
: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

86
[Link]-V JAVA_NOTES

Components of Event Handling


Event handling has three main components,
Events : An event is a change in state of an object.
Events Source : Event source is an object that generates an event.
Listeners : A listener is an object that listens to the event. A listener gets notified when an event
occurs.
How Events are handled?
A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by
a number of Java packages, like [Link], [Link] and [Link].

87
Event Classes Description Listener Interface
generated when button is pressed, menu-item is selected, list-item is
[Link]-V JAVA_NOTES
ActionListener
double clicked
generated when mouse is dragged, moved,clicked,pressed or released
MouseEvent MouseListener
and also when it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

generated when window is activated, deactivated, deiconified,


WindowEvent WindowListener
iconified, opened or closed

ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener

ContainerEvent generated when component is added or removed from container ContainerListener

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses keyboard focus FocusListener

88
[Link]-V JAVA_NOTES

Steps to handle events:


Implement appropriate interface in the class.
Register the component with the listener.

Steps to perform Event Handling


Following steps are required to perform event handling:
Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}

Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

89
[Link]-V JAVA_NOTES

Java Event Handling Code


We can put the event handling code into one of the following places:
Within class
Other class
Anonymous class
Java event handling by implementing ActionListener

import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent()
{
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
[Link](this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new AEvent();

90
[Link]-V JAVA_NOTES

}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
28.1M
552

Java Try Catch ext


2) Java event handling by outer class

import [Link].*;
import [Link].*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
Outer o=new Outer(this);
[Link](o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);

91
[Link]-V JAVA_NOTES

setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import [Link].*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
[Link]=obj;
}
public void actionPerformed(ActionEvent e){
[Link]("welcome");
}
}

3) Java event handling by anonymous class

import [Link].*;
import [Link].*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");

92
[Link]-V JAVA_NOTES

[Link](50,120,80,30);

[Link](new ActionListener(){
public void actionPerformed(){
[Link]("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information or
get input from the user. The JOptionPane class inherits JComponent class.

The JOptionPane is a subclass of JComponent class which includes static methods for creating
and customizing modal dialog boxes using a simple code. The JOptionPane is used instead
of JDialog to minimize the complexity of the code. The JOptionPane displays the dialog boxes
with one of the four standard icons (question, information, warning, and error) or the custom
icons specified by the user.
JOptionPane class is used to display four types of dialog boxes
MessageDialog - dialog box that displays a message making it possible to add icons to alert the
user.

93
[Link]-V JAVA_NOTES

ConfirmDialog - dialog box that besides sending a message, enables the user to answer a
question.
InputDialog - dialog box that besides sending a message, allows entry of a text.
OptionDialog - dialog box that covers the three previous types

Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new parentless


JDialog with the specified title.

static void showMessageDialog(Component It is used to create an information-message


parentComponent, Object message) dialog titled "Message".

static void showMessageDialog(Component It is used to create a message dialog with


parentComponent, Object message, String title, int given title and messageType.
messageType)

static int showConfirmDialog(Component It is used to create a dialog with the options


parentComponent, Object message) Yes, No and Cancel; with the title, Select an
Option.

static String showInputDialog(Component It is used to show a question-message dialog


parentComponent, Object message) requesting input from the user parented to
parentComponent.

void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.

94
[Link]-V JAVA_NOTES

Java JOptionPane Example: showMessageDialog()


import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:

Java JOptionPane Example: showMessageDialog()

import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](f,"Successfully Updated.","Alert",[Link]
_MESSAGE);

95
[Link]-V JAVA_NOTES

}
public static void main(String[] args) {
new OptionPaneExample();
} }
Output:

Java JOptionPane Example: showInputDialog()

import [Link].*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=[Link](f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:
Nested Structure in C in Hindi
Keep Watching

96
[Link]-V JAVA_NOTES

Java JOptionPane Example: showConfirmDialog()

import [Link].*;
import [Link].*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
[Link](this);
[Link](300, 300);
[Link](null);
[Link](JFrame.DO_NOTHING_ON_CLOSE);
[Link](true);
}
public void windowClosing(WindowEvent e) {
int a=[Link](f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
[Link](JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
Output:

97
[Link]-V JAVA_NOTES

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

JLabel() : creates a blank label with no text or image in it.


JLabel(String s) : creates a new label with the string specified.
JLabel(Icon i) : creates a new label with a image on it.
JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified
horizontal alignment

Commonly used methods of the class are :

getIcon() : returns the image that the label displays


setIcon(Icon i) : sets the icon that the label will display to image i
getText() : returns the text that the label will display
setText(String s) : sets the text that the label will display to string s

// Java Program to create a new label


// using constructor - JLabel(String s)
import [Link].*;
import [Link].*;
import [Link].*;
class text extends JFrame {

// frame
static JFrame f;

// label to display text

98
[Link]-V JAVA_NOTES

static JLabel l;

// default constructor
text()
{
}

// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("label");

// create a label to display text


l = new JLabel("new text ");

// create a panel
JPanel p = new JPanel();

// add label to panel


[Link](l);

// add panel to frame


[Link](p);

// set the size of frame


[Link](300, 300);

[Link]();
}
}

99
[Link]-V JAVA_NOTES

// Java Program to create a new label


// using constructor - JLabel(String s)
import [Link].*;
import [Link].*;
import [Link].*;
class text extends JFrame {

// frame
static JFrame f;

// label to display text


static JLabel l;

// default constructor
text()
{
}

// main class
public static void main(String[] args)
{
// create a new frame to store text field and button

100
[Link]-V JAVA_NOTES

f = new JFrame("label");

// create a label to display text


l = new JLabel("new text ");

// create a panel
JPanel p = new JPanel();

// add label to panel


[Link](l);

// add panel to frame


[Link](p);

// set the size of frame


[Link](300, 300);

[Link]();
}
}

// Java Program to create a label


// and add image to it .

101
[Link]-V JAVA_NOTES

import [Link].*;
import [Link].*;
import [Link].*;
class text extends JFrame {

// frame
static JFrame f;

// label to display text


static JLabel l;

// default constructor
text()
{
}

// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("label");

// create a new image icon


ImageIcon i = new ImageIcon("f:/[Link]");

// create a label to display image


l = new JLabel(i);

// create a panel
JPanel p = new JPanel();

102
[Link]-V JAVA_NOTES

// add label to panel


[Link](l);

// add panel to frame


[Link](p);

// set the size of frame


[Link](500, 500);

[Link]();
}
}

103
[Link]-V JAVA_NOTES

// Java Program to add a image and string


// to a label with horizontal alignment
import [Link].*;
import [Link].*;
import [Link].*;
class text extends JFrame {

// frame
static JFrame f;

// label to display text


static JLabel l;

// default constructor
text()
{
}

// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("label");

// create a new image icon


ImageIcon i = new ImageIcon("f:/[Link]");

// create a label to display text and image


l = new JLabel("new image text ", i, [Link]);

// create a panel

104
[Link]-V JAVA_NOTES

JPanel p = new JPanel();

// add label to panel


[Link](l);

// add panel to frame


[Link](p);

// set the size of frame


[Link](600, 500);

[Link]();
}
}

105
[Link]-V JAVA_NOTES

JTextField :
JTextField is a part of [Link] 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 :

JTextField() : constructor that creates a new TextField


JTextField(int columns) : constructor that creates a new empty TextField with specified number
of columns.
JTextField(String text) : constructor that creates a new empty text field initialized with the
given string.
JTextField(String text, int columns) : constructor that creates a new empty textField with the
given string and a specified number of columns .
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.

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive


action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener l) no longer receives action events from this textfield.

106
[Link]-V JAVA_NOTES

Java JTextField Example

import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:

107
[Link]-V JAVA_NOTES

Java JTextField Example with ActionListener

import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false);
b1=new JButton("+");
[Link](50,200,50,50);
b2=new JButton("-");
[Link](120,200,50,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();

108
[Link]-V JAVA_NOTES

int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
c=a-b;
}
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:
Stay

109
[Link]-V JAVA_NOTES

Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton class declaration
Let's see the declaration for [Link] class.

public class JButton extends AbstractButton implements Accessible


Commonly used Constructors:

Constructor Description

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.

Commonly used Methods of AbstractButton class:

Methods Description

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

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.

110
[Link]-V JAVA_NOTES

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 addActionListener(ActionListener a) It is used to add the action listener


to this object.

Java JButton Example


import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:

111
[Link]-V JAVA_NOTES

Java JButton Example with ActionListener


import [Link].*;
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
[Link](50,50, 150,20);
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("Welcome to Javatpoint.");
}
});
[Link](b);[Link](tf);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:

112
[Link]-V JAVA_NOTES

Example of displaying image on the button:


import [Link].*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\[Link]"));
[Link](100,100,100, 40);
[Link](b);
[Link](300,400);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output:

113
[Link]-V JAVA_NOTES

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton
class.
JCheckBox class declaration
Let's see the declaration for [Link] class.
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text, no


icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

protected String paramString() It returns a string


representation of this JCheckBox.

114
[Link]-V JAVA_NOTES

Java JCheckBox Example


import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

115
[Link]-V JAVA_NOTES

Java JCheckBox Example with ItemListener


import [Link].*;
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
[Link](150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
[Link](150,150, 50,50);
[Link](checkbox1); [Link](checkbox2); [Link](label);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("C++ Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Java Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](400,400);
[Link](null);
[Link](true);
}

116
[Link]-V JAVA_NOTES

public static void main(String args[])


{
new CheckBoxExample();
}
}
Output:
32.2
OOPs Concepts in Java

java JCheckBox Example: Food Order

import [Link].*;
import [Link].*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
[Link](50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");
[Link](100,100,150,20);

117
[Link]-V JAVA_NOTES

cb2=new JCheckBox("Burger @ 30");


[Link](100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
[Link](100,200,150,20);
b=new JButton("Order");
[Link](100,250,80,30);
[Link](this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if([Link]()){
amount+=100;
msg="Pizza: 100\n";
}
if([Link]()){
amount+=30;
msg+="Burger: 30\n";
}
if([Link]()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
[Link](this,msg+"Total: "+amount);
}

118
[Link]-V JAVA_NOTES

public static void main(String[] args) {


new CheckBoxExample();
}
}
Output:

JTextArea
A JTextArea can handle multiline plain text. Most often, when you have multiline text in a
JTextArea, you will need scrolling capabilities.

This is an example of an application using a java swing JTextArea. It demonstrates how to read,
write and append to the text area.
Source: ([Link])
import [Link].*;
import [Link].*;
import [Link].*;

public class JTextAreaExample extends JFrame {

public JTextAreaExample() {

119
[Link]-V JAVA_NOTES

JTextArea textArea = new JTextArea(10,25);

JPanel panel = new JPanel();


[Link](new FlowLayout());
[Link](textArea);

[Link](panel);
[Link]("JTextAreaExample Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link]();

// Wite text to the text area.


[Link]("This is a string of text.\n");

// Appends the given text to the end of text area.


[Link]("Another line of text");

// read contents of the text area.


String str = [Link]();

public static void main(String[] args) {


[Link](true);
JFrame frame = new JTextAreaExample();
[Link](true);
}}
Output:
$ java JTextAreaExample

120
[Link]-V JAVA_NOTES

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu
. It inherits JComponent
class.
JComboBox class declaration
Let's see the declaration for [Link] class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Act


ionListener, Accessible
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the


specified array
.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector
.

121
[Link]-V JAVA_NOTES

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is


editable.

void addActionListener(ActionListener It is used to add the ActionListener


a) .

void addItemListener(ItemListener i) It is used to add the ItemListener

122
[Link]-V JAVA_NOTES

Java JComboBox Example

import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

123
[Link]-V JAVA_NOTES

Java JComboBox Example with ActionListener


import [Link].*;
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JButton b=new JButton("Show");
[Link](200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
[Link](50, 100,90,20);
[Link](cb); [Link](label); [Link](b);
[Link](null);
[Link](350,350);
[Link](true);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ [Link]([Link]());
[Link](data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

124
[Link]-V JAVA_NOTES

Output:
14.9
Triggers in SQL (Hindi)

Java JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
JList class declaration
Let's see the declaration for [Link] class.

public class JList extends JComponent implements Scrollable, Accessible


Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.

125
[Link]-V JAVA_NOTES

Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) notified each time a change to the selection
occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

ListModel getModel() It is used to return the data model that holds a


list of items displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from


an array of objects.

Java JList Example


import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("Item1");
[Link]("Item2");
[Link]("Item3");
[Link]("Item4");
JList<String> list = new JList<>(l1);

126
[Link]-V JAVA_NOTES

[Link](100,100, 75,75);
[Link](list);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ListExample();
}}
Output:

Java JList Example with ActionListener

import [Link].*;
import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
final JLabel label = new JLabel();
[Link](500,100);
JButton b=new JButton("Show");
[Link](200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("C");

127
[Link]-V JAVA_NOTES

[Link]("C++");
[Link]("Java");
[Link]("PHP");
final JList<String> list1 = new JList<>(l1);
[Link](100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
[Link]("Turbo C++");
[Link]("Struts");
[Link]("Spring");
[Link]("YII");
final JList<String> list2 = new JList<>(l2);
[Link](100,200, 75,75);
[Link](list1); [Link](list2); [Link](b); [Link](label);
[Link](450,450);
[Link](null);
[Link](true);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if ([Link]() != -1) {
data = "Programming language Selected: " + [Link]();
[Link](data);
}
if([Link]() != -1){
data += ", FrameWork Selected: ";
for(Object frame :[Link]()){
data += frame + " ";
}
}
[Link](data);
}

128
[Link]-V JAVA_NOTES

});
}
public static void main(String args[])
{
new ListExample();
}}
Output:
33.6M
725
C++ vs Java

Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
It doesn't have title bar.
JPanel class declaration

public class JPanel extends JComponent implements Accessible

129
[Link]-V JAVA_NOTES

Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

Java JPanel Example


import [Link].*;
import [Link].*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
[Link](50,100,80,30);
[Link]([Link]);
JButton b2=new JButton("Button 2");
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);

130
[Link]-V JAVA_NOTES

[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:

what is mouse event handling in java

An event which indicates that a mouse action occurred in a component. A mouse action is
considered to occur in a particular component if and only if the mouse cursor is over the
unobscured part of the component's bounds when the action happens.

MouseListener and MouseMotionListener in Java


MouseListener and MouseMotionListener is an interface in [Link] package . Mouse
events
are of two types. MouseListener handles the events when the mouse is not in motion. While

131
[Link]-V JAVA_NOTES

MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract functions
that represent these five events.
The abstract functions are :
void mouseReleased(MouseEvent e) : Mouse key is released
void mouseClicked(MouseEvent e) : Mouse key is pressed/released
void mouseExited(MouseEvent e) : Mouse exited the component
void mouseEntered(MouseEvent e) : Mouse entered the component
void mousepressed(MouseEvent e) : Mouse key is pressed

java MouseListener Example


import [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");

132
[Link]-V JAVA_NOTES

}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:

what is adapter class in java


Java adapter classes provide the default implementation of listener interfaces
. If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
It assists the unrelated classes to work combinedly.
It provides ways to use classes in different ways.
It increases the transparency of classes.
It provides a way to include related patterns in the class.

133
[Link]-V JAVA_NOTES

It provides a pluggable kit for developing an application.


It increases the reusability of the class.
The adapter classes are found in [Link], [Link] and [Link] packages
. The Adapter classes with their corresponding listener interfaces are given below.
[Link] Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

134
[Link]-V JAVA_NOTES

Java WindowAdapter Example


In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.

[Link]

// importing the necessary libraries


import [Link].*;
import [Link].*;

public class AdapterExample {


// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
[Link] (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
[Link]();
}
});
// setting the size, layout and
[Link] (400, 400);
[Link] (null);
[Link] (true);
}

// main method

135
[Link]-V JAVA_NOTES

public static void main(String[] args) {


new AdapterExample();
}
}
Output:

what is key event handling in java

An event which indicates that a keystroke occurred in a component. This low-level event is
generated by a component object (such as a text field) when a key is pressed, released, or typed.
... ( KeyAdapter objects implement the KeyListener interface.) Each such listener object gets this
KeyEvent when the event occurs.

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in [Link] package, and it has three
methods.

Interface declaration
Following is the declaration for [Link] interface:

public interface KeyListener extends EventListener

136
[Link]-V JAVA_NOTES

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description

1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.

2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Methods inherited
This interface inherits methods from the following interface:34.
658Difference between JDK, JRE, and JVM
[Link]
Java KeyListener Example
In the following example, we are implementing the methods of the KeyListener interface.
[Link]
// importing awt libraries
import [Link].*;
import [Link].*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample extends Frame implements KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
137
[Link]-V JAVA_NOTES

[Link] (20, 50, 100, 20);


// creating the text area
area = new TextArea();
// setting the location of text area
[Link] (20, 80, 300, 300);
// adding the KeyListener to the text area
[Link](this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the label
when key is pressed
public void keyPressed (KeyEvent e) {
[Link] ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the labe
l when key is released
public void keyReleased (KeyEvent e) {
[Link] ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the label
when a key is typed
public void keyTyped (KeyEvent e) {
[Link] ("Key Typed");
}
// main method

138
[Link]-V JAVA_NOTES

public static void main(String[] args) {


new KeyListenerExample();
}
}
Output:

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.

FlowLayout: It arranges the components in a container like the words on a page. It fills the top
line from left to right and top to bottom. The components are arranged in the order as they are
added i.e. first components appears at top left, if the container is not wide enough to display all

139
[Link]-V JAVA_NOTES

the components, it is wrapped around the line. Vertical and horizontal gap between components
can be controlled. The components can be left, center or right aligned.
BorderLayout: It arranges all the components along the edges or the middle of the container
i.e. top, bottom, right and left edges of the area. The components added to the top or bottom gets
its preferred height, but its width will be the width of the container and also the components
added to the left or right gets its preferred width, but its height will be the remaining height of the
container. The components added to the center gets neither its preferred height or width. It
covers the remaining area of the container.
GridLayout: It arranges all the components in a grid of equally sized cells, adding them from
the left to right and top to bottom. Only one component can be placed in a cell and each region of
the grid will have the same size. When the container is resized, all cells are automatically
resized. The order of placing the components in a cell is determined as they were added.
GridBagLayout: It is a powerful layout which arranges all the components in a grid of cells and
maintains the aspect ration of the object whenever the container is resized. In this layout, cells
may be different in size. It assigns a consistent horizontal and vertical gap among components. It
allows us to specify a default alignment for components within the columns or rows.
BoxLayout: It arranges multiple components in either vertically or horizontally, but not both.
The components are arranged from left to right or top to bottom. If the components are
aligned horizontally, the height of all components will be the same and equal to the largest sized
components. If the components are aligned vertically, the width of all components will be the
same and equal to the largest width components.
CardLayout: It arranges two or more components having the same size. The components
are arranged in a deck, where all the cards of the same size and the only top card are visible at
any time. The first component added in the container will be kept at the top of the deck. The
default gap at the left, right, top and bottom edges are zero and the card components are
displayed either horizontally or vertically.

140
[Link]-V JAVA_NOTES

BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor

FileName: [Link]
import [Link].*;
import [Link].*;

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH

141
[Link]-V JAVA_NOTES

JButton b3 = new JButton("EAST");; // the button will be labeled as EAST


JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

[Link](b1, [Link]); // b1 will be placed in the North Direction


[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center

[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Output:titive questions on Structures

142
[Link]-V JAVA_NOTES

GRAPHICS CONTEXTS AND GRAPHICS OBJECTS IN JAVA

A Java graphics context enables drawing on the screen. A Graphics object manages a graphics
context and draws pixels on the screen that represent text and other graphical object (e.g., lines,
ellipses, rectangles and other polygons).
Displaying graphics in swing:
[Link] class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified
font

143
[Link]-V JAVA_NOTES

Example of displaying graphics in swing:

import [Link].*;
import [Link];

public class DisplayGraphics extends Canvas{

public void paint(Graphics g) {


[Link]("Hello",40,40);
setBackground([Link]);
[Link](130, 30,100, 80);
[Link](30,130,50, 60);
setForeground([Link]);
[Link](130,130,50, 60);
[Link](30, 200, 40,50,90,60);
[Link](30, 130, 40,50,180,40);

}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
[Link](m);

144
[Link]-V JAVA_NOTES

[Link](400,400);
//[Link](null);
[Link](true);
}

Color Class:
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class
creates color by using the given RGBA values where RGBA stands for RED, GREEN, BLUE,
ALPHA or using HSB value where HSB stands for HUE, SATURATION, BRIcomponents. The
value for individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value of alpha
determines the opacity of the color, where 0 or 0.0 stands fully transparent and 255 or 1.0 stands
opaque.

Constructors of Color Class

Color(ColorSpace c, float[] co, float a) : Creates a color in the specified ColorSpace with the
color components specified in the float array and the specified alpha.
Color(float r, float g, float b) : creates a opaque color with specified RGB components(values
are in range 0.0 – 0.1)
Color(float r, float g, float b, float a) : creates a color with specified RGBA components(values
are in range 0.0 – 0.1)
Color(int rgb): Creates an opaque RGB color with the specified combined RGB value
consisting of the red component in bits 16-23, the green component in bits 8 – 15, and the blue
component in bits 0-7.
Color(int rgba, boolean b): Creates an sRGB color with the specified combined RGBA value
consisting of the alpha component in bits 24-31, the red component in bits 16 – 23, the green
component in bits 8
– 15, and the blue component in bits 0 – 7.

145
[Link]-V JAVA_NOTES

Color(int r, int g, int b) : Creates a opaque color with specified RGB components(values are in
range 0 – 255)
Color(int r, int g, int b, int a) : Creates a color with specified RGBA components(values are in
range 0 – 255)

// Java program to set the background color of panel


// using the color specified in the constants
// of the class.
import [Link].*;
import [Link].*;

class color extends JFrame {

// constructor
color()
{
super("color");

// create a new Color


Color c = [Link];

// create a panel
JPanel p = new JPanel();

// set the background of the frame


// to the specified Color
[Link](c);

setSize(200, 200);
add(p);

146
[Link]-V JAVA_NOTES

show();
}

// Main Method
public static void main(String args[])
{
color c = new color();
}
}

Font Class:
Last Updated : 18 Sep, 2018
Font class is a part of JavaFX. The Font class represents fonts, which are used to render text on
the screen. The size of a Font is described as being specified in points which are a real world
measurement of approximately 1/72 inch. Font class inherits Object class.
Constructors of the class:
Font(double s) : Creates a font object with specified size.
Font(String n, double s) : Creates a font object with specified name and size.

147
[Link]-V JAVA_NOTES

Java Program to create a font object and apply it to a text and allow the user to select the font
from the combo box: In this program we will create a Font named font and specify its family,
its font weight and size. Apply this font to the text and add this text to the TextFlow named
textflow. Create a VBox named vbox and add the textflow to the vbox and add the vbox to the
scene and add the scene to stage. Create two combo box and add the font names to one and
the font weight to the other and create an EventHandler to handle the events of the combo
boxes and set the font to the type specified by the user.

// Java Program to create a font object


// and apply it to a text and allow the
// user to select font from the combo box
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class Font_2 extends Application {

// launch the application


public void start(Stage stage)

148
[Link]-V JAVA_NOTES

try {

// set title for the stage


[Link]("Font");

// create TextFlow
TextFlow text_flow = new TextFlow();

// create text
Text text_1 = new Text("GeeksforGeeks\n");

// set the text color


text_1.setFill([Link]);

// create a font
Font font = [Link]([Link]().get(0),
FontWeight.EXTRA_BOLD, 20);

// font weight names


String weight[] = { "BLACK", "BOLD",
"EXTRA_BOLD",
"EXTRA_LIGHT",
"LIGHT",
"MEDIUM",
"NORMAL",
"SEMI_BOLD",
"THIN" };

149
[Link]-V JAVA_NOTES

// Create a combo box


ComboBox combo_box =
new ComboBox([Link](weight));

// Create a combo box


ComboBox combo_box1 =
new ComboBox([Link]([Link]()));

// Create action event


EventHandler<ActionEvent> event =
new EventHandler<ActionEvent>() {

public void handle(ActionEvent e)


{

// set font of the text


text_1.setFont([Link]((String)combo_box1.getValue(),
[Link]((String)combo_box.getValue()), 20));
}
};

// Create action event


EventHandler<ActionEvent> event1 =
new EventHandler<ActionEvent>() {

public void handle(ActionEvent e)


{

150
[Link]-V JAVA_NOTES

// set font of the text


text_1.setFont([Link]((String)combo_box1.getValue(),
[Link]((String)combo_box.getValue()), 20));
}
};

// Set on action
combo_box.setOnAction(event);
combo_box1.setOnAction(event1);

// set font of the text


text_1.setFont(font);

// set text
text_flow.getChildren().add(text_1);

// set line spacing


text_flow.setLineSpacing(20.0f);

// create a HBox
HBox hbox = new HBox(combo_box, combo_box1);

// create VBox
VBox vbox = new VBox(hbox, text_flow);

// set spacing
[Link](30.0);

// set alignment of vbox

151
[Link]-V JAVA_NOTES

[Link]([Link]);

// create a scene
Scene scene = new Scene(vbox, 400, 300);

// set the scene


[Link](scene);

[Link]();
}
catch (Exception e) {
[Link]([Link]());
}
}
// Main Method
public static void main(String args[])
{

// launch the application


launch(args);
}
}

Output:

152
[Link]-V JAVA_NOTES

Draw a line using drawLine() method


. This uses drawLine() method.
Syntax:
drawLine(int x1, int y1, int x2, int y2)
Parameters: The drawLine method takes four arguments:
x1 – It takes the first point’s x coordinate.
y1 – It takes first point’s y coordinate.
x2 – It takes second point’s x coordinate.
y2 – It takes second point’s y coordinate
Result: This method will draw a line starting from (x1, y1) co-ordinates to (x2, y2) co-
ordinates.
Below programs illustrate the above problem:
Example:

// Java program to draw a line in Applet

import [Link].*;
import [Link].*;
import [Link].Line2D;

class MyCanvas extends JComponent {

public void paint(Graphics g)


{

// draw and display the line


[Link](30, 20, 80, 90);
}
}

153
[Link]-V JAVA_NOTES

public class GFG1 {


public static void main(String[] a)
{

// creating object of JFrame(Window popup)


JFrame window = new JFrame();

// setting closing operation


[Link](JFrame.EXIT_ON_CLOSE);

// setting size of the pop window


[Link](30, 30, 200, 200);

// setting canvas for draw


[Link]().add(new MyCanvas());

// set visibility
[Link](true);
}
}

Output :

154
[Link]-V JAVA_NOTES

Note: The above function are a part of [Link] package and belongs to [Link]
class. Also, these codes might not run in an online compiler please use an offline compiler.
The x1, x2, y1 and y2 coordinates can be changed by the programmer according to their need.

JSlider
Last Updated : 15 Apr, 2021
JSlider is a part of Java Swing package . JSlider is an implementation of slider. The Component
allows the user to select a value by sliding the knob within the bounded value . The slider can
show Major Tick marks and also the minor tick marks between two major tick marks, The knob
can be positioned at only those points.
Constructor of the class are :
Commonly used Constructors of JSlider class

Constructor Description

JSlider() creates a slider with the initial value of 50 and range of 0 to 100.

JSlider(int orientation) creates a slider with the specified orientation set by either
[Link] or [Link] with the range 0 to 100
and initial value 50.

JSlider(int min, int max) creates a horizontal slider using the given min and max.

JSlider(int min, int max, int creates a horizontal slider using the given min, max and value.
value)

JSlider(int orientation, int creates a slider using the given orientation, min, max and value.
min, int max, int value)

155
[Link]-V JAVA_NOTES

Commonly used Methods of JSlider class

Method Description

public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider.

public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider.

public void setPaintTicks(boolean b) is used to determine whether tick marks are painted.

public void setPaintLabels(boolean b) is used to determine whether labels are painted.

public void setPaintTracks(boolean b) is used to determine whether track is painted.

Java JSlider Example

import [Link].*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider([Link], 0, 50, 25);
JPanel panel=new JPanel();
[Link](slider);
add(panel);
}

public static void main(String s[]) {


SliderExample1 frame=new SliderExample1();
[Link]();

156
[Link]-V JAVA_NOTES

[Link](true);
}
}
Output:

Java JSlider Example: painting ticks


import [Link].*;
public class SliderExample extends JFrame{
public SliderExample() {
JSlider slider = new JSlider([Link], 0, 50, 25);
[Link](2);
[Link](10);
[Link](true);
[Link](true);
JPanel panel=new JPanel();
[Link](slider);
add(panel);
}
public static void main(String s[]) {
SliderExample frame=new SliderExample();
[Link]();
[Link](true);
}
}
Output:

157
[Link]-V JAVA_NOTES

JMENUBAR, JMENU AND JMENUITEMS ARE A PART OF JAVA SWING


PACKAGE.
JMenuBar is an implementation of menu bar . the JMenuBar contains one or more JMenu
objects, when the JMenu objects are selected they display a popup showing one or more
JMenuItems .
JMenu basically represents a menu . It contains several JMenuItem Object . It may also
contain JMenu Objects (or submenu).
Constructors :
JMenuBar() : Creates a new MenuBar.
JMenu() : Creates a new Menu with no text.
JMenu(String name) : Creates a new Menu with a specified name.
JMenu(String name, boolean b) : Creates a new Menu with a specified name and boolean
value specifies it as a tear-off menu or not. A tear-off menu can be opened and dragged away
from its parent menu bar or menu.
Commonly used methods:
add(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu bar.
add(Component c) : Add component to the end of JMenu
add(Component c, int index) : Add component to the specified index of JMenu
add(JMenuItem menuItem) : Adds menu item to the end of the menu.
add(String s) : Creates a menu item with specified string and appends it to the end of menu.
getItem(int index) : Returns the specified menuitem at the given index
import [Link].*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");

158
[Link]-V JAVA_NOTES

submenu=new JMenu("Sub Menu");


i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
[Link](i1); [Link](i2); [Link](i3);
[Link](i4); [Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
35.2Mxt
Stay

159
[Link]-V JAVA_NOTES

DRAW A ELLIPSE AND A RECTANGLE IN JAVA APPLET


Java applets are application that can be executed in web browsers or applet viewers . We can
draw shapes on the Java applet.
In this article we will draw a ellipse on Java applet by two ways . By using the drawOval(int x,
int y, int width, int height) or by using mathematical formula (X= A * sin a, Y= B *cos a, where
A and B are major and minor axes and a is the angle ) .
Similarly, we will draw a rectangle on Java applet by two ways . By using the drawRect(int x, int
y, int width, int height) or by drawing four lines joining the edges .
To draw a ellipse in Java Applet
Examples:
Let us draw a oval with width 150 and height 100
Input : x and y coordinates 100, 100 respectively
Width and height 150 and 100 respectively
Output :

To draw a rectangle in Java Applet


Examples:
We will draw a rectangle of height 200 and width 200 and
At a position 100,100 on the applet.
Input : x and y coordinates 100, 100 respectively
Width and height 200 and 200 respectively.

160
[Link]-V JAVA_NOTES

Output :

1. Java Program to draw a ellipse using drawOval(int x, int y, int width, int height)

// java program to draw a ellipse


// using drawOval function.
import [Link].*;
import [Link].*;
public class ellipse extends JApplet {
public void init()
{
// set size
setSize(400, 400);

repaint();
}
// paint the applet
public void paint(Graphics g)
{
// set Color for rectangle
[Link]([Link]);

161
[Link]-V JAVA_NOTES

// draw a ellipse
[Link](100, 100, 150, 100);
}
}

Output :

162
[Link]-V JAVA_NOTES

UNIT-IV

Packages in Java – Types, Advantages & Techniques to Access Packages


There are folders or directories in our computers for the classification and accessibility of various
files, and in Java, we have packages for the same. In Java, Packages are similar to folders, which
are mainly used to organize classes and interfaces.
Packages help us to write better and manageable code by preventing naming conflicts. Java
provides some built-in packages which we can use but we can also create our own (user-defined)
packages.
In this article, we are going to discuss everything about packages in Java along with their
syntaxes and examples. Moving forth in this article we are going to learn –
Packages in Java
Advantages of using Packages in Java
Types of Packages in Java
Creating a Package in Java
Example of Java Packages
Package naming Conventions
Compiling a Java Package
Executing Java Package Program
Accessing a Java Package
Sub packages in Java
Important Points in Java Package
Dividing Classes into Packages

Packages in Java
A package is a collection of similar types of Java entities such as classes, interfaces, subclasses,
exceptions, errors, and enums. A package can also contain sub-packages.
Advantages of using Packages in Java

163
[Link]-V JAVA_NOTES

There are several advantages of using Java Packages, some of them, are as follows –
Make easy searching or locating of classes and interfaces.
Avoid naming conflicts. For example, there can be two classes with the name Student in two
packages, [Link] and [Link]
Implement data encapsulation (or data-hiding).
Provide controlled access: The access specifiers protected and default have access control on
package level. A member declared as protected is accessible by classes within the same package
and its subclasses. A member without any access specifier that is default specifier is accessible
only by classes in the same package.
Reuse the classes contained in the packages of other programs.
Uniquely compare the classes in other packages.
Get to know about Access Specifiers in Java you didn’t know about.
just put similar classes into the same packages. After that, we simply import the classes from
existing packages through the import statement and use them in our program. A package
provides access to some classes and others are kept for internal purposes.

Note:
Package names are dot-separated, e.g., [Link]
Packages avoid namespace collision: A package can not contain two classes with the same
names, but two different packages can have a class with the same name.
The exact name of the class is identified by the structure of its package.

164
[Link]-V JAVA_NOTES

Types of Packages in Java


They can be divided into two categories:
Java API packages or built-in packages and
User-defined packages.

Java API packages or built-in packages


Java provides a large number of classes grouped into different packages based on a particular
functionality.
Examples:
[Link]: It contains classes for primitive types, strings, math functions, threads, and
exceptions.
[Link]: It contains classes such as vectors, hash tables, dates, Calendars, etc.
[Link]: It has stream classes for Input/Output.
[Link]: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.
[Link]: Classes for networking
java. Applet: Classes for creating and implementing applets

165
[Link]-V JAVA_NOTES

User-defined packages
As the name suggests, these packages are defined by the user. We create a directory whose name
should be the same as the name of the package. Then we create a class inside the directory.
Creating a Package in Java
To create a package, we choose a package name and to include the classes, interfaces,
enumerations, etc, inside the package, we write the package with its name at the top of every
source file.
There can be only one package statement in each type of file. If we do not write class, interfaces,
inside any package, then they will be placed in the current default package.
Example of Java Package
We can create a Java class inside a package using a package keyword.
package [Link]; //package
class Example
{
public static void main(String args[])
{
[Link]("Welcome to Techvidvan’s Java Tutorial");
}
}
output: Welcome to Techvidvan’s Java Tutorial

166
[Link]-V JAVA_NOTES

How do Packages in Java Work?


The names of packages and the directory structure are closely related to each other.
For example, if a package name is [Link], then there are three
directories- university, engineering, and csedept such that csedept is present in engineering and
engineering is present in university.
The package university can be considered as a top-level package while engineering is a
subpackage of university and cse dept is a sub-package of engineering.
Package Naming Conventions
Packages names follow the reverse order of domain names, that is, [Link]. For
example, in a university, the recommended convention is [Link] or
[Link] or [Link] etc.
In the following package:
[Link]
java is a top-level package
util is a sub package
and Vector is a class which is present in the subpackage util.
Compiling a Java Package
If you are using an IDE (Integrated Development Environment), then for compiling the package,
you need to follow the syntax given below:
javac -d directory javaFileName
For example,
javac -d . [Link]

-d specifies the destination where to locate the generated class file. You can use any directory
name like /home (in case of Linux), C:/folderName (in case of windows), etc. If you want the
package to be present in the same directory, you can use the dot ( . )
Executing Java Package Program
You need to use a fully qualified name e.g. [Link] etc to run the class.

167
[Link]-V JAVA_NOTES

To Compile:
javac -d . [Link]
Here -d represents the destination. The . represents the current folder.
To run:
java [Link]
Accessing Packages or Classes from Another Package
If we want to access all the classes and interfaces of an existing package then we use
the import statement. We can do it in three different ways:
import package.*;
import [Link];
fully qualified name.
1. By using * after the import statement, we can access all the classes of the package but not the
sub-packages.
Syntax:
For importing all the classes:
import packageName.*;
By using a particular class name after the import statement, we can access that particular class
package but not the sub-packages.
Syntax:
For importing a particular class:
import [Link];
Code to illustrate the above concept:
package [Link]; //package
class MyClass
{
public void printName(String name)
{
[Link](name);
}
}
package com..packagedemo1;

168
[Link]-V JAVA_NOTES

import [Link]; //importing a particular class MyClass


public class MyClass1
{
public static void main(String args[])
{
// Initializing the String variable with a value
String name = "Java Tutorial";
// Creating an instance of class MyClass from another package.
MyClass obj = new MyClass();
[Link](name);
}
}
Output:
Java Tutorial
3. Using a Fully qualified name means we can access the declared class of different packages
without using the import statement. But you need to use a fully qualified name every time when
you are accessing the class or interface which is present in a different package.
This type of technique is generally used when two packages have the same class name example
class Date is present in both the packages [Link] and [Link].
Code to illustrate the above concept:
package com..packagedemo; //package
class MyClass
{
public void printName(String name)
{
[Link](name);
}
}
package com..packagedemo1;
public class MyClass1
{

169
[Link]-V JAVA_NOTES

public static void main(String args[])


{
// Initializing the String variable with a value
String name = " Java Tutorial";
// Using fully qualified name to access the class of different package
[Link] obj = new [Link]();
[Link](name);
}
}
Output:
Note: If you import a package, you can not import the sub-packages. If you import a package, all
the classes and interface of that package will be imported but the classes and interfaces of the
sub-packages will not be accessible. Hence, you will have to import the subpackage as well.
Note: The sequence of the program must be package name then import [Link] both the
class begins.

170
[Link]-V JAVA_NOTES

Subpackage in Java
The package present inside a package is called the subpackage. It is created to further
categorize packages.
For example, If we create a package inside the techvidvan package then that will be called
subpackage.
Let’s say we have created another package inside techvidvan and the name of subpackage is
tutorials. So if we create a class in this subpackage it should have a package declaration in the
following manner:
package .[Link];
Here techvidvan is a package while tutorials is a subpackage of techvidvan.
The standard of defining the package is [Link]
example [Link] or [Link].
Code to explain Subpackage
package [Link];
class Demo
{
public static void main(String args[])
{
[Link]("Inside a sub-package");
}
}
To compile: javac -d. [Link]
To run: java [Link]
Output:
Inside a sub-package
Using Static Import
‘Static Import’ is a feature introduced in Java programming language for Java versions 5 and
above that allows fields and members of a class which are declared as public and static to be
directly used inside the Java code without specifying the name of the class in which these public
static fields or methods are defined.

171
[Link]-V JAVA_NOTES

Code to illustrate the use of static import statement


// Note static keyword after import.
package com..packagedemo;
import static [Link].*;
class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use '[Link]'
// as we imported the package using static.
[Link]("TechVidvan");
}
}
Important points on Packages in Java
Every class belongs to a package. If you do not mention any package, the classes in the file move
into a special unnamed package which is the same for all the files which do not belong to a
specified package.
Multiple classes and interfaces in a file can be part of the same package.
If the package name is specified, then the directory name must match the package name.
We can access the classes declared as public in another package using:
import [Link]-name
Dividing Your Classes Into Packages
You might be thinking that how to categorize your classes into packages. There is no standard
method to do this but thee are two methods which you can follow:
1. Divide by Layer
This is the first method in which we divide the classes according to the layers of the application.
For example, if your application contains a network layer, then you would create a package
named network.
All classes which are related to the network of the application are located in the network
package.

172
[Link]-V JAVA_NOTES

2. Divide by Application Functionality


You can also divide your classes on the basis of what part of the application functionality they
belong to. Thus, if your application has a functionality area that calculates interest you would
create a Java package named interest.
All classes related directly or indirectly to the interest calculations would go into that package. If
the number of classes in the root package becomes very large, they can also be moved to the sub-
packages.

What is Interface in Java?


An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. A Java interface contains static constants and abstract methods. A class can
implement multiple interfaces. In Java, interfaces are declared using the interface keyword. All
methods in the interface are implicitly public and abstract.
Now, we will learn how to use interface in Java.
Syntax for Declaring Interface
To use an interface in your class, append the keyword “implements” after your class name
followed by the interface name.
interface {
//methods
}

Example for Implementing Interface


Now, let’s understand interface in Java with example:
class Dog implements Pet
Why is an Interface required?
To understand the use of interface in Java better, let see an Java interface example.
example of Dog.

173
[Link]-V JAVA_NOTES

Suppose you have a requirement where class “dog” inheriting class “animal” and “Pet” (see
image below). But you cannot extend two classes in Java. So what would you do? The solution is
Interface.
The rulebook for interface says,
A Java implement interface is 100% abstract class and has only abstract methods.
Class can implement any number of interfaces.
Class Dog can extend to class “Animal” and implement interface as “Pet”.

interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
[Link]("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
[Link]();
}
}

174
[Link]-V JAVA_NOTES

Difference between Class and Interface


Class Interface
In class, you can instantiate variable and create an In an interface, you can’t instantiate variable and
object. create an object.

Class can contain concrete(with implementation) The interface cannot contain concrete(with
methods implementation) methods

The access specifiers used with classes are private,


In Interface only one specifier is used- Public.
protected and public.

When to use Interface and Abstract Class?


Use an abstract class when a template needs to be defined for a group of subclasses
Use an interface when a role needs to be defined for other classes, regardless of the inheritance
tree of these classes
facts about Interface
A Java class can implement multiple Java Interfaces. It is necessary that the class must
implement all the methods declared in the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning which classes it belongs.
Class needs to provide functionality for the methods declared in the interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only one class but
implement any number of interfaces
An interface cannot implement another Interface. It has to extend another interface if needed.
An interface which is declared inside another interface is referred as nested interface
At the time of declaration, interface variable must be initialized. Otherwise, the compiler will
throw an error.

175
[Link]-V JAVA_NOTES

The class cannot implement two interfaces in java that have methods with same name but
different return type.
Exception handling
Exception handling is one of the most important feature of java programming that allows us to
handle the runtime errors caused by exceptions. In this guide, we will learn what is an exception,
types of it, exception classes and how to handle exceptions in java with examples.
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated
error message. The good thing about exceptions is that they can be handled in Java. By handling
the exceptions we can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
Why an exception occurs?
There can be several reasons that can cause a program to throw exception. For example: Opening
a non-existing file in your program, Network connection problem, bad input data provided by
user etc.
Exception Handling
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the
system generated exception below:
An exception generated by the system is given below
Exception in thread "main" [Link]: / by zero at
[Link]([Link])
ExceptionDemo : The class name
main : The method name
[Link] : The filename
java:5 : Line number

176
[Link]-V JAVA_NOTES

Advantage of exception handling


Exception handling ensures that the flow of the program doesn’t break when an exception
occurs. For example, if a program has bunch of statements and an exception occurs mid way
after executing certain statements then the statements after the exception will not execute and the
program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Difference between error and exception
Errors indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such conditions and
take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a
number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its
bounds, for example array size is 5 (which means it has five elements) and you are trying to
access the 10th element.

177
[Link]-V JAVA_NOTES

Types of exceptions
There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked
at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Compiler will never force you to catch such exception or force you to declare it in the method
using throws keyword.

try-catch block
try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

178
[Link]-V JAVA_NOTES

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}

catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
38.78ence between JDK, JRE, and JVM
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

Internal Working of Java try-catch block

179
[Link]-V JAVA_NOTES

The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Problem without exception handling
if we don't use a try-catch block.

Example 1
[Link]

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

[Link]("rest of the code");

} ption in thread "main" java.

As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).

180
[Link]-V JAVA_NOTES

There might be 100 lines of code after the exception. If the exception is not handled, all the code
below the exception won't be executed.
Solution by exception handling
by using try-catch block.
Example 2
[Link]
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}

e
As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.

181
[Link]-V JAVA_NOTES

Example 3
a try block that will not throw an exception.
[Link]

public class TryCatchExample3 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
[Link]("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
[Link](e);
}

}
y zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not
execute.

182
[Link]-V JAVA_NOTES

Example 5
Let's see an example to print a custom message on exception.
TryCatchExample5
public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}

Can't divided by zero


Example 6
an example to resolve the exception in a catch block.
[Link]

public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;

183
[Link]-V JAVA_NOTES

try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
[Link](i/(j+2));
}
}
}

Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
[Link]

public class TryCatchExample7 {

public static void main(String[] args) {

try
{
int data1=50/0; //may throw exception

}
// handling the exception
catch(Exception e)
{

184
[Link]-V JAVA_NOTES

// generating the exception in catch block


int data2=50/0; //may throw exception

}
[Link]("rest of the code");
}
}

Exception in thread
Here, we can see that the catch block didn't contain the exception code. So, enclose exception
code within a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different type
of exception class (ArrayIndexOutOfBoundsException).
[Link]

public class TryCatchExample8 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception

}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
} }

185
[Link]-V JAVA_NOTES

Excion in thread "main" [Link] by zero


Example 9
Let's see an example to handle another unchecked exception.
[Link]

public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}

rest of the code


Example 10
an example to handle checked exception.
[Link]

import [Link];
import [Link];

186
[Link]-V JAVA_NOTES

public class TryCatchExample10 {

public static void main(String[] args) {

PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {

[Link](e);
}
[Link]("File saved successfully");
}
}
access

Difference between throw and throws


Throw vs Throws in java
1. Throws clause is used to declare an exception, which means it works similar to the try-catch
block. On the other hand throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is
followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");
and
throws ArithmeticException;

187
[Link]-V JAVA_NOTES

3. Throw keyword is used in the method body to throw an exception, while throws is used in
method signature to declare the exceptions that can occur in the statements present in the
method.
For example:
Throw:
...
void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
[Link]("Error: "+[Link]());
}
}
...

Throws:
...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}
...
4. You can throw one exception at a time but you can handle multiple exceptions by declaring
them using throws keyword.
For example:
Throw:
void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by zero!!");

188
[Link]-V JAVA_NOTES

}
..
Throws:
//Declaring multiple exceptions using throws
void myMethod() throws ArithmeticException, NullPointerException{
//Statements where exception might occur
}
These were the main differences between throw and throws in Java. Lets see complete
examples of throw and throws keywords.
Throw Example
To understand this example we should know what is throw keyword and how it works.
public class Example1{
void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
[Link]("Eligible for voting");
}
public static void main(String args[]){
Example1 obj = new Example1();
[Link](13);
[Link]("End Of Program");
}
}
Output:
Exception in thread "main" [Link]:
Not Eligible for voting
at [Link]([Link])
at [Link]([Link])
Throws Example

189
[Link]-V JAVA_NOTES

To understand this example we should know what is throws clause and how it is used in method
declaration for exception handling.
public class Example1{
int division(int a, int b) throws ArithmeticException{
int t = a/b;
return t;
}
public static void main(String args[]){
Example1 obj = new Example1();
try{
[Link]([Link](15,0));
}
catch(ArithmeticException e){
[Link]("You shouldn't divide number by zero");
}
}
}
Output: You shouldn't divide number by zero

Thread
A Thread is a very light-weighted process, or we can say the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept in Java.
All the tasks are executed without affecting the main program. In a program or process, all the
threads have their own separate path for execution, so each thread of a process is independent.

190
[Link]-V JAVA_NOTES

Another benefit of using thread is that if a thread gets an exception or an error at the time of its
execution, it doesn't affect the execution of the other threads. All the threads share a common
memory and have their own stack, local variables and program counter. When multiple threads
are executed in parallel at the same time, this process is known as Multithreading

In a simple way, a Thread is a:


Feature through which we can perform multiple activities within a single process.
Lightweight process.
Series of executed statements.
Nested sequence of method calls.
Thread Model
Just like a process, a thread exists in several states. These states are as follows:

191
[Link]-V JAVA_NOTES

1) New (Ready to run)


A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution immediately.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by
extending the Thread class. These are the only two ways through which we can create a thread.
Thread Class
A Thread class has several methods and constructors which allow us to perform various
operations on a thread. The Thread class extends the Object class. The Object class implements
the Runnable interface. The thread class has the following constructors that are used to perform
various operations.

192
[Link]-V JAVA_NOTES

Thread()
Thread(Runnable, String name)
Thread(Runnable target)
Thread(ThreadGroup group, Runnable target, String name)
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, String name)
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Runnable Interface(run() method)
The Runnable interface is required to be implemented by that class whose instances are intended
to be executed by a thread. The runnable interface gives us the run() method to perform an
action for the thread.
start() method
The method is used for starting a thread that we have newly created. It starts a new thread with a
new callstack. After executing the start() method, the thread changes the state from New to
Runnable. It executes the run() method when the thread gets the correct time to execute it.
Let's take an example to understand how we can create a Java
thread by extending the Thread class:

ThreadExample1.

// Implementing runnable interface by extending Thread class


public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
[Link]("Thread started running..");
[Link]("Sum of two numbers is: "+ result);
}

193
[Link]-V JAVA_NOTES

public static void main( String args[] )


{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
[Link]();
}
}
Output:

Creating thread by implementing the runnable interface


In Java, we can also create a thread by implementing the runnable interface. The runnable
interface provides us both the run() method and the start() method.
Let's takes an example to understand how we can create, start and run the thread using the
runnable interface.
[Link]
class NewThread implements Runnable {
String name;
Thread thread;
NewThread (String name){
[Link] = name;
thread = new Thread(this, name);
[Link]( "A New thread: " + thread+ "is created\n" );
[Link]();
}

194
[Link]-V JAVA_NOTES

public void run() {


try {
for(int j = 5; j > 0; j--) {
[Link](name + ": " + j);
[Link](1000);
}
}catch (InterruptedException e) {
[Link](name + " thread Interrupted");
}
[Link](name + " thread exiting.");
}
}
class ThreadExample2 {
public static void main(String args[]) {
new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
[Link](8000);
} catch (InterruptedException excetion) {
[Link]("Inturruption occurs in Main Thread");
}
[Link]("We are exiting from Main Thread");
}
}

195
[Link]-V JAVA_NOTES

Multithreading
is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching between
the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


Each process has an address in memory. In other words, each process allocates a separate
memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers
, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.

196
[Link]-V JAVA_NOTES

Note: At least one process is required for each thread.


What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS
, and one process can have multiple threads.
Note: At a time one thread is executed only.
Java Thread class
Java provides Thread class to achieve thread programming. Thread class provides constructors
and methods to create and perform operations on a thread. Thread class extends Object class
and implements Runnable interface.
to perform input and output (I/O) in Java. All these streams represent an input source and an
output destination. The stream in the [Link] package supports many data such as primitives,
object, localized characters, etc.

197
[Link]-V JAVA_NOTES

Stream:
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}

198
[Link]-V JAVA_NOTES

}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Now let's have a file [Link] with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link]
file and do the following −
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import [Link].*;
public class CopyFile {

public static void main(String args[]) throws IOException {

199
[Link]-V JAVA_NOTES

FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
Now let's have a file [Link] with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating [Link]
file with the same content as we have in [Link]. So let's put the above code in [Link]
file and do the following −
$javac [Link]
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are aware

200
[Link]-V JAVA_NOTES

of C or C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard is used
as standard input stream and represented as [Link].
Standard Output − This is used to output the data produced by the user's program and usually a
computer screen is used for standard output stream and represented as [Link].
Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as [Link].
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "q" −
Example

import [Link].*;
public class ReadConsole {

public static void main(String args[]) throws IOException {


InputStreamReader cin = null;

try {
cin = new InputStreamReader([Link]);
[Link]("Enter characters, 'q' to quit.");
char c;
do {
c = (char) [Link]();
[Link](c);
} while(c != 'q');
}finally {
if (cin != null) {
[Link]();
}
}

201
[Link]-V JAVA_NOTES

}
}
Let's keep the above code in [Link] file and try to compile and execute it as shown in
the following program. This program continues to read and output the same character until we
press 'q' −
$javac [Link]
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

202
[Link]-V JAVA_NOTES

The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file

InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.

203
[Link]-V JAVA_NOTES

[Link]. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns an int. Returns
the next byte of data and -1 will be returned if it's the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads [Link] bytes from the input stream into an array. Returns the total
number of bytes read. If it is the end of the file, -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following
links −
ByteArrayInputStream
DataInputStream

204
[Link]-V JAVA_NOTES

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

[Link]. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes [Link] bytes from the mentioned byte array to the OutputStream.

205
[Link]-V JAVA_NOTES

There are other important output streams available, for more detail you can refer to the following
links −
ByteArrayOutputStream
DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream −
import [Link].*;
public class fileStreamTest {
public static void main(String args[]) {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("[Link]");
for(int x = 0; x < [Link] ; x++) {
[Link]( bWrite[x] ); // writes the bytes
}
[Link]();

InputStream is = new FileInputStream("[Link]");


int size = [Link]();

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


[Link]((char)[Link]() + " ");
}
[Link]();
} catch (IOException e) {
[Link]("Exception");
}
}
}
The above code would create file [Link] and would write given numbers in binary format. Same
would be the output on the stdout screen.

206
[Link]-V JAVA_NOTES

File Navigation and I/O


There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
File Class
FileReader Class
FileWriter Class
Directories in Java
A directory is a File which can contain a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail, check a list of
all the methods which you can call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create directories −
The mkdir( ) method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory −
Example
import [Link];
public class CreateDir {

public static void main(String args[]) {


String dirname = "/tmp/user/java/bin";
File d = new File(dirname);

// Create directory now.


[Link]();
}
}
Compile and execute the above code to create "/tmp/user/java/bin".

207
[Link]-V JAVA_NOTES

Note − Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows −
Example
import [Link];
public class ReadDir {

public static void main(String[] args) {


File file = null;
String[] paths;

try {
// create new file object
file = new File("/tmp");

// array of files and directory


paths = [Link]();

// for each name in the path array


for(String path:paths) {
// prints filename and directory name
[Link](path);
}
} catch (Exception e) {
// if any error occurs
[Link]();
}
}

208
[Link]-V JAVA_NOTES

}
This will produce the following result based on the directories and files available in
your /tmp directory −
Output
[Link]
[Link]
[Link]
[Link]

What is sequential access

Sequential access is a term describing a group of elements (such as data in a memory array or a
disk file or on magnetic tape data storage) being accessed in a predetermined, ordered sequence.
... Sequential access is sometimes the only way of accessing the data.
RandomAccessFile

This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number of
byte has been read than EOFException is thrown. It is a type of IOException.

209
[Link]-V JAVA_NOTES

210

You might also like