[Go to site: main page, start]

0% found this document useful (0 votes)
9 views14 pages

Java Objects and Classes Explained

The document discusses objects and classes in Java. It defines what a class and object are, and how to define a class. It also covers topics like creating objects, accessing class members, constructors, visibility modifiers, strings, and methods of the String class.

Uploaded by

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

Java Objects and Classes Explained

The document discusses objects and classes in Java. It defines what a class and object are, and how to define a class. It also covers topics like creating objects, accessing class members, constructors, visibility modifiers, strings, and methods of the String class.

Uploaded by

Nishath Ashraf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;
[Link]();

Write a program to accept two numbers & calculating its sum using Class & Object.
class Sum
{
int a,b,ans;
DataInputStream ds=new DataInputStream([Link]);
void accept()
{
[Link](“Enter the two Numbers”);
a=[Link]([Link]());

Page | 2
b=[Link]([Link]());
}
void cal()
{
ans=a+b;
}
void display()
{
[Link](“Ans=”+ans);
}
}

public class Ex
{
public static void main(string args[])
{
Sum S=new Sum();
[Link]();
[Link]();
[Link]();
}
}

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 [Link] class.
class XYZ
{
protected void finalize() throws IOException
{
[Link](“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’.
[Link](“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=[Link]();
Here the length function returns the value seven.
[Link]([Link])//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=[Link](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 ([Link](str2))
{
[Link](“two strings are equal”);
} else
{
[Link](“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”
[Link](str2);

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

Ex: String str1=”WELcome TO java”


String str2=[Link]();

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

Ex: String str1=”WELcome TO java”


String str2=[Link]();

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=[Link](‘J’, ’K’);
This method is also replace the old string to the new string.
String str1=”JAVA”
String str2=[Link](‘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=[Link](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=[Link](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=[Link](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=[Link]();

Write a program to perform all the string


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

Page | 9
[Link]("Strin1 UPER CASE ="+[Link]());
[Link]("Strin2 LOWER CASE ="+[Link]());
[Link]("Replaceing string1 "+s1+" is="+[Link]('j','k'));
[Link]("Strings equals ignore ase="+[Link](s2));
[Link]("Second charecter of 2nd string "+s2+" is="+[Link](1));
s3=[Link]();
[Link]("String "+s2+" triming is "+s3);
[Link]("String of "+s2+"String from 2nd and ending from 5
is="+[Link](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:

[Link](): 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”);
[Link](“Append=”+[Link](s2));

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

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

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

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

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”);
[Link](“String str1=”+s1);
[Link](“String str2=”+s2);
[Link](“Append=”+[Link](s2));
[Link](“Insertd string=”+ [Link](3,s2));
[Link](“Set length of string2=”+ [Link](3));
[Link](“Character at string s2=”+ [Link](3,m));
[Link](“revers string s2=”+ [Link]());
}
}
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 [Link].*; class Ex


{
public static void main(String args[])
throws IOException
{
try
{
FileInputStream fis=new FileInputStream(“[Link]”);
int c;
While((c=[Link]())!=-1)
[Link](c);

Page | 11
[Link]();
}
Catch(FileNotFoundExecption e)
{
[Link](“File Not Found”);
}
}
}
FileInputStream

A prog. to read data from the user & writer this into a file.
import [Link].*;
public class Ex
{
public static void main(String args[])
try
{
DataInputStream ds=new DataInputStream([Link]);
[Link](“Enter the data”);
String s=[Link]();
FileInputStream f=new FileInputStream(“[Link]”);
byte b[]=[Link]()
[Link](b);
[Link]();
}
Catch(IOException e)
{
[Link](“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(“[Link]”);
int size=[Link]();
byte b[]=new byte[size];
[Link](b);
String s=new String(b);
[Link](“the file context are:”+s);
[Link]();
}
Catch(IOException e)
{
[Link](“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()
{
[Link](“X=”+x);
[Link](“Y=”+y);
}
}
public class Ex
{
public static void main(String args[])
{
Xyz obj1=new
Xyz(10,20); Xyz obj2=new
Xyz(100,200);
[Link]();
[Link]();
}
}

Page | 13
Page | 14

Common questions

Powered by AI

There are three types of constructors in Java: default constructors, parameterized constructors, and overloaded constructors. A default constructor has no parameters and is automatically created by Java if no constructors are defined. It initializes objects with default values or nulls . A parameterized constructor takes one or more parameters to initialize variables to specified values . Overloaded constructors involve multiple constructors in a class with different parameter lists, allowing for various initialization schemes based on the arguments passed to them .

Finalization in Java involves the 'finalize()' method, which is called by the garbage collector before an object is garbage collected. It is used to perform cleanup operations and free resources, such as closing file streams or releasing network sockets . This method is defined in the 'java.lang.Object' class and can be overridden to specify cleanup behavior for custom resources . Finalization is less commonly used today due to alternatives like try-with-resources, but it can still be useful in managing memory in complex applications.

Java provides a rich set of methods for string manipulation through its 'String' and 'StringBuffer' classes. The 'String' class offers methods like 'length()', 'concat()', 'equals()', 'equalsIgnoreCase()', 'toLowerCase()', 'toUpperCase()', 'replace()', 'charAt()', 'substring()', and 'trim()', which allow for comprehensive text processing (e.g., comparing strings case-insensitively with 'equalsIgnoreCase()' or replacing characters with 'replace()'). The 'StringBuffer' class further supports mutable string operations, providing methods like 'append()', 'insert()', 'setLength()', 'setCharAt()', and 'reverse()' for dynamic concatenation and manipulation . These tools make Java adept at handling complex string operations.

In Java, both 'String' and 'StringBuffer' classes provide methods for modifying character sequences. The 'String' class, which is immutable, includes methods like 'replace()', 'substring()', and 'concat()', but these return new strings instead of modifying the original object . In contrast, 'StringBuffer' allows direct modification of character sequences through methods like 'append()', 'insert()', 'setCharAt()', and 'reverse()', making it more efficient for operations requiring frequent and dynamic changes . This mutable nature of 'StringBuffer' objects avoids the overhead of creating multiple intermediate string objects, which is a limitation in the 'String' class due to its immutability.

In Java, the 'this' keyword refers to the current object within a method or constructor. It is used to distinguish between class fields and parameters that have the same name, or to call other constructors in the same class. For example, in the class 'Xyz', 'this.x = a;' is used to set the instance variable 'x' to the value of 'a', distinguishing it from the local parameter 'a' .

A Java class is defined using the syntax '<access_specifier> class <class_name><extends> <super_class><implements> <interface_list> { //data members //member functions }'. Class names should start with a capital letter. There can only be one public class per program file, which must match the filename . Classes that are not public cannot be accessed by classes in other packages. Additionally, if a class is declared private, it causes a compile-time error as it cannot be accessed by other classes, though an inner class can be private .

In Java, the 'new' operator is used to create new objects and allocate memory for them on the heap. This operator invokes the constructor of the specified class, returning a reference to the new object. The syntax for object creation using 'new' is: '<class_name> <object_name> = new <class_name>(arguments_list);'. For example, 'Sum s = new Sum();' creates an instance of the 'Sum' class .

In Java, instance variables are attributes defined in a class for which each instantiated object of the class has its own copy. They are initialized when the class is instantiated and are accessed using the object reference. Conversely, static variables are shared among all instances of a class, associated with the class itself rather than any particular object. Static variables are defined with the 'static' keyword and maintain a single copy regardless of how many objects are created . This distinction affects memory management and usage patterns, as static variables can be accessed without an instance through '<class_name>.<variable_name>' syntax.

Access specifiers in Java, such as public and private, control the visibility and accessibility of classes, methods, and variables. A public class can be accessed by any other class in any package, which is necessary for the main class of a program to be public . Conversely, a private class is not visible to the Java compiler and will cause compile-time errors if used as a standalone class; however, an inner class can be private within its enclosing class . This encapsulation is crucial for maintaining modularity and protecting data integrity.

Defining a class as private in Java is generally not allowed for top-level classes, as it causes compile-time errors because the class is invisible to the Java compiler, making it inaccessible for any other classes . However, inner classes can be declared private within their enclosing class, allowing them to be encapsulated and hidden from other classes. This promotes encapsulation and information hiding, essential in designing secure and modular applications. The main rule is that such a class can only be accessed and utilized by its enclosing class .

You might also like