Elective I Java Programming Notes
Elective I Java Programming Notes
Elective I Java Programming Notes
AN INTRODUCTION TO JAVA
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
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
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
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.
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".
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.
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.
}}
Output:
22
21
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.
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
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
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.
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
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
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{
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
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
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);
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
System.out.println(min);
}
}}
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}};
LECTURER: SURAJ PANDEY , CCT COLLEGE Page 37
***************************************************************************************************
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.
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.
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.
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
LECTURER: SURAJ PANDEY CCT COLLEGE Page 4
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
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
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.
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;
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 {
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
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
// 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
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
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;
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;
}
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.
Inheritance
Types of Inheritance
Why multiple inheritance is not possible in Java in case of class?
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.
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.
// 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[]){
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:
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.
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.
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...");}
}
Output:running...
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
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.
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
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.
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 :
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 :
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
// interface.
import java.io.*;
// A simple interface
interface In1
void display();
// interface.
System.out.println("Geek");
// 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){
// 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){
}
class GFG {
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
Lecturer: Suraj Pandey, CCT College Page 1
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.
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
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.
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.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
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).
Lecturer: Suraj Pandey, CCT College Page 6
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.
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
Output:
Example 6
Output:
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).
Output:
Example 9
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
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. }
Test it Now
Output:
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.
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
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.
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:
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. }
Test it Now
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)
Lecturer: Suraj Pandey, CCT College Page 17
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.
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.
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. }
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
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.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
input.
Java uses the concept of stream to make I/O
operation fast. The java.io package contains all
the classes required for input and output
operations.
We can perform file handling in java by java
IO API.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
is composed of bytes. It's called a stream because
it's like a stream of water that continues to flow.
In java, 3 streams are created for us
automatically. All these streams are attached
with console.
1) System.out: standard output stream
COLLEGE
BY LECTURER SURAJ PANDEY CCT
1. System.out.println("simple message");
2. System.err.println("error message");
COLLEGE
BY LECTURER SURAJ PANDEY CCT
st character
2. System.out.println((char)i);//will print the char
acter
COLLEGE
BY LECTURER SURAJ PANDEY CCT
an output destination. The stream in the java.io
package supports many data such as primitives,
Object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. there
are two kinds of Streams
InPutStream: The InputStream is used to read data
from a source.
OutPutStream: the OutputStream is used for
writing data to a destination.
Note Provider: Lecturer. Suraj Pandey
LET'S UNDERSTAND WORKING OF JAVA OUTPUTSTREAM AND INPUTSTREAM BY
THE FIGURE GIVEN BELOW.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
OUTPUTSTREAM CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
superclass of all classes representing an input
stream of bytes.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
another words, they are used for file handling in
java.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
If you have to write primitive values then use
FileOutputStream.Instead, for character-oriented
data, prefer FileWriter.But you can write byte-
oriented as well as character-oriented data.
import java.io.*;
class Test{
public static void main(String args[]){
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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);}
}
}
Note Provider: Lecturer. Suraj Pandey
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
JAVA FILEINPUTSTREAM CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
bytes such as image data. For reading streams of
characters, consider using FileReader.
It should be used to read byte-oriented data for
example to read image, audio, video etc.
import java.io.*;
class SimpleRead{
public static void main(String args[]){
COLLEGE
BY LECTURER SURAJ PANDEY CCT
try{
FileInputStream fin=new FileInputStream("abc.tx
t");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Note Provider: Lecturer. Suraj Pandey
Output:Sachin is my favourite player.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
EXAMPLE OF READING THE DATA OF CURRENT
JAVA FILE AND WRITING IT INTO ANOTHER FILE
COLLEGE
BY LECTURER SURAJ PANDEY CCT
image file, video file etc. In this example, we are
reading the data of C.java file and writing it into
another file M.java.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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();
}
}
COLLEGE
BY LECTURER SURAJ PANDEY CCT
data is written into a byte array that can be
written to multiple stream.
The ByteArrayOutputStream holds a copy of
data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream
automatically grows according to data.
Closing the ByteArrayOutputStream has no
effect.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
METHODS OF BYTEARRAYOUTPUTSTREAM
CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
JAVA BYTEARRAYOUTPUTSTREAM EXAMPLE
COLLEGE
BY LECTURER SURAJ PANDEY CCT
2 files.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStrea
m();
bout.write(139);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("success...");
}
}
success...
Note Provider: Lecturer. Suraj Pandey
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
JAVA SEQUENCEINPUTSTREAM CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
streams one by one.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
Constructors of SequenceInputStream class:
Simple example of SequenceInputStream class
COLLEGE
BY LECTURER SURAJ PANDEY CCT
In this example, we are printing the data of two
files f1.txt and f2.txt.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fi
n2);
int i;
while((i=sis.read())!=-1){
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}
Note Provider: Lecturer. Suraj Pandey
EXAMPLE OF SEQUENCEINPUTSTREAM THAT
READS THE DATA FROM TWO FILES
COLLEGE
BY LECTURER SURAJ PANDEY CCT
f3.txt.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");
FileOutputStream fout=new FileOutputStream("f3.txt");
SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
int i;
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();
}
}
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Enumeration object. Enumeration object can be
get by calling elements method of the Vector
class. Let's see the simple example where we are
reading the data from the 4 files.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Vector v=new Vector();
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
//creating enumeration object by calling the elements method
Enumeration e=v.elements();
//passing the enumeration object in the constructor
SequenceInputStream bin=new SequenceInputStream(e);
int i=0;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
fin2.close();
}
}
COLLEGE
BY LECTURER SURAJ PANDEY CCT
internal buffer to store data. It adds more
efficiency than to write data directly into a
stream. So, it makes the performance fast.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
information in the BufferedOutputStream object
which is connected to the FileOutputStream
object. The flush() flushes the data of one stream
and send it into another. It is required if you
have connected the one stream with another.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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...
COLLEGE
BY LECTURER SURAJ PANDEY CCT
mechanism to make the performance fast.
Example of Java BufferedInputStream
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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
Note Provider: Lecturer. Suraj Pandey
JAVA FILEWRITER AND FILEREADER (FILE
HANDLING IN JAVA)
COLLEGE
BY LECTURER SURAJ PANDEY CCT
character-oriented classes, used for file handling
in java.
Java has suggested not to use the
FileInputStream and FileOutputStream classes
if you have to read and write the textual
information.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
oriented data to the file.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
METHODS OF FILEWRITER CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
Java FileWriter Example
In this example, we are writing the data in the
COLLEGE
BY LECTURER SURAJ PANDEY CCT
file abc.txt.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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...
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileInputStream class.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
METHODS OF FILEREADER CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
Java FileReader Example
In this example, we are reading the data from the
COLLEGE
BY LECTURER SURAJ PANDEY CCT
file abc.txt file.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
public static void main(String args[])throws Exce
ption{
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
Note Provider: Lecturer. Suraj Pandey
CHARARRAYWRITER CLASS:
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Appendable interface. Its buffer automatically
grows when data is written in this stream.
Calling the close() method on this object has no
effect.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
4 files a.txt, b.txt, c.txt and d.txt.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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();
}
}
Note Provider: Lecturer. Suraj Pandey
READING DATA FROM KEYBOARD
COLLEGE
BY LECTURER SURAJ PANDEY CCT
1. InputStreamReader
2. Console
3. Scanner
4. DataInputStream etc.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
data from keyboard.It performs two tasks:
connects to input stream of keyboard
COLLEGE
BY LECTURER SURAJ PANDEY CCT
In this example, we are connecting the
BufferedReader stream with the
InputStreamReader stream for reading the line
by line data from the keyboard.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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
Amit
Welcome Amit
COLLEGE
BY LECTURER SURAJ PANDEY CCT
until the user writes stop
In this example, we are reading and printing the
data until the user prints stop.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
COLLEGE
BY LECTURER SURAJ PANDEY CCT
from 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 from
console.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
METHODS OF CONSOLE CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
HOW TO GET THE OBJECT OF CONSOLE
COLLEGE
BY LECTURER SURAJ PANDEY CCT
public static Console console(){}
import java.io.*;
class ReadStringTest{
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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: james gosling
Welcome james gosling
import java.io.*;
class ReadPasswordTest{
public static void main(String args[]){
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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
Note Provider: Lecturer. Suraj Pandey
JAVA SCANNER CLASS
COLLEGE
BY LECTURER SURAJ PANDEY CCT
them.
The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and
parse various primitive values.
Java Scanner class is widely used to parse text
for string and primitive types using regular
expression.
Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.
Note Provider: Lecturer. Suraj Pandey
Commonly used methods of Scanner class
There is a list of commonly used Scanner class
COLLEGE
BY LECTURER SURAJ PANDEY CCT
methods:
COLLEGE
BY LECTURER SURAJ PANDEY CCT
bydefault. It provides many methods to read and
parse various primitive values.
Java Scanner class is widely used to parse text
for string and primitive types using regular
expression.
Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
methods:
Java Scanner Example to get input from console
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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();
}
}
Note Provider: Lecturer. Suraj Pandey
Enter your rollno 111 Enter your name
Ratan Enter 450000 Rollno:111
COLLEGE
BY LECTURER SURAJ PANDEY CCT
name:Ratan fee:450000
COLLEGE
BY LECTURER SURAJ PANDEY CCT
delimiter. The \s represents whitespace.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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
Note Provider: Lecturer. Suraj Pandey
java.io.PrintStream class:
The PrintStream class provides methods to write
COLLEGE
BY LECTURER SURAJ PANDEY CCT
data to another stream. The PrintStream class
automatically flushes the data so there is no need
to call flush() method. Moreover, its methods
don't throw IOException.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
public void print(char c): it prints the specified char value.
public void print(char[] c): it prints the specified character array
values.
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.
Note Provider: Lecturer. Suraj Pandey
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 terminates
the line.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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.
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 the
formatted 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 the
formatted string to the current stream using specified format.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Note Provider: Lecturer. Suraj Pandey
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileOutputStream fout=new FileOutputStream("mfile.tx
t");
PrintStream pout=new PrintStream(fout);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
}
}
Note Provider: Lecturer. Suraj Pandey
Example of printf() method of
java.io.PrintStream class:
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Let's see the simple example of printing integer
value by format specifier.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
int a=10;
System.out.printf("%d",a);//Note, out is the obje
ct of PrintStream class
}
}
Output:10
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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, such
as GZIPOutputStream.
Example of Compressing file using
DeflaterOutputStream class
In this example, we are reading data of a file and
compressing it into another file using
DeflaterOutputStream class. You can compress any
file, here we are compressing the Deflater.java file
Note Provider: Lecturer. Suraj Pandey
import java.io.*;
import java.util.zip.*;
class Compress{
public static void main(String args[]){
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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");
}
}
COLLEGE
BY LECTURER SURAJ PANDEY CCT
uncompress the file in the deflate compression
format. It provides facility to the other
uncompression filters, such as GZIPInputStream
class.
Example of uncompressing file using
InflaterInputStream class
In this example, we are decompressing the
compressed file def.txt into D.java .
COLLEGE
BY LECTURER SURAJ PANDEY CCT
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");
}
}
COLLEGE
BY LECTURER SURAJ PANDEY CCT
and I/O. We would see most commonly used
example one by one:
Byte Streams
Java byte streams are used to perform input and
output of 8-bit bytes. Though there are many
classes related to byte streams but the most
frequently used classes are
, FileInputStream and FileOutputStream.
Following is an example which makes use of
these two classes to copy an input file into an
output file:
Note Provider: Lecturer. Suraj Pandey
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
COLLEGE
BY LECTURER SURAJ PANDEY CCT
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close(); }
if (out != null)
{
out.close();
}}}} Note Provider: Lecturer. Suraj Pandey
Character Streams
Java Byte streams are used to perform input and
output of 8-bit bytes, where as
COLLEGE
BY LECTURER SURAJ PANDEY CCT
Java Character streams are used to perform input
and output for 16-bit unicode. Though there are many
classes related to character streams but the most
frequently used classes are
, FileReader and FileWriter.. Though internally
FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here major difference is that
FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
We can re-write above example which makes use of
these two classes to copy an input file (having unicode
characters) into an output file:
Note Provider: Lecturer. Suraj Pandey
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
COLLEGE
BY LECTURER SURAJ PANDEY CCT
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}}}}
Note Provider: Lecturer. Suraj Pandey
Reading and Writing Files:
As described earlier, A stream can be defined as a
COLLEGE
BY LECTURER SURAJ PANDEY CCT
sequence of data. TheInputStream is used to
read data from a source and
the OutputStream is used for writing data to a
destination.
Here is a hierarchy of classes to deal with Input
and Output streams.
COLLEGE
BY LECTURER SURAJ PANDEY CCT
FileInputStream:
This stream is used for reading data from the
files. Objects can be created using the keyword
new and there are several types of constructors
available.
Following constructor takes a file name as a
string to create an input stream object to read
the file.:
InputStream f = new
FileInputStream("C:/java/hello");
Note Provider: Lecturer. Suraj Pandey
Following constructor takes a file object to create
an input stream object to read the file. First we
COLLEGE
BY LECTURER SURAJ PANDEY CCT
create a file object using File() method as follows:
File f = new File("C:/java/hello"); InputStream f =
new FileInputStream(f);Once you
have InputStream object in hand, then there is a
list of helper methods which can be used to read
to stream or to do other operations on the stream.