Java Notes
Java Notes
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.
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.
1
[Link]-V JAVA_NOTES
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.
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 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.
byte, short, int and long data types are used for storing whole numbers.
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
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) {
class JavaExample {
public static void main(String[] args) {
class JavaExample {
public static void main(String[] args) {
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
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
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
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;
9
[Link]-V JAVA_NOTES
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.
[Link]([Link]);
[Link]([Link]);
11
[Link]-V JAVA_NOTES
[Link]([Link]);
[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.
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();
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.
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.
o Multidimensional Array
14
[Link]-V JAVA_NOTES
Instantiation of an Array
1. arrayRefVar=new datatype[size];
In such case, data is stored in row and column based index (also known as matrix form).
15
[Link]-V JAVA_NOTES
Operators
An operator is a character that represents an action, for example + is an arithmetic operator that
represents 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
16
[Link]-V JAVA_NOTES
}
}
Output:
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
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;
18
[Link]-V JAVA_NOTES
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.
== 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.
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.
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.
}
else{
[Link]("num1 is not less than num2");
}
6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
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
result = ~num1;
[Link]("~num1: "+result);
22
[Link]-V JAVA_NOTES
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.
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
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.
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]
26
[Link]-V JAVA_NOTES
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]
27
[Link]-V JAVA_NOTES
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.
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. }
[Link]
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.
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
[Link]
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.
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 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.
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]
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
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.
33
[Link]-V JAVA_NOTES
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
Output:
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.
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
34
[Link]-V JAVA_NOTES
Output:
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.
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
Output:
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]
37
[Link]-V JAVA_NOTES
Output:
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.
Consider the following example in which we have used the break statement with the for loop.
38
[Link]-V JAVA_NOTES
[Link]
Output:
0
1
2
3
4
5
6
[Link]
39
[Link]-V JAVA_NOTES
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
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.
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.
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
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.
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
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.
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.
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:
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:
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
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:
import [Link].*;
public class SimpleIO {
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
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:
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:
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
HTML Tutorial
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.
51
[Link]-V JAVA_NOTES
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
19 mapLibraryName(String libname) This method maps a library name into the platform-
specific string which represents a native library.
53
[Link]-V JAVA_NOTES
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.
56
[Link]-V JAVA_NOTES
Object Definitions:
What is a class
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.
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
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;
61
[Link]-V JAVA_NOTES
void info(){
[Link]("Id: "+empId+" Name: "+empName);
}
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
63
[Link]-V JAVA_NOTES
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:
65
[Link]-V JAVA_NOTES
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
}
66
[Link]-V JAVA_NOTES
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;
}
}
// Outputs 15 (5 + 10)
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();
// Outputs 5
69
[Link]-V JAVA_NOTES
class InnerClass {
public int myInnerMethod() {
return x;
}
}
}
// 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
73
[Link]-V JAVA_NOTES
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
76
[Link]-V JAVA_NOTES
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.
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
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
80
[Link]-V JAVA_NOTES
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
import [Link];
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
82
[Link]-V JAVA_NOTES
Output: 25
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
83
[Link]-V JAVA_NOTES
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
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.
86
[Link]-V JAVA_NOTES
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
ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener
88
[Link]-V JAVA_NOTES
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
89
[Link]-V JAVA_NOTES
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
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");
}
}
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
Methods Description
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
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:
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
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 :
// frame
static JFrame f;
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 panel
JPanel p = new JPanel();
[Link]();
}
}
99
[Link]-V JAVA_NOTES
// frame
static JFrame f;
// 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 panel
JPanel p = new JPanel();
[Link]();
}
}
101
[Link]-V JAVA_NOTES
import [Link].*;
import [Link].*;
import [Link].*;
class text extends JFrame {
// frame
static JFrame f;
// 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 panel
JPanel p = new JPanel();
102
[Link]-V JAVA_NOTES
[Link]();
}
}
103
[Link]-V JAVA_NOTES
// frame
static JFrame f;
// 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 panel
104
[Link]-V JAVA_NOTES
[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 :
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
106
[Link]-V JAVA_NOTES
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
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.
Constructor Description
Methods Description
110
[Link]-V JAVA_NOTES
111
[Link]-V JAVA_NOTES
112
[Link]-V JAVA_NOTES
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
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.
Methods Description
114
[Link]-V JAVA_NOTES
115
[Link]-V JAVA_NOTES
116
[Link]-V JAVA_NOTES
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
118
[Link]-V JAVA_NOTES
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 JTextAreaExample() {
119
[Link]-V JAVA_NOTES
[Link](panel);
[Link]("JTextAreaExample Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link]();
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.
Constructor Description
121
[Link]-V JAVA_NOTES
Methods Description
void removeAllItems() It is used to remove all the items from the list.
122
[Link]-V JAVA_NOTES
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
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.
Constructor Description
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
Methods Description
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:
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
129
[Link]-V JAVA_NOTES
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.
130
[Link]-V JAVA_NOTES
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
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.
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
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:
133
[Link]-V JAVA_NOTES
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
134
[Link]-V JAVA_NOTES
[Link]
// main method
135
[Link]-V JAVA_NOTES
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.
Interface declaration
Following is the declaration for [Link] interface:
136
[Link]-V JAVA_NOTES
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
138
[Link]-V JAVA_NOTES
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].*;
// 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
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Output:titive questions on Structures
142
[Link]-V JAVA_NOTES
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
import [Link].*;
import [Link];
}
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.
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)
// constructor
color()
{
super("color");
// create a panel
JPanel p = new JPanel();
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.
148
[Link]-V JAVA_NOTES
try {
// create TextFlow
TextFlow text_flow = new TextFlow();
// create text
Text text_1 = new Text("GeeksforGeeks\n");
// create a font
Font font = [Link]([Link]().get(0),
FontWeight.EXTRA_BOLD, 20);
149
[Link]-V JAVA_NOTES
150
[Link]-V JAVA_NOTES
// Set on action
combo_box.setOnAction(event);
combo_box1.setOnAction(event1);
// set text
text_flow.getChildren().add(text_1);
// 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);
151
[Link]-V JAVA_NOTES
[Link]([Link]);
// create a scene
Scene scene = new Scene(vbox, 400, 300);
[Link]();
}
catch (Exception e) {
[Link]([Link]());
}
}
// Main Method
public static void main(String args[])
{
Output:
152
[Link]-V JAVA_NOTES
import [Link].*;
import [Link].*;
import [Link].Line2D;
153
[Link]-V JAVA_NOTES
// 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
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.
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);
}
156
[Link]-V JAVA_NOTES
[Link](true);
}
}
Output:
157
[Link]-V JAVA_NOTES
158
[Link]-V JAVA_NOTES
159
[Link]-V JAVA_NOTES
160
[Link]-V JAVA_NOTES
Output :
1. Java Program to draw a ellipse using drawOval(int x, int y, int width, int height)
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
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
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
-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
169
[Link]-V JAVA_NOTES
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
172
[Link]-V JAVA_NOTES
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
Class can contain concrete(with implementation) The interface cannot contain concrete(with
methods implementation) methods
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
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.
178
[Link]-V JAVA_NOTES
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.
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]
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 {
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]
}
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 {
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]
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
184
[Link]-V JAVA_NOTES
}
[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]
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
} }
185
[Link]-V JAVA_NOTES
import [Link];
import [Link];
186
[Link]-V JAVA_NOTES
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
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
191
[Link]-V JAVA_NOTES
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.
193
[Link]-V JAVA_NOTES
194
[Link]-V JAVA_NOTES
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)
196
[Link]-V JAVA_NOTES
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 {
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 {
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 {
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
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.
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]();
206
[Link]-V JAVA_NOTES
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 {
try {
// create new file object
file = new File("/tmp");
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]
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