OOPS
OOPS
MODULE 2
I/O Basics & Files: Reading input, writing output - Scanner class, Buffered Reader class,
Reading and Writing files. Constructors: Visibility modifiers, Methods and Objects,
Inbuilt classes like String, Character, String Buffer, ‘this’ reference, nested classes.
What is File I/O?
Java I/O stream is the flow of data that you can either read from, or you can write to. It is
used to perform read and write operations in file permanently. Java uses streams to perform
these tasks. Java I/O stream is also called File Handling, or File I/O. It is available in
java.io package.
Java.io package provides classes for system input and output through files, network streams,
memory buffers, etc.
Some input-output
stream will be initialized automatically by the JVM and these streams are available in
System class as
1) System.out: standard output stream
2) System.in: standard input stream
3) System.ewrr: standard error stream
Streams
Streams are the sequence of bits(data).
There are two types of streams:
• Input Streams
• Output Streams
Input Streams:
Input streams are used to read the data from various input devices like keyboard, file,
network, etc.
Output Streams:
Output streams are used to write the data to various output devices like monitor, file, network,
etc.
Streams based on data
There are two types of streams based on data:
• Byte Stream: used to read or write byte data.
Java Input
We know that taking data inputs are important parts of a computer program. Sometimes our
application will need to read input data from keyboard. Java provides classes in the packages
such as java.lang, java.io and java.util to facilitate accepting data inputs. Several techniques
are there.
1. Using Command Line Arguments
We can take keyboard input using command line arguments. In the given addition example,
we are expecting two input values.
The first input is denoted as “args[0]” and the first input is denoted as “args[1]“. Since, both
of them are String values; we need to convert them into integer values for calculating the
sum. The Double class belongs to the java.lang package; so, we don’t have to import
anything. See the code below.
CommandLine.java
public class CommandLine {
int n = args.length;
int sum;
if (n < 2) {
System.out.println("INPUT ERROR!");
System.exit(0);
}
else {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
sum = a + b;
System.out.println("SUM = " + sum);
}
}
Output:
C:\testing>java CommandLine 20 30
SUM = 50
2. Using System class
We can also accept keyboard input using the java.lang.System class. It is a very useful
technique when we don’t have support for packages like java.io or java.util. Here, we are
taking as input one character value (stored in variable in ch) at a time. Subsequently, we are
appending this character value to the string named “str“. When we press ‘@‘ symbol, the
input taking is stopped. If everything goes fine, the string value will be converted to a
decimal number and finally be displayed.
As System.in.read() method has an exception associated with it, we have declared Exception
class in the main() method signature.
Since the classes System and Double belong to the java.lang package, we don’t have to
import anything. See the program below.
SimpleInput.java
public class SimpleInput {
}
Output:
C:\testing>java SimpleInput
Enter a decimal number (press '@' to quit):
1234.75@
Number = 1234.75
}
Output:
C:\testing>java ConsoleTest
Enter two decimal numbers:
24.35
33.40
SUM = 57.75
// Creating object
Scanner sc = new Scanner(System.in);
}
Output:
C:\testing>java ScannerTest
Enter an integer:
12
Enter a word:
Delhi
Enter a boolean:
true
Enter a sentence:
Java programming is a fun!
Enter a decimal no:
23.75
Display values:
i = 12
s = Delhi
b = true
str = Java programming is a fun!
d = 23.75
NOTE: With this technique, creating a new object of Scanner is a must for inputting a
sentence. Otherwise, that input taking task will be skipped to the next one.
Console cs = System.console();
System.out.println("Enter two decimal numbers: ");
double a = Double.parseDouble(cs.readLine());
double b = Double.parseDouble(cs.readLine());
double sum = a + b;
System.out.println("SUM = " + sum);
}
}
Output:
C:\testing>java ConsoleTest
Enter two decimal numbers:
24.35
33.40
SUM = 57.75
Java Output
We know that displaying variables is an important part of a computer program. Our Java
application can display the output data to the monitor using the standard output stream named
System.out.
In Java, we mostly use the System.out.print() and System.out.println() methods to display the
output data.
With print() method, the cursor stays at the same line; while with println(), the cursor moves
to the next line.
But, using these two methods, it is really difficult to format the output data according to the
requirements of programs.
That is why we may want to use the System.out.printf() method for getting the formatted
output like what we did in C programming.
An Example
This example illustrates the difference between println() and printf() methods.
Let us suppose we have been asked to perform the summation of the following series up
to two-decimal places:
S = 1 + 1/2 + 1/3 + · · · · · · · · · · + 1/n
}
Output:
C:\testing>java Series
Enter the limit:
5
The sum is: 2.283333333333333
Observation: If we look at the output of the program, we could see that the result displayed
here is not up to two-decimal places. That means the displayed result fails to meet the
requirements of the program. We have used here println() method only.
The modified code using “printf()” method to display the result is given
below. Series_Modified.java
public class Series_Modified {
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Access Modifier within class within package outside package by subclass only
Private Y N
Default Y Y
Protected Y Y
Public Y Y
1) Private
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
The default modifier is more restrictive than protected. That is why, there is a compile-time
error.
Constructors in Java
In Java, a constructor is a block of codes
similar to the method. It is called when an
instance of the class is created. At the time of
calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to
initialize the object.
Every time an object is created using the
new() keyword, at least one constructor is
called.
Constructors in Java
It calls a default constructor if there is no
constructor available in the class. In such
case, Java compiler provides a default
constructor by default.
There are two types of constructors in Java:
no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it
constructs the values at the time of object
creation. It is not necessary to write a
constructor for a class. It is because java
compiler creates a default constructor if your
class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the
constructor.
1.Constructor name must be the same as its
class name
2.A Constructor must have no explicit return
type
3.A Java constructor cannot be abstract,
static, final, and synchronized
Types of
Constructors
In Java, constructors can be
divided into 3 types: 1. No-Arg
Constructor
2. Parameterized Constructor
3. Default Constructor
1. Java No-Arg
Constructors
Similar to methods, a Java constructor
may or may not have any parameters
(arguments).
If a constructor does not accept any
parameters, it is known as a no
argument constructor.
For example,
Constructor()
{
// body of the constructor
}
class Flower
{
String name;
Flower()
{
name = "rose";
}
}
class Main
{
public static void main(String[] args)
{
Flower obj = new Flower();
System.out.println("Flower name = " + obj.name); }
}
2. Java Parameterized
Constructor
A Java constructor can also accept one or
more parameters. Such constructors are
known as parameterized constructors
(constructor with parameters). Example
class Main
{
String languages; //
constructor accepting single
value
Main(String lang)
{
languages = lang;
3. Java Default
Constructor
If we do not create any constructor, the Java
compiler automatically create a no-arg
constructor during the execution of the
program. This constructor is called default
constructor.
Example
class Main
{
int a;
boolean b;
public static void main(String[]
args)
{
// A default constructor is called
Main obj = new Main();
System.out.println("Default
Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
3. Java Default
Constructor
Here, we haven't created any constructors. Hence, the
Java compiler automatically creates the default
constructor.
The default constructor initializes any uninitialized
instance variables with default values.
In the above program, the
variables a and b are initialized
with default
value 0 and false respectively.
3. Java Default
Constructor The above program
is equivalent to:
class Main {
int a;
boolean b;
Main() {
a = 0;
b = false;
}
public static void main(String[] args) {
// call the constructor
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
String language;
// constructor
with a single
parameter
Main(String
language) {
this.language =
language;
}
public void
getName() {
obj1.getName();
obj2.getName();
}
}
this keyword in Java
You may invoke the method of the current class by using the
this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method.
example
3) this() : to invoke current class
constructor
The this() constructor call can be used to
invoke the current class constructor. It is used
to reuse the constructor. In other words, it is
used for constructor chaining.
Calling default constructor from parameterized constructor:
Calling parameterized constructor from default constructor:
Real usage of this() constructor
call
The this() constructor call should be used to reuse the
constructor from the constructor. It maintains the
chain between the constructors i.e. it is used for
constructor chaining. example given below that
displays the actual use of this keyword.
4) this: to pass as an argument in the
method
The this keyword can also be passed as an argument in the
method. It is mainly used in the event handling. example:
Application of this that can be passed as an
argument:
In event handling (or) in a situation where we
have to provide reference of a class to another
one. It is used to reuse one object in many
methods.
5) this: to pass as argument in the
constructor call
We can pass the this keyword in the constructor also. It
is useful if we have to use one object in multiple
classes.
example:
6) this keyword can be used to return
current class instance
We can return this keyword as an statement from the
method. In such case, return type of the method must be the
class type (non-primitive). example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example of this keyword that you return as a
statement from the method
Java String
In Java, string is basically an object that represents sequence of char values. An
array of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
String.
When the intern method is invoked, if the pool already contains a String equal to this
String object as determined by the equals(Object) method, then the String from the
pool is returned. Otherwise, this String object is added to the pool and a reference to
this String object is returned.
String Interning in Java is a process where identical strings are searched in the string pool
and if they are present, the same memory is shared with other strings having the same value.
The intern() method creates an exact copy of a String that is present in the heap memory and
stores it in the String constant pool.
Takeaway - intern() method is used to store the strings that are in the heap in the string
constant pool if they are not already present.
Example of String intern() in Java
String str1 = new String("Java");
String str2 = new String("Java");
System.out.println(str1 == str2);
str3 = str1.intern();
str4 = str2.intern();
System.out.println(str3 == str4);
Output
false
true
Explanation - The strings str1 and str2 are not equal as they have different memory location
in the heap. When we apply the intern() method on str1 and store it in str3, it gets created in
the String constant pool. But when the compiler executes the statement for applying the
intern() method on str2, it checks the String constant pool first if the value is already present
or not.
Here, since the value "Java" was already present, it only returns the reference and does not
create the string again.
Whenever a new string is created, JVM first checks the string pool. In case, if it encounters
the same string, then instead of creating a new string, it returns the same instance of the found
string to the variable. If the string was not present, it creates a new string literal then allocates
memory to it.
Therefore, this method helps to save memory space.
Stringoperation6.java
1. public class Stringoperation6
2. {
3. public static void main(String ar[])
4. {
5. String s=new String("Sachin");
6. String s2=s.intern();
7. System.out.println(s2);//Sachin
8. }
9. }
Output:
Sachin
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String.
Stringoperation7.java
1. public class Stringoperation7
2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }
Output:
1010
Java String replace() Method
The String class replace() method replaces all occurrence of first sequence of
character with second sequence of character.
Stringoperation8.java
1. public class Stringoperation8
2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an
Islan d.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
" Kava"
7. System.out.println(replaceString);
8. }
9. }
Output:
Kava is a programming language. Kava is a platform. Kava is an Island. In
Java, a String is a sequence of characters represented as an instance of the
java.lang.String class.
Internally, strings are represented as an array of Unicode characters indexed
starting with 0, 1, 2, and so on, from left to right.
All the operations that we use in an array can also be performed on String objects. Strings
as array of characters
Interfaces in string
The String class implements CharSequence, Serializable,
and Comparable interfaces. Below are the details of these interfaces:
• The CharSequence interface provides charAt() used to access the char value at the
specified index.
• The Comparable interface provides the compareTo() method to compare the
objects.
• The Serializable interface is a markup interface as it does not provide any methods
or constants.
The Serializable interface simply provides information to the JVM at run-time to
enable serialization and deserialization.
Interfaces implemented by the String class
In Java, strings are immutabletheir object cannot be modified after it is initialized.
The string can be initialized at the time of object creation. Thereafter, an entirely new
string object is created in the memory whenever the’ string’ object is modified. String
literals are stored in the Java heap memory storage area known as the String Pool.
Syntax
Code
Explanation
In the first case, the string object named "Hello" is created as a literal and stored in
the String pool, which results in optimization of memory by JVMJava Virtual Machine. On
the other hand,"World" is created using the new operator with the string object. An
entirely new memory will be allocated dynamically, and this string would not be added
to the String pool.
interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings
in Java by using these three classes.
In the above
example, only one object will be created. Firstly, JVM will not find any string object
with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance. Note: String
objects are stored in a special memory area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference varia
ble
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s will
refer to the object in a heap (non-pool).
Java String Example
StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
No. Method Description
1 char charAt(int index) It returns char value for the particular index
4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)
6 String substring(int beginIndex, int It returns substring for given begin index
endIndex) and end index.
13 String replace(char old, char new) It replaces all occurrences of the specified
char value.
17 String[] split(String regex, int limit) It returns a split string matching regex and
limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.
// outer class
class OuterClass {
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
}
}
}
// Driver class
public class StaticNestedClassDemo {
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject
= new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Output:
outer_x = 10
outer_private = 30
outer_y = 20
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then,
create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new
InnerClass(); There are two special kinds of inner classes :
1. Local inner classes
2. Anonymous inner classes
• Java
// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
}
}
}
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
Output:
outer_x = 10
outer_y = 20
outer_private = 30
Comparison between normal or regular class and static nested class
S.N Normal/Regular inner class Static nested class
O
1. Without an outer class object Without an outer class object
existing, there cannot be an inner existing, there may be a static
class object. nested class object. That is, static
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
System.out.println(myInner.y + myOuter.x); }