Chapter 2 Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Chapter-2

Objects & Classes

Class: “A class is a collection both data member & member


functions” Or
“It is a collection of similar type of object”

Object: object is an instance of a class used to access the both Data member & member
functions outside the class also.

Defining a class:
Syntax:
<access_ specifier> class
<class_name><extends><super_class><implements><interface_list>
{
//data member
//member function
}

Rules for defining a class:


• The name start with a capital letter
• They can be only one public class per program
• A program can have any number of non-public classes

Note: If we declare a class as private then it is not visible to java compiler & hence we
get compile time error but inner class can be declared as private.

Ex: public class D extends A implements B


{
Int b;
Void display()
{
…………
…………
}
}

Adding methods to a class :


Syntax: retrun_type function_name(parameter_list)
{
---------
---------

Page | 1
}

Adding variable to a class :


The variable inside a class are of two types
1. Static variable or Class variable
2. Instance variable
Ex: class XYZ
{
Int a;
Static int b;
void display()
{
----------
----------
}
}
Note: In java no classes are terminated in semicolon.

Creating object:
Syntax: <class_name> <object_name>=new <class_name>(arguments_list)

An object is created by instantiating a class. The process creating an object is called as


instantiation and the created object is an instance.
The object is created by using ‘new’ operator
Ex: sum s=new sum();

Accessing Class member:


We can access the member of the class using Dot ( . ) operator.
Syntax: Obj_name.variabele_name;
Obj_name.function_name();
Ex: s.a;
s.add();

Write a program to accept two numbers & calculating its sum using Class & Object.
class Sum
{
int a,b,ans;
DataInputStream ds=new DataInputStream(System.in);
void accept()
{
System.out.println(“Enter the two Numbers”);
a=Integer.parseInt(ds.readLine());

Page | 2
b=Integer.parseInt(ds.readLine());
}
void cal()
{
ans=a+b;
}
void display()
{
System.out.println(“Ans=”+ans);
}
}

public class Ex
{
public static void main(string args[])
{
Sum S=new Sum();
S.accept();
S.cal();
S.display();
}
}

Constructors:
They are used to initialize the object, constructor having the same name as the class name
and executes automatically when the object is created.
Ex: class XYZ
{
int x;
XYZ() //constructor
{
x=10;
}
}

Types of constructor :
Constructors are three types:
1. Default constructor (Non-parameterized constructor)
2. Parameterized constructor
3. Constructor overloading

1. Default constructor:-

Page | 3
Default constructor having no parameters & Executed automatically when the object is
created.
If we doesn’t give the default constructor in the class, java automatically provides default
constructors that initializes the variables as ‘0’ or ‘NULL’. Ex: class XYZ
{
int a,b;
XYZ() //default constructor or non-parameterised constructor
{

a=10;
b=20;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ();
}
}

2. Parameterized constructor :-
The constructor having one or more parameters that is used to initialize the variable is
called parameterized constructor.
Ex: class XYZ
{

int
a,b
;
XYZ(int x, int y) //parameterised constructor
{

a=x;

b=y
;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ(10,20);
Page | 4
}
}

3. Overloaded constructor:
Two or more constructors having different parameters is called overloaded constructor.

Ex: class XYZ


{
int a,b,c;
XYZ()
{

a=1;
b=2;
c=3;
}
XYZ(int x, int y)
{
a=x;
b=y;
c=20;
}
XYZ(int x, int y, int z)
{
a=x;
b=y;
c=z;
}
}
public
class
Ex
{
public static void main(String
args[]) {
XYZ obj1=new XYZ();
XYZ obj2=new XYZ(10,20);
XYZ obj3=new XYZ(10,20,30);
}
}

Page | 5
Finalize method: we can do some cleanup operations this operation is known as
finalization. An object is garbage collected the memory will be cleanup using the finalize
method & it reuse for the further operation or memory allocations. This method is a
member of the java.lang.object class.
class XYZ
{
protected void finalize() throws IOException
{
System.out.println(“Garbage collection object”);
}
}

Visibility modifiers

Accessibility private Public Protected default


