Javaprogramming Notes
Javaprogramming Notes
PROGRAMMING
NOTES
v
Compile By Arjun
www.arjun00.com.np
CHAPTER 1
AN INTRODUCTION TO JAVA
In this chapter
1.1 Java as a Programming Platform
1.2 The Java “White Paper” Buzzwords
1.3 Java Applets and the Internet
1.4 A Short History of Java
Simple
Primary characteristics of Java include a simple
language that can be programmed without extensive
programmer training while being attuned to current
software practices. The fundamental concepts of Java
are grasped quickly; programmers can be productive
from thevery beginning.
www.arjun00.com.np
Object-Oriented
Java is designed to be object oriented from the ground
up. Object technology has finally found itsway into the
programming mainstream after a gestation period of
thirty years. The needs of distributed, client-server
based systems coincidewith the encapsulated,
message-passing paradigms of object-based software.
To function within increasingly complex, network-
based environments, programming systems must
adopt object-oriented concepts. Java provides a clean
and efficient object-based development environment
Distributed
Java has an extensive library of routines for coping
with TCP/IP protocols like HTTP andFTP. Java
applications can open and access objects across the Net
via URLs with the sameease as when accessing a local
file system.
www.arjun00.com.np
Robust
Java is designed for creating highly reliable software. It
provides extensive compile-time checking, followed by
a second level of run-time checking. Language
features guide programmerstowards reliable
programming habits.
The Java compiler detects many problems that in
other languages would show up only at runtime. As
for the second point, anyone who has spent hours
chasing memory corruption caused by a pointer bug
will be very happy with this aspect of Java.
Secure
Java is designed to operate in distributed
environments, which means that security is of
paramount importance. With security features
designed into the language and run-time system,Java
lets you construct applications that can’t beinvaded
from outside. In the networked environment,
applications written in Java are secure from intrusion
by unauthorized code attempting to get behind the
scenes and create viruses or invade file systems.
www.arjun00.com.np
Architecture-Neutral
Java is designed to support applications that will be
deployed into heterogeneous networked
environments. In such environments, applications
must be capable of executing on a variety of hardware
architectures. Within this variety of hardware
platforms, applications must execute atop a variety of
operating systems and interoperate with multiple
programming language interfaces. To accommodate
the diversity of operating environments, the Java
compiler generates bytecodes—an architecture
neutral intermediate format designed to transport
code efficiently to multiple hardware and software
platforms.
Portable
Architecture neutrality is just one part of a truly
portable system. Java takes portability a stage
further by being strict in its definition of the basic
language. Java puts a stake in the ground and
specifies the sizes of its basic data types and the
behavior of its arithmetic operators. Your programs
are the same on every platform—there are no data
type incompatibilities across hardware and software
architectures.
www.arjun00.com.np
The architecture-neutral and portable language
environment of Java is known as the Java Virtual
Machine. It’s the specification of an abstract machine
for which Java language compilers can generate code.
Interpreted
The Java interpreter can execute Java bytecodes directly
on any machine to which the interpreter has been
ported. Since linking is a more incremental and
lightweight process, the development process can be
much more rapid andexploratory.
High Performance:
Performance is always a consideration. Java achieves
superior performance by adopting a scheme by which
the interpreter can run at full speed without needing
to check the run-time environment. The automatic
garbage collector runs as a low-priority background
thread, ensuring a high probability that memory is
available when required, leading to better
performance.
www.arjun00.com.np
Applications requiring large amounts ofcompute power
can be designed such that compute- intensive sections
can be rewritten in native machinecode as required
and interfaced with the Java environment. In general,
users perceive that interactive applications respond
quickly even though they’re interpreted
Multithreaded
[The] benefits of multithreading are better interactive
responsiveness and real-time behavior.
It was the first mainstream language to support
concurrent programming.
At the time, multicore processors were exotic, butweb
programming had just started, and processors spent a
lot of time waiting for a response from the server.
Concurrent programming was needed to make sure
the userinterface didn’t freeze. Concurrent
programming is never easy, but Javahas done a very
good job making it manageable.
www.arjun00.com.np
Dynamic
In a number of ways, Java is a more dynamic
language than C or C++. It was designed to adaptto
an evolving environment. Libraries can freely add new
methods and instance variables without any effect on
their clients. In Java, finding out runtime type
information is straightforward.
www.arjun00.com.np
(UNIT-II)
Fundamental Programming Structures
Comments
The Java comments are the statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code.
Documentation Comment
1) Java Single Line Comment
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:
10
www.arjun00.com.np Page 1
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
10
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
There are 8 types of primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
www.arjun00.com.np Page 2
Data Type Default Value Default size
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
www.arjun00.com.np Page 3
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It
is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0F.
www.arjun00.com.np Page 4
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0)
to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
Computer programs manipulate (or process) data. A variable is used to store a piece of data for
processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In
other words, a variable has a name, a type and stores a value.
A variable has a name (aka identifier), e.g., radius, area, age, height and numStudents. The name is
needed to uniquely identify and reference each variable. You can use the name to assign a value to
the variable (e.g., radius = 1.2), and to retrieve the value stored (e.g., radius*radius*3.1419265).
A variable has a data type. The frequently-used Java data types are:
int: meant for integers (whole numbers) such as 123 and -456.
double: meant for floating-point number (real numbers) having an optional decimal point and
fractional part, such as 3.1416, -55.66, 1.2e3, or -4.5E-6, where e or E denotes exponent of base 10.
String: meant for texts such as "Hello" and "Good Morning!". Strings are enclosed within a pair of
double quotes.
char: meant for a single character, such as 'a', '8'. A char is enclosed by a pair of single quotes.
In Java, you need to declare the name and the type of a variable before using a variable. For
examples,
int sum; // Declare an "int" variable named "sum"
double average; // Declare a "double" variable named "average"
String message; // Declare a "String" variable named "message"
char grade; // Declare a "char" variable named "grade"
A variable can store a value of the declared data type. It is important to take note that a variable in
most programming languages is associated with a type, and can only store value of that particular
type. For example, an int variable can store an integer value such as 123, but NOT floating-point
number such as 12.34, nor string such as "Hello".
www.arjun00.com.np Page 5
The concept of type was introduced in the early programming languages to simplify interpretation
of data made up of binary sequences (0's and 1's). The type determines the size and layout of the
data, the range of its values, and the set of operations that can be applied.
The following diagram illustrates three types of variables: int, double and String. An int variable
stores an integer (or whole number or fixed-point number); a double variable stores a floating-
point number (or real number); a String variable stores texts.
.
An identifier is needed to name a variable (or any other entity such as a method or a class). Java
imposes the following rules on identifiers:
An identifier is a sequence of characters, of any length, comprising uppercase and lowercase
letters (a-z, A-Z), digits (0-9), underscore (_), and dollar sign ($).
White space (blank, tab, newline) and other special characters (such as +, -, *, /, @, &, commas, etc.)
are not allowed. Take note that blank and dash (-) are not allowed, i.e., "max value" and "max-value"
are not valid names. (This is because blank creates two tokens and dash crashes with minus sign!)
An identifier must begin with a letter (a-z, A-Z) or underscore (_). It cannot begin with a digit (0-
9) (because that could confuse with a number). Identifiers begin with dollar sign ($) are reserved
for system-generated entities.
An identifier cannot be a reserved keyword or a reserved literal
(e.g., class, int, double, if, else, for, true, false, null).
Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
Examples: abc, _xyz, $123, _1_2_3 are valid identifiers. But 1abc, min-value, surface area, ab@c are
NOT valid identifiers.
www.arjun00.com.np Page 6
A variable name is a noun, or a noun phrase made up of several words with no spaces between
words. The first word is in lowercase, while the remaining words are initial-capitalized. For
examples, radius, area, fontSize, numStudents, xMax, yMin, xTopLeft, isValidInput,
and thisIsAVeryLongVariableName. This convention is also known as camel-case.
Recommendations
It is important to choose a name that is self-descriptive and closely reflects the meaning of the
variable, e.g., numberOfStudents or numStudents, but not n or x, to store the number of students. It
is alright to use abbreviations.
Do not use meaningless names like a, b, c, i, j, k, n, i1, i2, i3, j99, exercise85 (what is the purpose of
this exercise?), and example12 (What is this example about?).
Avoid single-letter names like i, j, k, a, b, c, which are easier to type but often meaningless.
Exceptions are common names like x, y, z for coordinates, i for index. Long names are harder to
type, but self-document your program. (I suggest you spend sometimes practicing your typing.)
Use singular and plural nouns prudently to differentiate between singular and plural variables. For
example, you may use the variable row to refer to a single row number and the variable rows to
refer to many rows (such as an array of rows - to be discussed later).
To use a variable in your program, you need to first introduce it by declaring its name and type, in
one of the following syntaxes. The act of declaring a variable allocates a storage of size capable of
holding a value of the type.
Syntax Example
// Declare a variable of a specified type int sum;
type identifier; double average;
String statusMsg;
// Declare multiple variables of the SAME type, int number, count;
// separated by commas double sum, difference, product, quotient;
type identifier1, identifier2, ..., identifierN; String helloMsg, gameOverMsg;
// Declare a variable and assign an initial value int magicNumber = 99;
type identifier = initialValue; double pi = 3.14169265;
String helloMsg = "hello,";
// Declare multiple variables of the SAME type, int sum = 0, product = 1;
// with initial values double height = 1.2; length = 3.45;
type identifier1 = initValue1, ..., identifierN = initValueN; String greetingMsg = "hi!", quitMsg = "bye!";
Constants are non-modifiable (immutable) variables, declared with keyword final. You can only
assign values to final variables ONCE. Their values cannot be changed during program execution.
For examples:
final double PI = 3.14159265; // Declare and initialize the constant
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
3. Unary Operator,
4. Arithmetic Operator,
5. Shift Operator,
6. Relational Operator,
7. Bitwise Operator,
8. Logical Operator,
9. Ternary Operator and
10. Assignment Operator.
Equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary Ternary ?:
Assignment Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
www.arjun00.com.np Page 8
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21
www.arjun00.com.np Page 9
true
Java arithmatic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
www.arjun00.com.np Page 10
80
80
240
The Java right shift operator >> is used to move left operands value to right by the number of bits
specified by the right operand.
Java Right Shift Operator Example
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
www.arjun00.com.np Page 11
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
www.arjun00.com.np Page 12
Java Ternary Operator
Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in
Java programming. it is the only conditional operator which takes three operands.
Another Example:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5
www.arjun00.com.np Page 13
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:
13
9
18
9
In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically. The automatic conversion is done by the compiler and manual
conversion performed by the programmer. In this section, we will discuss type casting and its
types with proper examples.
Type casting
Convert a value from one data type to another data type is known as type casting.
www.arjun00.com.np Page 14
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
Both data types must be compatible with each other.
The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see
an example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
www.arjun00.com.np Page 15
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
www.arjun00.com.np Page 16
Java if-else Statement:
The java if-else statement also tests the condition. It executes the if block if condition is true.
Syntax
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
www.arjun00.com.np Page 17
public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}
Output:
odd number
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
www.arjun00.com.np Page 18
System.out.println("Invalid!");
}
}
}
Output:
C grade
www.arjun00.com.np Page 19
Output:
You are eligible to donate blood
Example 2:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
} }
Output:
You are not eligible to donate blood
Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
www.arjun00.com.np Page 20
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
www.arjun00.com.np Page 21
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
Output:
Vowel
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in Java.
1. for loop
2. while loop
3. do-while loop
www.arjun00.com.np Page 22
Java For Loop vs While Loop vs Do While Loop
Comparison for loop while loop do while loop
Introduction The Java for loop is a control The Java while loop is The Java do while loop
flow statement that iterates a a control flow is a control flow
part of the programs multiple statement that statement that
times. executes a part of the executes a part of the
programs repeatedly programs at least once
on the basis of given and the further
boolean condition. execution depends
upon the given
boolean condition.
When to use If the number of iteration is If the number of If the number of
fixed, it is recommended to iteration is not fixed, it iteration is not fixed
use for loop. is recommended to and you must have to
use while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.
Syntax for(init;condition;incr/decr){ while(condition){ do{
// code to be executed //code to be executed //code to be executed
} } }while(condition);
Example //for loop //while loop //do-while loop
for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);
Syntax for for(;;){ while(true){ do{
infinitive //code to be executed //code to be executed //code to be executed
loop } } }while(true);
www.arjun00.com.np Page 23
Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It
is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Example:
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
www.arjun00.com.np Page 24
11
12
13
21
22
23
31
32
33
Pyramid Example 1:
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
**
***
****
*****
Pyramid Example 2:
public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
******
*****
****
***
**
*
www.arjun00.com.np Page 25
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
www.arjun00.com.np Page 26
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33
www.arjun00.com.np Page 27
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
www.arjun00.com.np Page 28
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
www.arjun00.com.np Page 29
1
2
3
4
www.arjun00.com.np Page 30
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
6
7
8
9
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is
continued when it reaches to 5.
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
www.arjun00.com.np Page 31
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
www.arjun00.com.np Page 32
System.out.println(a[i]);
}}
Output:
33
3
4
5
System.out.println(min);
}
www.arjun00.com.np Page 33
min(a);//passing array to method
}}
Output:
3
www.arjun00.com.np Page 34
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array
in negative, equal to the array size or greater than the array size while traversing the array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
www.arjun00.com.np Page 35
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445
Jagged Array in Java
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
//Java Program to illustrate the jagged array
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
www.arjun00.com.np Page 36
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
}}
Output:
268
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the
columns of the second matrix which can be understood by the image given below.
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
//Java Program to multiply two matrices
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
www.arjun00.com.np Page 37
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
***************************************************************************************************
What is OOP?
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software
development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It
can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of each other's data or code. The only necessary
thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the
tail, barking, eating, etc.
www.arjun00.com.np Page 1
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume
any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides
code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer
differently, to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know
the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
www.arjun00.com.np Page 2
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule,
it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members
are private here.
What Is a Class?
We can define a class as a container that stores the data members and methods together. These data members and
methods are common to all the objects present in a particular package.
Every class we use in Java consists of the following components, as described below:
Access Modifier
Object-oriented programming languages like Java provide the programmers with four types of access modifiers.
1. Public
2. Private
3. Protected
4. Default
These access modifiers specify the accessibility and users permissions of the methods and members of the class.
Class Name
This describes the name given to the class that the programmer decides on, according to the predefined naming
conventions.
www.arjun00.com.np Page 3
Type of Classes
In Java, we classify classes into two types:
Built-in Classes
Built-in classes are just the predefined classes that come along with the Java Development Kit (JDK). We also call
these built-in classes libraries. Some examples of built-in classes include:
java.lang.System
java.util.Date
java.util.ArrayList
java.lang.Thread
Lots of classes and methods are already predefined by the time you start writing your own code:
some already written by other programmers in your team
many predefined packages, classes, and methods come from the Java Library.
Library: collection of packages
Package: contains several classes
class: contains several methods
Method: a set of instructions
java.lang.String
String class will be the undisputed champion on any day by popularity and none will deny that. This is a final class
and used to create / operate immutable string literals. It was available from JDK 1.0
java.lang.System
Usage of System depends on the type of project you work on. You may not be using it in your project but still it is
one of the popular java classes around. This is a utility class and cannot be instantiated. Main uses of this class are
access to standard input, output, environment variables, etc. Available since JDK 1.0
java.lang.Exception
Throwable is the super class of all Errors and Exceptions. All abnormal conditions that can be handled comes
www.arjun00.com.np Page 4
under Exception. NullPointerException is the most popular among all the exceptions. Exception is at top of
hierarchy of all such exceptions. Available since JDK 1.0
java.util.ArrayList
An implementation of array data structure. This class implements List interface and is the most popular member or
java collections framework. Difference between ArrayList and Vector is one popular topic among the beginners and
frequently asked question in java interviews. It was introduced in JDK 1.2
java.util.HashMap
An implementation of a key-value pair data structure. This class implements Map interface. As similar to ArrayList
vs Vector, we have HashMap vs Hashtable popular comparisons. This happens to be a popular collection class that
acts as a container for property-value pairs and works as a transport agent between multiple layers of an
application. It was introduced in JDK 1.2
java.lang.Object
Great grandfather of all java classes. Every java class is a subclass of Object. It will be used often when we work on
a platform/framework. It contains the important methods like equals, hashcode, clone, toString, etc. It is available
from day one of java (JDK 1.0)
java.lang.Thread
A thread is a single sequence of execution, where multiple thread can co-exist and share resources. We can extend
this Thread class and create our own threads. Using Runnable is also another option. Usage of this class depends on
the domain of your application. It is not absolutely necessary to build a usual application. It was available from JDK
1.0
java.lang.Class
Class is a direct subclass of Object. There is no constructor in this class and their objects are loaded in JVM
by classloaders. Most of us may not have used it directly but I think its an essential class. It is an important class in
doing reflection. It is available from JDK 1.0
java.util.Date
This is used to work with date. Sometimes we feel that this class should have added more utility methods and we
end up creating those. Every enterprise application we create has a date utility. Introduced in JDK 1.0 and later
made huge changes in JDK1.1 by deprecating a whole lot of methods.
java.util.Iterator
This is an interface. It is very popular and came as a replacement for Enumeration. It is a simple to use convenience
utility and works in sync with Iterable. It was introduced in JDK 1.2
In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification
Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a
variable nor the name of a folder used for package.
Using any predefined class in Java won’t cause such compiler error as Java predefined classes are not keywords.
Following are some invalid variable declarations in Java:
boolean break = false; // not allowed as break is keyword
int boolean = 8; // not allowed as boolean is keyword
boolean goto = false; // not allowed as goto is keyword
String final = "hi"; // not allowed as final is keyword
Using predefined class name as User defined class name
Question : Can we have our class name as one of the predefined class name in our program?
Answer : Yes we can have it. Below is example of using Number as user defined class
// Number is predefined class name in java.lang package
// Note : java.lang package is included in every java
program by default
public class Number
www.arjun00.com.np Page 5
{
public static void main (String[] args)
{
System.out.println("It works");
}
}
Output:
It works
Using String as User Defined Class:
// String is predefined class name in java.lang package
// Note : java.lang package is included in every java
program by default
public class String
{
public static void main (String[] args)
{
System.out.println("I got confused");
}
}
User-Defined Classes
User-defined classes are rather self-explanatory. The name says it all. They are classes that the user defines and
manipulates in the real-time programming environment. User-defined classes are broken down into three types:
Concrete Class
Concrete class is just another standard class that the user defines and stores the methods and data members in.
Syntax:
class con{
//class body;
}
Abstract Class
www.arjun00.com.np Page 6
Abstract classes are similar to concrete classes, except that you need to define them using the "abstract" keyword.
If you wish to instantiate an abstract class, then it should include an abstract method in it. Otherwise, it can only be
inherited.
Syntax:
abstract class AbstClas{
//method();
abstract void demo();
}
Interfaces
Interfaces are similar to classes. The difference is that while class describes an object’s attitudes and behaviors,
interfaces contain the behaviors a class implements. These interfaces will only include the signatures of the
method but not the actual method.
Syntax:
public interface demo{
public void signature1();
public void signature2();
}
public class demo2 implements demo{
public void signature1(){
//implementation;
}
public void signature2(){
//implementation;
}
}
Identity
This is the unique name given by the user that allows it to interact with other objects in the project.
Example:
Name of the student
Behavior
The behavior of an object is the method that you declare inside it. This method interacts with other objects present
in the project.
www.arjun00.com.np Page 7
Example:
Studying, Playing, Writing
State
The parameters present in an object represent its state based on the properties reflected by the parameters of
other objects in the project.
Example:
Section, Roll number, Percentage
Create a Class
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named MyClass, so now we can use this
to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
www.arjun00.com.np Page 8
public class Main {
int x = 5;
www.arjun00.com.np Page 9
public class Main {
int x = 5;
Multiple Objects
If you create multiple objects of one class, you can change the attribute values in one object, without affecting the
attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {
www.arjun00.com.np Page 10
int x = 5;
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
www.arjun00.com.np Page 11
}
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object
of a class is created. It can be used to set initial values for object attributes:
Example
Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute
www.arjun00.com.np Page 12
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When
we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main {
int x;
public Main(int y) {
x = y;
}
// Outputs 5
www.arjun00.com.np Page 13
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.
The library contains components for managing input, database programming, and much much more.
The library is divided into packages and classes. Meaning you can either import a single class (along with its
methods and attributes), or a whole package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the
following code:
Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a
complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class from
the java.util package. This package also contains date and time facilities, random-number generator and other
utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the
classes in the java.util package:
Example
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store them. Just like
folders on your computer:
Example
└── root
└── mypack
www.arjun00.com.np Page 14
└── MyPackageClass.java
To create a package, use the package keyword:
MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods
to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class. You will learn more
about objects and how to access methods through objects later in this tutorial.
void means that this method does not have a return value. You will learn more about return values later in this
chapter
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
www.arjun00.com.np Page 15
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
www.arjun00.com.np Page 16
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
// Liam is 5
// Jenny is 8
// Anja is 31
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value. If you want the
method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:
Example
public class Main {
static int myMethod(int x) {
return 5 + x;
}
www.arjun00.com.np Page 17
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
www.arjun00.com.np Page 18
Inheritance and Interfaces
4.1. Classes, Super classes, and Subclasses
4.2. Polymorphism
4.3. Dynamic Binding
4.4. Final Classes and Methods
4.5. Abstract Classes
4.6. Access Specifiers
4.7. Interfaces
Interface: Interfaces are the blueprints of the classes. They specify what a class must do and not how. Like a class, an
interface can have methods and variables, but the methods declared in an interface are by default abstract (i.e.) they
only contain method signature and not the body of the method. Interfaces are used to implement a
complete abstraction.
Inheritance: It is a mechanism in java by which one class is allowed to inherit the features of the another class. There are
multiple inheritances possible in java. They are:
Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In the image below, class A
serves as a base class for the derived class B.
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived
class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B,
which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
www.arjun00.com.np Page 1
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived class B, C and D.
www.arjun00.com.np Page 2
Inheritance in Java
Inheritance
Types of Inheritance
Why multiple inheritance is not possible in Java in case of class?
www.arjun00.com.np Page 3
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is
an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or
subclass.
In fact, in Java, all classes must be derived from some class. Which leads to the question "Where does it all begin?" The
top-most class, the class from which all other classes are derived, is the Object class defined in java.lang. Object is the
root of a hierarchy of classes.
www.arjun00.com.np Page 4
The subclass inherits state and behavior in the form of variables and methods from its superclass. The subclass can just
use the items inherited from its superclass as is, or the subclass can modify or override it. So, as you drop down in the
hierarchy, the classes become more and more specialized:
Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its
ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.
Creating Subclasses
To create a subclass of another class use the extends clause in your class declaration. (The Class Declaration explains all
of the components of a class declaration in detail.) As a subclass, your class inherits member variables and methods
from its superclass. Your class can choose to hide variables or override methods inherited from its superclass.
Sometimes, for security or design reasons, you want to prevent your class from being subclassed. Or, you may just wish
to prevent certain methods within your class from being overriden. In Java, you can achieve either of these goals by
marking the class or the method as final.
www.arjun00.com.np Page 5
System.out.println("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car
class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
www.arjun00.com.np Page 6
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
www.arjun00.com.np Page 7
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
www.arjun00.com.np Page 8
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
www.arjun00.com.np Page 9
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by
inheritance.
Like we specified Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those
methods to perform different tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could
be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Why And When To Use "Inheritance" and "Polymorphism"?
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
www.arjun00.com.np Page 11
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-primitive.
int data=30;
Here data variable is a type of int.
2) References have a type
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
3) Objects have a type
An object is an instance of particular java class,but it is also an instance
of its superclass.
class Animal{}
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
www.arjun00.com.np Page 12
Example of static binding
class Dog{
private void eat(){System.out.println("dog is eating...");}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
www.arjun00.com.np Page 13
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because
final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
www.arjun00.com.np Page 14
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
Output:running...
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
www.arjun00.com.np Page 15
}
Output: 70
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).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
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.
www.arjun00.com.np Page 16
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It
needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method
www.arjun00.com.np Page 17
Example of abstract class
A method which is declared as abstract and does not have implementation is known as an abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by
the Honda class.
www.arjun00.com.np Page 18
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Definition :
- Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These
Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or
sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented
programming.
In java we have four Access Specifiers and they are listed below.
1. public
2. private
3. protected
4. default(no specifier)
public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be
accessed from any class in the Java program, whether these classes are in the same package or in another package.
Example :
www.arjun00.com.np Page 19
public class Demo { // public class
public x, y, size; // public instance variables
}
private specifiers :
Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be accessed within the
same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are
not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. Using Private
Specifier we can achieve encapsulation and hide data from the outside world.
Example :
protected specifiers :
Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within
the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.
default(no specifier):
When you don't set access specifier for the element, it will follow the default accessibility level. There is no default
specifier keyword. Classes, variables, and methods can be default accessed.Using default specifier we can access class,
method, or field which belongs to same package,but not from outside this package.
Example :
www.arjun00.com.np Page 20
class Demo
{
int i; (Default)
}
Interfaces in Java
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default
abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and any class implementing Player must be
able to (or must implement) move(). So it specifies a set of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then the class must be declared abstract.
• A Java library example is, Comparator Interface. If a class implements this interface, then it can be used to
sort a collection.
Syntax :
interface <interface_name> {
To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the methods in
an interface are declared with an empty body and are public and all fields are public, static and final by default. A
www.arjun00.com.np Page 21
class that implements an interface must implement all the methods declared in the interface. To implement interface
use implements keyword.
To implement an interface we use keyword: implements
// interface.
import java.io.*;
// A simple interface
interface In1
void display();
// interface.
System.out.println("Geek");
www.arjun00.com.np Page 22
}
// Driver Code
t.display();
System.out.println(a);
Output:
Geek
10
A real-world example:
Let’s consider the example of vehicles like bicycle, car, bike………, they have common functionalities. So we make an
interface and put all these common functionalities. And lets Bicycle, Bike, car ….etc implement all these functionalities
in their own class in their own way.
import java.io.*;
interface Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
www.arjun00.com.np Page 23
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
www.arjun00.com.np Page 24
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}
class GFG {
www.arjun00.com.np Page 25
Unit –V Exception Handling
5.1. Dealing With Errors
5.2. Catching Exceptions
5.3. try, catch, throw, throws, and finally
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.
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
This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know
the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by
user.
Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary corrective
actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by zero this
www.arjun00.com.np Page 1
exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for example
array size is 5 (which means it has five elements) and you are trying to access the 10th element.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of hierarchy.One branch is headed
by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an
example of such an exception.Another branch,Error are used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
www.arjun00.com.np Page 2
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked
exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
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.
3) Error
www.arjun00.com.np Page 3
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether an
exception is handled or not.
Let's see an example of Java Exception Handling where we using a try-catch statement to handle the exception.
www.arjun00.com.np Page 4
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has
characters, converting this variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
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 of try block, the rest of the block code will not execute. So, it is
recommended not to keeping the code in try block that will not throw an exception.
www.arjun00.com.np Page 5
Java try block must be followed by either catch or finally block.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}Syntax
of try-finally block
1. try{
2. //code that may throw an exception
3. }finally{}Java
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.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.
Example 1
Output:
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).
www.arjun00.com.np Page 6
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Let's see the solution of the above problem by a java try-catch block.
Example 2
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
www.arjun00.com.np Page 7
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16. }
17.
18. }
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
Example 4
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
www.arjun00.com.np Page 8
2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. // handling the exception
9. catch(Exception e)
10. {
11. // displaying the custom message
12. System.out.println("Can't divided by zero");
13. }
14. }
15.
16. }
Output:
Example 6
Output:
www.arjun00.com.np Page 9
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
Output:
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).
www.arjun00.com.np Page 10
8. }
9. // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
10. catch(ArrayIndexOutOfBoundsException e)
11. {
12. System.out.println(e);
13. }
14. System.out.println("rest of the code");
15. }
16.
17. }
Output:
Example 9
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
www.arjun00.com.np Page 11
Let's see an example to handle checked exception.
1. import java.io.FileNotFoundException;
2. import java.io.PrintWriter;
3.
4. public class TryCatchExample10 {
5.
6. public static void main(String[] args) {
7.
8.
9. PrintWriter pw;
10. try {
11. pw = new PrintWriter("jtp.txt"); //may throw exception
12. pw.println("saved");
13. }
14. // providing the checked exception handler
15. catch (FileNotFoundException e) {
16.
17. System.out.println(e);
18. }
19. System.out.println("File saved successfully");
20. }
21. }
Output:
www.arjun00.com.np Page 12
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:
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the
code is executed.
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
www.arjun00.com.np Page 13
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Example 1
Output:
Example 2
www.arjun00.com.np Page 14
5. try{
6. int a[]=new int[5];
7.
8. System.out.println(a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.println("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Output:
Example 3
In this example, try block contains two exceptions. But at a time only one exception occurs and its corresponding catch
block is invoked.
www.arjun00.com.np Page 15
15. {
16. System.out.println("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. System.out.println("Parent Exception occurs");
21. }
22. System.out.println("rest of the code");
23. }
24. }
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In such case,
the catch block containing the parent exception class Exception will invoked.
Output:
www.arjun00.com.np Page 16
rest of the code
Example 5
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e. from most specific to
most general).
1. class MultipleCatchBlock5{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10. System.out.println("rest of the code...");
11. }
12. }
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause
another error. In such cases, exception handlers have to be nested.
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
www.arjun00.com.np Page 17
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
www.arjun00.com.np Page 18
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
www.arjun00.com.np Page 19
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
12. Output:5
13. finally block is always executed
14. rest of the code...
15. Case 2
16. Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Case 3
Let's see the java finally example where exception occurs and handled.
www.arjun00.com.np Page 20
11. }
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18,
we are throwing the ArithmeticException otherwise print a message welcome to vote.
www.arjun00.com.np Page 21
JAVA INPUT/OUTPUT
Java I/O (Input and Output) is used to processthe
input and produce the output based on the input.
Java uses the concept of stream to make I/O
operation fast. The java.io package contains allthe
classes required for input and output operations.
We can perform file handling in java by javaIO
API.
STREAM
A stream is a sequence of data.In Java a streamis
composed of bytes. It's called a stream becauseit's like a
stream of water that continues to flow.
In java, 3 streams are created for us automatically.
All these streams are attachedwith console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
2. System.err.println("error message");
www.arjun00.com.np
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st
character
2. System.out.println((char)i);//will print the char
acter
www.arjun00.com.np
OUTPUTSTREAM CLASS
www.arjun00.com.np
InputStream class
Input Stream class is an abstract class. It is the superclass
of all classes representing an inputstream of bytes.
www.arjun00.com.np
FILEINPUTSTREAM AND
FILEOUTPUTSTREAM(FILE HANDLING)
www.arjun00.com.np
EXAMPLE OF JAVA FILEOUTPUTSTREAM
CLASS
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new
FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into
byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
www.arjun00.com.np
JAVA FILEINPUTSTREAM CLASS
www.arjun00.com.np
EXAMPLE OF FILEINPUTSTREAM
CLASS
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new
FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
www.arjun00.com.np
EXAMPLE OF READING THE DATA OF
CURRENT
JAVA FILE AND WRITING IT INTO ANOTHER
FILE
www.arjun00.com.np
import java.io.*;
class C{
public static void main(String args[])throws
Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new
FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}
METHODS OF BYTEARRAYOUTPUTSTREAM
CLASS
www.arjun00.com.np
JAVA BYTEARRAYOUTPUTSTREAM
EXAMPLE
Let's see a simple example of java
ByteArrayOutputStream class to write data into2 files.
import java.io.*;
class S{
public static void main(String args[])throws
Exception{
FileOutputStream fout1=new
FileOutputStream("f1.txt");
FileOutputStream fout2=new
FileOutputStream("f2.txt");
ByteArrayOutputStream bout=new
ByteArrayOutputStream();
bout.write(139);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
success...
www.arjun00.com.np
JAVA SEQUENCEINPUTSTREAM
CLASS
Java SequenceInputStream class is used to readdata from
multiple streams. It reads data of streams one by one.
CONSTRUCTORS OF SEQUENCEINPUTSTREAM
CLASS:
www.arjun00.com.np
Constructors of SequenceInputStream class:
Simple example of SequenceInputStream class
In this example, we are printing the data of twofiles
f1.txt and f2.txt.
import java.io.*;
class Simple{
public static void main(String args[])throws
Exception{
FileinputStream fin1=new
FileinputStream("f1.txt");
FileinputStream fin2=new
FileinputStream("f2.txt");
SequenceinputStream sis=new
SequenceinputStream(fin1,fin2);
int i;
while((i=sis.read())!=-1){
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}
www.arjun00.com.np
EXAMPLE OF SEQUENCEINPUTSTREAM
THAT READS THE DATA FROM TWO FILES
www.arjun00.com.np
EXAMPLE OF SEQUENCEINPUTSTREAM
CLASS THAT READS THE DATA FROM
MULTIPLE FILES USING ENUMERATION
www.arjun00.com.np
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new
BufferedOutputStream(fout);
String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
success...
www.arjun00.com.np
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new
BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
Sachin is my favourite player
CONSTRUCTORS OF FILEWRITER
CLASS
www.arjun00.com.np
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:
success...
CONSTRUCTORS OF FILEWRITER
CLASS
www.arjun00.com.np
METHODS OF FILEREADER CLASS
import java.io.*;
class Simple{
public static void main(String args[])throws
Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:
my name is sachin
www.arjun00.com.np
CHARARRAYWRITER CLASS:
The CharArrayWriter class can be used to writedata to
multiple files. This class implements theAppendable
interface. Its buffer automatically grows when data is
written in this stream. Calling the close() method on
this object has noeffect.
Example of CharArrayWriter class:
In this example, we are writing a common data to4 files
a.txt, b.txt, c.txt and d.txt.
import java.io.*;
class Simple{
public static void main(String args[])throws
Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("my name is");
FileWriter f1=new FileWriter("a.txt");
FileWriter f2=new FileWriter("b.txt");
FileWriter f3=new FileWriter("c.txt");
FileWriter f4=new FileWriter("d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
}
} www.arjun00.com.np
READING DATA FROM KEYBOARD
There are many ways to read data from the
keyboard. For example:
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read
data from keyboard.It performs two tasks:
connects to input stream of keyboard
converts the byte-oriented stream into character-
oriented stream
BufferedReader class
BufferedReader class can be used to read dataline by
line by readLine() method.
www.arjun00.com.np
import java.io.*;
class G5{
public static void main(String args[])throws
Exception{
InputStreamReader r=new
InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Arjun
Welcome Arjun
www.arjun00.com.np
Another Example of reading data from keyboard by
InputStreamReader and BufferdReader classuntil the
user writes stop
In this example, we are reading and printing thedata
until the user prints stop.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new
InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Arjun
data is: Arjun
Enter data: 10
data is: 10
Enter data: stop
data is: stop
www.arjun00.com.np
Java Console class
The Java Console class is be used to get inputfrom
console. It provides methods to read text and
password.
If you read password using Console class, it will
not be displayed to the user.
The java.io.Console class is attached with system
console internally. The Console class is introduced
since 1.5.
Let's see a simple example to read text fromconsole.
String text=System.console().readLine();
System.out.println("Text is: "+text);
www.arjun00.com.np
HOW TO GET THE OBJECT OF
CONSOLE
System class provides a static method console() that
returns the unique instance of Console class.
public static Console console(){}
Let's see the code to get the instance of Console class.
Console c=System.console();
import java.io.*;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: Arjun
Welcome Arjun
JAVA CONSOLE EXAMPLE TO READ
PASSWORD
www.arjun00.com.np
import java.io.*;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char arra
y into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: sonoo
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+"
name:"+name+" fee:"+fee);
sc.close();
}
}
import java.util.*;
public class ScannerTest2{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea
buiscuits";
Scanner s = new
Scanner(input).useDelimiter("\\s");
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.nextInt());
System.out.println(s.next());
s.close();
}}
Output:
10tea20coffee
java.io.PrintStream class:
The PrintStream class provides methods to write data
to another stream. The PrintStream class
automatically flushes the data so there is no needto call
flush() method. Moreover, its methods don't throw
IOException.
www.arjun00.com.np
There are many methods in PrintStream class. Let's see
commonly
used methods of PrintStream class:
public void print(boolean b): it prints the specified boolean
value.
public void print(char c): it prints the specified char value.
public void print(char[] c): it prints the specified character
arrayvalues.
public void print(int i): it prints the specified int value.
public void print(long l): it prints the specified long value.
public void print(float f): it prints the specified float value.
public void print(double d): it prints the specified double
value.
public void print(String s): it prints the specified string value.
public void print(Object obj): it prints the specified object
value.
public void println(boolean b): it prints the specified boolean
value and terminates the line.
public void println(char c): it prints the specified char value
and
terminates the line.
public void println(char[] c): it prints the specified character
array values and terminates the line.
public void println(int i): it prints the specified int value and
terminates the line.
public void println(long l): it prints the specified long value
and terminatesthe line.
public void println(float f): it prints the specified float value
and terminates the line.
public void println(double d): it prints the specified
double value and terminates the line.
public void println(String s): it prints the specified
string value and terminates the line./li>
public void println(Object obj): it prints the specified object
value and terminates the line.
www.arjun00.com.np
public void println(): it terminates the line only.
public void printf(Object format, Object... args): it writes the
formatted
string to the current stream.
public void printf(Locale l, Object format, Object... args):
it writes theformatted string to the current stream.
public void format(Object format, Object... args): it writes the
formatted string to the current stream using specified format.
public void format(Locale l, Object format, Object... args): it
writes theformatted string to the current stream using specified
format.
EXAMPLE OF
JAVA.IO.PRINTSTREAMCLASS:
In this example, we are simply printing integerand
string values.
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws
Exception{
FileOutputStream fout=new
FileOutputStream("mfile.txt");
PrintStream pout=new PrintStream(fout);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}
}
www.arjun00.com.np
Example of printf() method
ofjava.io.PrintStream class:
Let's see the simple example
of printing integer value by
format specifier.
class PrintStreamTest{
public static void main(String args[]){
int a=10;
System.out.printf("%d",a);//Note, out is the object
of PrintStream class
}
}
Output:10
Compressing and Uncompressing File
The DeflaterOutputStream and InflaterInputStream
classes provide mechanism to compress and
uncompress the data in the deflate compression
format.
DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the
data in the deflate compression format. It provides
facility to the other compression filters, suchas
GZIPOutputStream.
Example of Compressing file
using DeflaterOutputStream.
In this example, we are reading data of a file and
compressing it into another file using
DeflaterOutputStream class. You can compress anyfile,
here we are compressing the Deflater.java file www.arjun00.com.np
import java.io.*;
import java.util.zip.*;
class Compress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("Deflater.java");
FileOutputStream fout=new FileOutputStream("def.txt");
DeflaterOutputStream out=new DeflaterOutputStream(fout);
int i;
while((i=fin.read())!=-1){
out.write((byte)i);
out.flush();
}
fin.close();
out.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
InflaterInputStream class:
The InflaterInputStream class is used to uncompress
the file in the deflate compression format. It provides
facility to the other uncompression filters, such as
GZIPInputStreamclass.
Example of uncompressing file using
InflaterInputStream class
In this example, we are
decompressing thecompressed file
def.txt into D.java .
www.arjun00.com.np
import java.io.*;
import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
www.arjun00.com.np
⬧ Reading and Writing Files:
As described earlier, A stream can be defined as a
sequence of data. TheInputStream is used to read data
from a source andthe OutputStream is used for
writing data to adestination.
Here is a hierarchy of classes to deal with Inputand
Output streams.
www.arjun00.com.np
THE END