JAVA Unit2
JAVA Unit2
Object Definitions:
Constructors in Java
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.
class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
class Bike{
final void run(){System.out.println("running");}
}
honda.run();
}
}
Visibility modifiers are the keywords which are used to restrict the use of class, interface, methods,
and property
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.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
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:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
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.
No Method Description
1 char charAt(int index) It returns char value for the particular index
4 boolean equals(Object another) It checks the equality of string with the given
object.
7 String replace(char old, char new) It replaces all occurrences of the specified char
value.
java provides wrapper class Character for primitive data type char.
The Character class offers a number of useful class (i.e., static) methods for manipulating
characters. You can create a Character object with the Character constructor −
Character ch = new Character('a');
The Java compiler will also create a Character object for you under some circumstances. For
example, if you pass a primitive char into a method that expects an object, the compiler
automatically converts the char to a Character for you. This feature is called autoboxing or
unboxing, if the conversion goes the other way.
// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.
public insert(int offset, It is used to insert the specified string with this string at
synchronized String s) the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public delete(int startIndex, It is used to delete the string from specified startIndex and
synchronized int endIndex) endIndex.
StringBuffer
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number
of characters.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
The File class is an abstract representation of file and directory pathname. A pathname can be
either absolute or relative.
he File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
Fields
Modifier Type Field Description
Constructors
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract pathname and a child
child) pathname string.
File(String pathname) It creates a new File instance by converting the given pathname string
into an abstract pathname.
File(String parent, String It creates a new File instance from a parent pathname string and a child
File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
Useful Methods
Modifier and Method Description
Type
boolean createNewFile() It atomically creates a new, empty file named by this abstract
pathname if and only if a file with this name does not yet exist.
boolean canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file denoted by
this abstract pathname.
boolean canRead() It tests whether the application can read the file denoted by this
abstract pathname.
boolean isDirectory() It tests whether the file denoted by this abstract pathname is a
directory.
boolean isFile() It tests whether the file denoted by this abstract pathname is a
normal file.
String getName() It returns the name of the file or directory denoted by this abstract
pathname.
String getParent() It returns the pathname string of this abstract pathname's parent,
or null if this pathname does not name a parent directory.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1
IOException at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException from the current input stream.
Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset off to
int len) the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
Method Description
int available() It is used to return the estimated number of bytes that can be read from the
input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.
int len)
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel It is used to return the unique FileChannel object associated with the file
protected void finalize() It is used to ensure that the close method is call when there is no more
reference to the file input stream.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In
this file, we are having following content:
Welcome to javatpoint.
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int It write the bytes from the specified byte-input stream into a specified
off, int len) byte array, starting with the given offset
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Method Description
int available() It returns an estimate number of bytes that can be read from the input stream
without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified byte
off, int ln) array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources associated
void reset() It repositions the stream at a position the mark method was last called on this
input stream.
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Method Description
int size() It is used to return the number of bytes written to the data output
stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.
len)
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}