Same class Yes yes yes Yes
Same package sub class No yes yes Yes

Same package not sub No Yes No yes


class
Different package sub No Yes yes No
class

Different package not No Yes No No


sub class

Strings
A combination or collection of characters is called as string.
The strings are objects in java of the class ‘String’.
System.out.println(“Welcome to java”);
The string “welcome to java” is automatically converted into a string object by java.
A string in java is not a character array and it is not terminated with “NULL”.

String are declared and created:-

Using character strings

Page | 6
String str1=new String(“vvfgc”);
String str2=new String(str1);
String str3=”Tumkur”
We can also create string object by assigning value directly.
String object also create by using either new operator or enclosing of characters in double
codes.
Java string can be con-catenation using the plus operator (+).
String name1=”vvfgc”;
String name2=”college”;
String str1=name1+name2;
String str2=”Narasimha”+”murthy”;
String str3=name1+”murthy”;
String str4=”Narasimha”+name2;

Methods of string classes :-

1. Length:
public int length();
It will give the length of a string.

Ex: String
str=”murthy” int
n=str.length();
Here the length function returns the value seven.
System.out.prntln(str.length)//it is also returns the value 7

2. concat:
public String concat(String str);
It used to concating of two string.
Ex: String str1=”murthy”
String str2=”college”
String str3=str1.concat(str2);
‘+’ operator is also used to concatenate of two string.

3. equals:
public Boolean equals(String obj);
This method also check weather two strings are equal or not . it returns true if the two
strings are equal otherwise it returns false.

Page | 7
Ex:
String str1=”college”
String str2=”college”
if (str1.equals(str2))
{
System.out.println(“two strings are equal”);
} else
{
System.out.println(“two strings are Not equal”);
}
4. equalsIgnoreCase:- public Boolean equalsIgnoreCase(String obj);
The method ignores the case while comparing the content, It return Truewhen the two
strings character are in the different cases.

Ex: String str1=”college”


String str2=”college”
Str1.equalsIgnoreCase(str2);

5. toLowerCase:-
public String toLowerCase();
This method converts all the character to Lower case.

Ex: String str1=”WELcome TO java”


String str2=str1.toLowerCase();

6. toUpperCase:-
public String toUpperCase();
This method converts all the character to Upper case.

Ex: String str1=”WELcome TO java”


String str2=str1.toUpperCase();

7. replace:-syntax: public String repalce(char old, char new);


This method replace all the appearance of old character with a new character.

Ex: String str1=”JAVA”


String str2=str1.repalce(‘J’, ’K’);
This method is also replace the old string to the new string.
String str1=”JAVA”
String str2=str1.replace(‘JAVA’, ‘KAVA’);

Page | 8
8. charAt:-syntax: public String charAt(int index);
This method returns a single character located at the specified index position with a
string object.

Ex: String str1=”JAVA”


Char c=str1.charAt(2); //output V

9. subString:-syntax: public String substring(int begin);


This method returns a string which is derived from the main string with the mentioned
position.
This will returns the substring from the specified begin to end of the string.

Ex: String str1=”welcome to java programing”


String str2=str1.SubString(3);//output: come to java programing
Syntax2: String SubString(int begin, int end);
This will returns the specified begin to the specified end

Ex: String str1=”welcome t_o java programing”


String str2=str1.SubString(3,10);//output: come t_

10. trim:-syntax: public String trim();


This method is used to remove the beginning and ending of the wide space in a given
string.

Ex: String str1=” JAVA PROGRAMING ”


String str2=str1.trim();

Write a program to perform all the string


