KEMBAR78
JAVA Unit2 | PDF | Constructor (Object Oriented Programming) | Programming
0% found this document useful (0 votes)
29 views20 pages

JAVA Unit2

Uploaded by

Google Verse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views20 pages

JAVA Unit2

Uploaded by

Google Verse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

JAVA –Unit2 PESIAMS,Shimoga

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

What is a class in Java

o A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created.

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.

Rules for creating Java 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 Java constructors

There are two types of constructors in Java:

Default constructor (no-arg constructor): A constructor is called "Default Constructor"


when it doesn't have any parameter.

class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Darshan P R, Asst. Professor Page 1


JAVA –Unit2 PESIAMS,Shimoga

Parameterized constructor: A constructor which has a specific number of parameters is called


a parameterized constructor.

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

class student4 public static void main(String args[])


{
{
int id;
String name; student4 s1 = new student4(111,"Karan");
student4 s2 = new student4(222,"Aryan");
student4(int i,String n) s1.display();
{ s2.display();
id = i;
name = n; }
} }
void display()
{
System.out.println(id+" "+name);
}

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.

class student5 void display()


{
{
int id;
String name; System.out.println(id+" "+name+" "+age);
int age; }
student5(int i,String n) public static void main(String args[])
{ {
id = i;
name = n; Student5 s1 = new Student5(111,"Karan");
} Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
Student5(int i,String n,int a){ s2.display();
id = i;
}
name = n;
age=a; }
}

Darshan P R, Asst. Professor Page 2


JAVA –Unit2 PESIAMS,Shimoga

Java Constructor Java Method


A constructor is used to initialize the state of an A method is used to expose the behavior of an object.
object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor The method is not provided by the compiler in any
if you don't have any constructor in a class. case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.

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

Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//this program will create compile time wrror

Java final method

If you make any method as final, you cannot override it.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
Darshan P R, Asst. Professor Page 3
JAVA –Unit2 PESIAMS,Shimoga

honda.run();
}
}

Java final class

If you make any class as final, you cannot extend it.

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
} // this program will generate compile time error

Visibility modifiers are the keywords which are used to restrict the use of class, interface, methods,
and property

There are four types of Java access modifiers:

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.

Access within within outside package by outside

Darshan P R, Asst. Professor Page 4


JAVA –Unit2 PESIAMS,Shimoga

Modifier class package subclass only 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.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

No Method Description

Darshan P R, Asst. Professor Page 5


JAVA –Unit2 PESIAMS,Shimoga

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 String substring(int beginIndex) It returns substring for given begin index.

4 boolean equals(Object another) It checks the equality of string with the given
object.

5 boolean isEmpty() It checks if string is empty.

6 String concat(String str) It concatenates the specified string.

7 String replace(char old, char new) It replaces all occurrences of the specified char
value.

8 String[] split(String regex) It returns a split string matching regex.

9 int indexOf(int ch) It returns the specified char value index.

10 String toLowerCase() It returns a string in lowercase.

11 String toUpperCase() It returns a string in uppercase.

12 String trim() It removes beginning and ending spaces of this


string.

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');

Darshan P R, Asst. Professor Page 6


JAVA –Unit2 PESIAMS,Shimoga

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';

// Here primitive 'x' is boxed for method test,


// return is unboxed to char 'c'
char c = test('x');
Following table shows the Java escape sequences −

Escape Sequence Description

\t Inserts a tab in the text at this point.

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.

\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.

\' Inserts a single quote character in the text at this point.

\" Inserts a double quote character in the text at this point.

\\ Inserts a backslash character in the text at this point.

Java StringBuffer Class

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.

mportant Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

Darshan P R, Asst. Professor Page 7


JAVA –Unit2 PESIAMS,Shimoga

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

important methods of StringBuffer class


Modifier and Method Description
Type

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 replace(int It is used to replace the string from specified startIndex


synchronized startIndex, int and endIndex.
StringBuffer endIndex, String str)

public delete(int startIndex, It is used to delete the string from specified startIndex and
synchronized int endIndex) endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
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 ");

Darshan P R, Asst. Professor Page 8


JAVA –Unit2 PESIAMS,Shimoga

sb.append("Java");//now original string is changed


System.out.println(sb);//prints Hello Java
}
}

Java File Class

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

static String pathSeparator It is system-dependent path-separator character,


represented as a string for convenience.

static char pathSeparatorChar It is system-dependent path-separator character.

static String separator It is system-dependent default name-separator character,


represented as a string for convenience.

static char separatorChar It is system-dependent default name-separator character.

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

Darshan P R, Asst. Professor Page 9


JAVA –Unit2 PESIAMS,Shimoga

child) pathname string.

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 isAbsolute() It tests whether this abstract pathname is absolute.

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.

Darshan P R, Asst. Professor Page 10


JAVA –Unit2 PESIAMS,Shimoga

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:

New File is created!

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword


Darshan P R, Asst. Professor Page 11
JAVA –Unit2 PESIAMS,Shimoga

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

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.

We can perform file handling in Java by Java I/O API.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

Darshan P R, Asst. Professor Page 12


JAVA –Unit2 PESIAMS,Shimoga

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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");

Let's see the code to get input from console.

int i=System.in.read();//returns ASCII code of 1st character


System.out.println((char)i);//will print the character

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.

Useful methods of OutputStream


Method Description

1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

InputStream class

Darshan P R, Asst. Professor Page 13


JAVA –Unit2 PESIAMS,Shimoga

InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.

Useful methods of InputStream


Method Description

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.

3) public void close()throws is used to close the current input stream.


IOException

FileOutputStream class methods

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.

Darshan P R, Asst. Professor Page 14


JAVA –Unit2 PESIAMS,Shimoga

void close() It is used to closes the file output 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...

Java FileInputStream class methods

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

Darshan P R, Asst. Professor Page 15


JAVA –Unit2 PESIAMS,Shimoga

getChannel() input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

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.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

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.

Java BufferedOutputStream class methods

Darshan P R, Asst. Professor Page 16


JAVA –Unit2 PESIAMS,Shimoga

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

void flush() It flushes the buffered output stream.

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");
}
}

Java BufferedInputStream class methods

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

Darshan P R, Asst. Professor Page 17


JAVA –Unit2 PESIAMS,Shimoga

with the stream.

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);}
}
}

java DataOutputStream class methods

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)

Darshan P R, Asst. Professor Page 18


JAVA –Unit2 PESIAMS,Shimoga

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 writeChars(String s) It is used to write string to the output stream as a sequence of


characters.

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...");
}
}

Java DataInputStream class Methods

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.

Darshan P R, Asst. Professor Page 19


JAVA –Unit2 PESIAMS,Shimoga

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+"-");
}
}
}

Darshan P R, Asst. Professor Page 20

You might also like