operation import java.lang.String; import
java.lang.*; public class lab7
{
public static void main(String args[])
{
String s1="java";
String s2="PROGRAM ing";
String s3;
System.out.println("string1 length="+s1.length());
System.out.println("string1 length="+s2.length());
System.out.println("strings Concatination="+s1.concat(s2));
if (s1.equals (s2))
System.out.println("String are equal");
else
System.out.println("String are NOT equal");

Page | 9
System.out.println("Strin1 UPER CASE ="+s1.toUpperCase());
System.out.println("Strin2 LOWER CASE ="+s2.toLowerCase());
System.out.println("Replaceing string1 "+s1+" is="+s1.replace('j','k'));
System.out.println("Strings equals ignore ase="+s1.equalsIgnoreCase(s2));
System.out.println("Second charecter of 2nd string "+s2+" is="+s2.charAt(1));
s3=s2.trim();
System.out.println("String "+s2+" triming is "+s3);
System.out.println("String of "+s2+"String from 2nd and ending from 5
is="+s2.substring(3,6));
}
}

String Buffer class


It creates string of flexible length that can be modifying in terms of both length and
content. Stringbuffer class object as the rights to access all the methods of string classes
but the object of string class has no rights to access the methods of string buffer class.

String buffer created as:


StringBuffer sb=new StringBuffer(“murthy”)

Methods of string buffer class:

1.append(): This method is used to concatenating the two strings, It is affected to


the current object.
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“college”);
System.out.println(“Append=”+s1.append(s2));

2.insert(): Insert the string s2 at the position ‘n’ of the string s1.
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“fgc”);
s1.insert(3,s2);

3.SetLength():This method is used to set the length from the string to ‘n’.
Syntax: s1.SetLength(n);
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
s1.setLngth(3);

4.SetcharAt(): This method is used to set the nth character to the given new character.
Syntax: s1.SetcharAt(n,char new);
Ex: StringBuffer s2=new StringBuffer(“java”);
s2.setcharAt(0,’k’);//kava

Page | 10
5.reverse(): This method is used to reverse the character with in an object of the
string buffer class.
Syntax: s1.reverse();
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
s1.reverse();

Write a program to perform all the string buffer


method public class Ex
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“college”);
System.out.println(“String str1=”+s1);
System.out.println(“String str2=”+s2);
System.out.println(“Append=”+s1.append(s2));
System.out.println(“Insertd string=”+ S1.insert(3,s2));
System.out.println(“Set length of string2=”+ S2.setLength(3));
System.out.println(“Character at string s2=”+ S2.SetcharAt(3,m));
System.out.println(“revers string s2=”+ s2.reverse());
}
}
Creating Files
Whenever we need to store data permanently then we use the concept of files. We can create a
file, write data into file, read data from an existing file. We can copy the contents of our file to
another file. To perform all these operation we use i/o stream.
Prog. To illustrates the use of FileInputStream

import java.io.*; class Ex


{
public static void main(String args[])
throws IOException
{
try
{
FileInputStream fis=new FileInputStream(“ster.txt”);
int c;
While((c=fis.read())!=-1)
System.out.print(c);

Page | 11
fis.close();
}
Catch(FileNotFoundExecption e)
{
System.out.println(“File Not Found”);
}
}
}
FileInputStream

A prog. to read data from the user & writer this into a file.
import jave.io.*;
public class Ex
{
public static void main(String args[])
try
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println(“Enter the data”);
String s=ds.readLine();
FileInputStream f=new FileInputStream(“xyz.txt”);
byte b[]=s.getbyte()
f.write(b);
f.close();
}
Catch(IOException e)
{
System.out.println(“Exception Occurred”);
}
}
}

A Prog. to read the data from the file &Print on screen.


public class Ex
{
public static void main(String args[])

{
try

Page | 12
{
FileInputStream f=new FileInputStream(“xyz.txt”);
int size=f.avaliable();
byte b[]=new byte[size];
f.read(b);
String s=new String(b);
System.out.println(“the file context are:”+s);
f.close();
}
Catch(IOException e)
{
System.out.print(“Exception Occurred”);
}
}
}

‘this’ Keyword
"this keyword refers to the current object”. It always points object that is currently
executing.
Ex: class Xyz
{
int x,y;
{
this.x=a;
this.y=b;
}
void display()
{
System.out.println(“X=”+x);
System.out.println(“Y=”+y);
}
}
public class Ex
{
public static void main(String args[])
{
Xyz obj1=new
Xyz(10,20); Xyz obj2=new
Xyz(100,200);
obj1.display();
obj2.display();
}
}

Page | 13
Page | 14

You might also like