U2 Class Introduction_CAG
U2 Class Introduction_CAG
OBJECT ORIENTED
PROGRAMMING CONEPTS
Prepared By:
C A Gajjar
Lecturer in IT
Dr. S & S S Ghandhy College Of Engg. & Tech., Surat
1
Introduction
Java is a true OO language and therefore the underlying structure
of all Java programs is classes.
Anything we wish to represent in Java must be encapsulated in a
class that defines the “state” and “behaviour” of the basic
program components known as objects.
Classes create objects and objects use methods to communicate
between them. They provide a convenient method for packaging
a group of logically related data items and functions that work
on them.
A class essentially serves as a template for an object and behaves
like a basic data type “int”.
It is therefore important to understand how the fields and
methods are defined in a class and how they are used to build a
Java program that incorporates the basic OO concepts such as
encapsulation, inheritance, and polymorphism.
2
Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
A Class is a 3-Compartment Box Encapsulating Data and Operations
Box
width
height
depth
volume()
4
5
Class Definition in Java
The general form for a class definition:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
Return-type methodname1(parameter-list) {
// body of method
}
Return-type methodname2(parameter-list) {
// body of method
}
// ...
Return-type methodnameN(parameter-list) {
// body of method
}
}
6
A Simple Class
Class with no methods
class Box {
double width;
double height;
double depth;
}
7
A Simple Class
Class with methods
class Box {
double width;
double height; Instance Variable
double depth;
void volume(){
//Run method implementation Instance Method
}
}
8
A Simple Class
Declaration of Instance variable:
Variables defined within a class are called
instance variables because each instance of class
contains its own copy of these variables.
Ex.Width, Height and depth
Declaration of Method:-
Methods defined with in a class are called
instance methods.
Ex. volume()
9
A Simple Class
public class Circle { // class name
double radius; // variables
String color;
double getRadius() { ...... } // methods
double getArea() { ...... }
}
10
Data Abstraction
Declare the Box class, have created a new data
type – Data Abstraction
Box aBox;
Box bBox;
11
Class of Box
aBox, bBox simply refers to a Box object, not an
object itself.
aBox bBox
null null
12
Creating objects/Instance of a class
To create an instance/object of a class, you have to:
Declare an instance identifier (instance name) of a
particular class.
Construct the instance (i.e., allocate storage for the
instance and initialize the instance) using the "new"
operator.
Objects/Instances are created dynamically using the
new keyword.
13
Creating objects/Instance of a class
aBox and bBox refer to Box objects.
14
Creating objects/Instance of a class
aBox = new Box();
bBox = new Box() ;
bBox = aBox;
15
Automatic garbage collection
The object does not have a reference and
cannot be used in future.
16
Creating objects/Instance of a class
// Declare 3 instances of the class Circle, c1, c2, and c3
c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can Declare and Construct in the same statement
17
Object creation
To create c1 object of Circle class, we can write:
Circle c1 = new Circle();
Here, new is an operator that creates the object of Circle class.
Here, left hand side is Circle is the class name and c1 is object
name. c1 is actually a variable of Circle class.
This variable stores reference number of object returned by JVM,
after creating the object.
Here, c1 is a variable and Circle is class name as well as data
type of c1.
We can say that c1 is a variable of Circle class type.
18
Object creation
When an object is created, the memory is allocated on ‘heap’.
After creation of an object, JVM produces a unique reference
number for the object from the memory address of the object.
This reference number is also classed hash code number.
To know hash code number (or reference) of an object, we can
use hashcode()method of Object class.
class Circle{
int radius;
String color;
void getRadius(){}
void getArea(){}
}
class Demo{
public static void main(String args[]){
Circle c1 = new Circle();
System.out.println("Hash code="+c1.hashCode());
}
}
19
Hash code=798154996
Memory organization for members of a class
ptr to special
ptr to Heap structure ptr to static variables
object reference Instance variable ptr to method1
Instance variable ptr to method2
special structure
code method2
heap memory static
code method1 variables
method area
20
Dot (.) Operator
The variables and methods of a class are formally
called member variables and member methods.
To reference a member variable or method, you must:
First identify the instance you are interested in, and then,
Use the dot operator (.) to reference the desired member variable
or method.
For example,
In a class Circle, with two member variables (radius and color) and
two member methods (getRadius() and getArea()).
We have created three instances of the class Circle,
namely, c1, c2 and c3.
To invoke the method getArea(), you must first identity the
instance of interest, says c2, then use the dot operator, in the form
of c2.getArea().
21
Dot (.) Operator
// Suppose that the class Circle has variables radius and color,
// and methods getArea() and getRadius().
// Declare and construct instances c1 and c2 of the class Circle
System.out.println(c1.getArea());
System.out.println(c1.getRadius());
// Reference member variables for instance c2 via dot operator
c2.radius = 5.0;
c2.color = "blue";
22
Member Variables
A member variable has a name (or identifier) and a type;
and holds a value of that particular type.
Variable Naming Convention: A variable name shall be a
noun or a noun phrase made up of several words. The first
word is in lowercase and the rest of the words are initial-
capitalized (camel-case),
e.g., fontSize, roomNumber, xMax, yMin and xTopLeft.
The formal syntax for variable definition in Java is:
[AccessControlModifier] type variableName [= initialValue];
[AccessControlModifier] type variableName-1 [= initialValue-1] [, type
variableName-2 [= initialValue-2]] ... ;
For example,
private double radius;
public int length = 1, width = 1;
23
Member Methods
A method:
1.receives arguments from the caller,
2.performs the operations defined in the method body,
and
3.returns a piece of result (or void) to the caller.
The syntax for method declaration in Java is as
follows:
[AccessControlModifier] returnType methodName
([parameterList]) { // method body or implementation ...... }
For examples:
// Return the area of this Circle instance
public double getArea() { return radius * radius * Math.PI; }
24
Member Methods
Method Naming Convention:
A method name shall be a verb, or a verb phrase
made up of several words.
The first word is in lowercase and the rest of the
words are initial-capitalized (camel-case).
For example,
getArea(), setRadius(), getParameterValues(), hasNext().
A variable name is a noun, denoting an attribute;
A method name is a verb, denoting an action.
A class name is a noun beginning with
uppercase.
25
Example
class Box{
double width;
double height;
double depth;
}
class BoxDemo{
public static void main(String[] args) {
Box mybox = new Box();
double vol;
//Assign values to mybox instance variable
mybox.width = 10;
mybox.height = 20;
mybox.width = 5;
//Compute volume of object mybox
vol = mybox.width * mybox.height * mybox.width;
System.out.println("Volume is ="+vol);
}
}
26
Adding a Method to the Box Class
// This program includes a method inside the box class.
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is =");
System.out.println(width * height * depth);
}
}
27
Adding a Method to the Box Class
class Box {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// assign different values to mybox2's instance variables
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
28
Method that Takes Parameters
//sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
//in main program method can be called to set box
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
//initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
29
Circle Class
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
30
Circle Program
public class Circle {
public double x, y;
public double r;
public double circumference() {return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
class MyMain{
public static void main(String args[]) {
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double AR = aCircle.area(); // invoking method
double Circum = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+AR);
System.out.println("Circumference ="+Circum);
}
}
31
Better way of Initialising or Access Data
Members x, y, r
When there too many items to update/access and also to
develop a readable code, generally it is done by defining
specific method for each purpose.
To initialise/Update a value:
aCircle.setX( 10 )
To access a value:
aCircle.getX()
These methods are informally called as Accessors or
Setters/Getters Methods.
32
Accessors – “Getters/Setters”
33
How does this code looks ? More
readable ?
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain{
public static void main(String args[]){
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.setX(10);
aCircle.setY(20);
aCircle.setR(5);
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.getR()+" Area="+area);
System.out.println("Radius="+aCircle.getR()+" Circumference
="+circumf);
}
}
34
Visibility Controls/Access Modifiers of JAVA
37
Visibility Controls of JAVA
Default Access Modifier – No Keyword
Default access modifier means no need to declare an access
modifier for a class, field, method etc.
A variable or method declared without any access control
modifier is available to any other class in the same
package.
The default modifier cannot be used for methods in an
interface because the methods in an interface are by default
public.
38
Visibility Controls of JAVA
Default Access Modifier – Example
class BaseClass
{ BaseClass::Display with
'default' scope
void display()
{
System.out.println("BaseClass::Display with 'default' scope");
}
}
class Main
{
public static void main(String[] args) {
//access class with default scope
BaseClass obj = new BaseClass();
39
Visibility Controls of JAVA
Public Access Modifier - public
The public keyword is an access specifier, which allows the
programmer to control the visibility of class members.
When a class member is preceded by public, then that
member may be accessed by code outside the class.
A class, method, constructor, interface etc declared public can
be accessed from any other class.
Therefore, methods or blocks declared inside a public class
can be accessed from any class belonging to the Java world.
However, if the public class we are trying to access is in a
different package, and then the public class still need to be
imported. Because of class inheritance, all public methods
and variables of a class are inherited by its subClasses.
40
Visibility Controls of JAVA
Public Access Modifier - public
Example:
public static void main(String[] args)
{
// ...
}
The main( ) method of an application needs to be public.
41
Visibility Controls of JAVA
Public Access Modifier – Example
class Test
{
public void display()
{
System.out.println("Software Testing");
}
}
class Main
{
public static void main(String[] args)
{
Test obj = new Test();
obj.display();
}
}
42
Visibility Controls of JAVA
Protected Access Modifier – Protected
Variables, methods and constructors which are declared
protected in a super class can be accessed only by the
subClasses in other package or any class within the package
of the protected members' class.
The protected access modifier cannot be applied to class and
interfaces.
Methods can be declared protected, however methods in a
interface cannot be declared protected.
Protected access gives chance to the subClass to use the
helper method or variable, while prevents a non-related class
from trying to use it.
43
Visibility Controls of JAVA
Protected Access Modifier – Protected
44
Visibility Controls of JAVA
Private Access Modifier – private
Methods, Variables and Constructors that are
declared private can only be accessed within the
declared class itself.
Private access modifier is the most restrictive
access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed
and interfaces.
The scope of private entities (methods and variables)
object of the class from any other place like the main
method.
47
Visibility Controls of JAVA
Private Access Modifier – Example
48
Visibility Controls of JAVA
Private Access Modifier – private
Example:
class A {
private String s1 = "Hello";
public String getName() {
return this.s1;}
}
Here, s1 variable of A class is private, so there's no
void findArea(){
double area;
area = length * breadth;
System.out.println("Area = "+area);
}
}
class PrivateClass{
public static void main(String args[]){
Rectangle R = new Rectangle();
R.length = 10;
R.breadth = 5;
R.findArea();
}
} 50
Private Access Specifier Example
Output:
51
this Keyword
Sometimes a method will need to refer to the object that invoked
it.
To allow this, Java defines the this keyword. Keyword this can
be used inside any method or constructor of class to refer to the
current object.
It means, this is always a reference to the object on which the
method was invoked.
this keyword can be very useful in case of Variable Hiding.
We cannot create two Instance/Local variables with same name.
But it is legal to create one instance variable & one local variable
or method parameter with same name.
Local Variable will hide the instance variable which is called
Variable Hiding.
52
this Keyword
53
this Keyword
this: to refer current class instance variable
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables
and parameters, this keyword resolves the problem of
ambiguity.
this: to invoke current class method
You may invoke the method of the current class by using the this
keyword.
this: to reuse 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.
54
this: to refer current class instance variable
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 Test{
public static void main(String[] args) {
Student s1 = new Student(11,"Ankit",5000f);
Student s2 = new Student(22,"Sameer",5500f);
s1.display();
s2.display();
111 Ankit 5000.0
}
112 Sameer 5500.0
} 55
this: to invoke current class method
class Sample{
void methodOne(){
System.out.println("Inside methodOne");
}
void methodTwo(){
System.out.println("Inside methodTwo");
this.methodOne(); //same as methodOne();
}
}
class TestThis{
public static void main(String[] args) {
Sample obj = new Sample();
obj.methodTwo();
}
}
Inside methodTwo
Inside methodOne
56
this: to reuse constructor call
class Student{
int rollno; 111 ankit java 0.0
String name, course; 112 sumit java 6000.0
float fee;
Student(int rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
Student(int rollno, String name, String course, float fee){
this(rollno, name, course); //reusing constructor
this.fee = fee;
}
void display(){
System.out.println(rollno+" "+name+" "+course+" "+fee);
}
}
class Test1{
public static void main(String[] args) {
Student s1 = new Student(11,"Ankit","Java");
Student s2 = new Student(22,"Sameer","Python",5500f);
s1.display();
s2.display();
}
} 57
Static Keyword
The static keyword in Java is used for memory
management mainly.
We can apply static keyword with variables,
methods, blocks and nested classes.
The static keyword belongs to the class than an
instance of the class.
The static can be:
Variable (also known as a class variable)
Block
Nested class
58
Static Keyword
Static Variable:-
If we declare any variable as static, it is known as a
static variable.
The static variable can be used to refer to the
memory).
59
Static Keyword
class Student{
int rollno;
String name;
static String college=“SSGC"; }
Suppose there are 500 students in my college, now all
instance data members will get memory each time when the
object is created.
All students have its unique rollno and name, so instance data
member is good in such case.
Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
Java static property is shared to all objects.
60
Static Keyword
class Student{
int rollno; 11 Karan SSGC
String name; 22 Sumit SSGC
static String college = "SSGC";
Student(int r,String n){
rollno = r;
name = n;
}
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
class Test2{
public static void main(String[] args) {
Student s1 = new Student(11,"Karan");
Student s2 = new Student(22,"Sumit");
s1.display();
s2.display();
}
}
//we can change the college of all objects by the single line of code
//Student.college=“DrSSGCSurat" 61
Static Keyword
Program of the counter without static variable:-
//Use of instance variable which get memory
//each time when we create object of a class.
class Counter{
int cnt = 0; //will get memory each time when object is created
Counter(){
cnt ++;
System.out.println("Count="+cnt);
}
}
class Test3{
public static void main(String[] args) {
//Creating objects
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
} Count=1
} Count=1
Count=1
62
Static Keyword
Program of counter by static variable
//Use of static variable which
//is shared with all the objects of a class.
class CounterTwo{
static int cnt = 0; //will get memory only once and retain value
CounterTwo(){
cnt ++;
System.out.println("Count="+cnt);
}
}
class Test3{
public static void main(String[] args) {
//Creating objects
CounterTwo c1 = new CounterTwo();
CounterTwo c2 = new CounterTwo();
CounterTwo c3 = new CounterTwo();
}
Count=1
}
Count=2
Count=3
63
Static Keyword
Static Variable Non- Static Variable
Static variables can be accessed using Non static variables can be accessed
class name. using instance of a class.
Syntax Syntax
class_name.variable_name obj_ref.variable_name
Static variables can be accessed by Non static variables cannot be
static and non static methods accessed inside a static method.
Static variables reduce the amount of Non static variables do not reduce the
memory used by a program. amount of memory used by a program
Static variables are shared among all Non static variables are specific to that
instances of a class. instance of a class.
Static variable is like a global variable Non static variable is like a local
and is available to all methods. variable and they can be accessed
through only instance of a class.
Memory is allocated at the time of Non-static variable also known as
loading of class so that these are also instance variable while because
known as class variable. memory is allocated whenever
instance is created. 64
Static Keyword
Java static method:-
If you apply static keyword with any method, it is
known as static method.
A static method belongs to the class rather than the
object of a class.
A static method can be invoked without the need for
creating an instance of a class.
A static method can access static data member and
can change the value of it.
65
Static Keyword
class Student{
int rollno;
String name;
static String college = "SSGC";
static void change(){ //static method
college = "DrSSGCSurat";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStatic{
public static void main(String[] args) {
Student.change(); //static method call: Class.Method();
Student s1 = new Student(11, "Rahul");
11 Rahul DrSSGCSurat
Student s2 = new Student(12, "Ronak");
Student s3 = new Student(22, "Rakesh"); 12 Ronak DrSSGCSurat
s1.display(); 22 Rakesh DrSSGCSurat
s2.display();
s3.display();
}
}
66
Static Keyword
class Calculate{
static int cube(int n){
return n*n*n;
}
67
Static Keyword
Static Method Non- Static Method
These method always preceded by These method never be preceded by
static keyword. static keyword
Syntax Syntax
static void fun2() void fun2()
{....} {....}
Memory is allocated only once at the Memory is allocated multiple time
time of class loading. whenever method is calling.
These are common to every object so It is specific to an object so that these
that it is also known as member are also known as instance method.
method or class method.
These property always access with These methods always access with
class reference object reference
Syntax: Syntax:
className.methodname(); Objref.methodname();
If any method wants to be execute only If any method wants to be execute
once in the program that can be multiple time that can be declare as
declare as static . non static. 69
Static Keyword
Restrictions for the static method :-
There are two main restrictions for the static
method.
The static method can not use non static data
72
Static Keyword
class Main{
static int a = 23;
static int b;
static int max;
//static blocks
static{
System.out.println("First Static Block");
b = a * 4;
}
static {
System.out.println("Second Static Block");
max = 30;
} First Static block.
//static method Second Static block.
static void display(){ a = 23
System.out.println("a = "+a); b = 92
System.out.println("b = "+b); Max = 30
System.out.println("Max = "+max);
}
public static void main(String[] args) {
display();
}
} 73
Method Overloading
If class have multiple methods with same name but different
parameters is known as Method Overloading.
Method overloading is also known as compile time (static)
polymorphism.
The same method name will be used with different number of
parameters and parameters of different type.
Overloading of methods with different return types is not allowed.
Compiler identifies which method should be called among all the
methods have same name using the type and number of arguments.
However, the two functions with the same name must differ in at
least one of the following,
The number of parameters
The data type of parameters
The order of parameter
74
Method Overloading
75
Constructors
Constructor is a special method that gets invoked
“automatically” at the time of object creation.
Constructor is normally used for initializing
objects with default values unless different
values are supplied.
Constructor has the same name as the class
name.
Constructor cannot return values.
A class can have more than one constructor as
long as they have different signature (i.e.,
different input arguments syntax).
76
Constructors
A constructor is different from an ordinary method
in the following aspects:
The name of the constructor method is the same as the
class name.
Constructor has no return type. It implicitly
returns void. No return statement is allowed inside the
constructor's body.
Constructor can only be invoked via the "new"
operator. It can only be used once to initialize the
instance constructed. Once an instance is constructed,
you cannot call the constructor anymore.
Constructors are not inherited
77
Constructors
Types of Constructors:
Default Constructor
Parameterized Constructor
Copy Constructor
Private Constructor
78
Constructors
Default Constructor:
A constructor with no parameter is called the default
constructor.
It initializes the member variables to their default
value.
For example,
Circle() constructor initialize member
variables radius and color to their default value.
79
Defining a Constructor
Like any other method
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data
Fields
}
Invoking:
There is NO explicit invocation statement needed:
When the object creation statement is executed, the
constructor method will be executed automatically.
80
Defining a Constructor: Example
81
82
83
Parameterized Constructors
A constructor that has parameters is known as
parameterized constructor.
It is used to provide different values to the
distinct objects.
It is required to pass parameters on creation of
objects.
If we define only parameterized constructors,
then we cannot create an object with default
constructor.
This is because compiler will not create default
constructor. You need to create default
constructor explicitly.
90
111 Karan 222 Aryan
Parameterized Constructors
111 Karan
222 Aryan
91
111 Karan 222 Aryan
Parameterized Constructors
92
Parameterized Constructors
93
Parameterized Constructors
94
111 Karan 222 Aryan
Copy Constructors
A copy constructor is a constructor that takes only
one parameter which is the same type as the class in
which the copy constructor is defined.
A copy constructor is used to create another object
that is a copy of the object that it takes as a
parameter. But, the newly created copy is totally
independent of the original object.
It is independent in the sense that the copy is located
at different address in memory than the original.
96
111 Karan 222 Aryan
Copy Constructors
10xyz
20abc
10xyz
97
111 Karan 222 Aryan
Copy Constructors
Advantages of copy constructor:
The Copy constructor is easier to use when
our class contains a complex object with
several parameters.
Whenever we want to add any field to our
class, then we can do so just by changing the
input to the constructor.
One of the most crucial importance of copy
constructors is that there is no need for any
typecasting.
98
111 Karan 222 Aryan
Private Constructors
Java allows us to declare a constructor as
private.
We can declare a constructor private by using
the private access specifier.
Note that if a constructor is declared private,
we are not able to create an object of the class.
we can use this private constructor in
Singleton Design Pattern.
i.e. a class must ensure that only single instance
should be created and single object can be used
by all other classes.
99
111 Karan 222 Aryan
10
2
111 Karan 222 Aryan
Private Constructors
10
3
111 Karan 222 Aryan
Constructor Overloading
Constructor overloading in java allows to
more than one constructor inside one Class.
It is not much different than method
overloading.
In Constructor overloading you have multiple
constructors with different signature with
only difference that constructor doesn't have
return type.
These types of constructor known as
overloaded constructor.
105
111 Karan 222 Aryan
Constructor Overloading
/* programe defines three constructors to initialize the dimensions of a
box various ways using constructor overloading. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Box() { // constructor used when no dimensions specified
width = -1; // use -1 to indicate
height= -1; // an uninitialized
depth = -1; // box
}
Box(double len) { // constructor used when cube is created
width = height = depth = len;
}
double volume() { // compute and return volume
return width * height * depth;
}
}
106
111 Karan 222 Aryan
Constructor Overloading
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0 107
111 Karan 222 Aryan
Constructor Overloading
108
111 Karan 222 Aryan
Constructor Overloading
109
String Class:-
111 Karan 222 Aryan
110
String Class:-
111 Karan 222 Aryan
Creating a String:-
String literal :-
111
String Class:-
111 Karan 222 Aryan
Creating a String:-
Using new keyword :-
112
Methods/Operations of String Class
Method Description
length () Returns the length of this string.
toUpperCase() Converts all of the characters in this String to upper
case.
toLowerCase() Converts all of the characters in this String to lower
case.
substring(): extracts a substring from the string and returns it.
113
String Class:-
111 Karan 222 Aryan
114
String Class:-
111 Karan 222 Aryan
115
String Class:-
111 Karan 222 Aryan
116
String Class:-
111 Karan 222 Aryan
117
String Class:-
111 Karan 222 Aryan
118
String Class:-
111 Karan 222 Aryan
119
String Class:-
111 Karan 222 Aryan
120
String Class:-
111 Karan 222 Aryan
121
String Class:-
111 Karan 222 Aryan
123
String Class:-
111 Karan 222 Aryan
By Using == operator
The == operator compares references not values.
124
String Class:-
111 Karan 222 Aryan
125
String Class:-
111 Karan 222 Aryan
class StringCompare{
public static void main(String[] args) {
String s1 = "Rohan";
String s2 = "Rohan";
String s3 = "Sohan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //-1
System.out.println(s3.compareTo(s1)); //1
}
}
126
String Class:-
111 Karan 222 Aryan
128
String Class:-
111 Karan 222 Aryan
129
String Class:-
111 Karan 222 Aryan
130
StringBuffer Class:-
111 Karan 222 Aryan
131
StringBuffer Class:-
111 Karan 222 Aryan
Constructor Description
StringBuffer() This constructs a string buffer with no
characters in it and an initial capacity of 16
characters.
132
StringBuffer Class:-
111 Karan 222 Aryan
133
StringBuffer Class:-
111 Karan 222 Aryan
Output: test123
135
StringBuffer Class:-
111 Karan 222 Aryan
Output: te123st
136
StringBuffer Class:-
111 Karan 222 Aryan
Output: olleH
137
StringBuffer Class:-
111 Karan 222 Aryan
138
StringBuffer Class:-
111 Karan 222 Aryan
Output: 16
139
String v/s StringBuffer Class:-
111 Karan 222 Aryan
String StringBuffer
It is immutable means you cannot It is mutable means you can
modify. modify.
String class is slower than the StringBuffer class is faster than the
StringBuffer. String.
String is not safe for use by multiple String buffers are safe for use by
threads. multiple threads.
140
StringJoiner Class:-
111 Karan 222 Aryan
141
StringJoiner Class:-
111 Karan 222 Aryan
Method Description
142
StringJoiner Class:-
111 Karan 222 Aryan
143
StringJoiner Class:-
111 Karan 222 Aryan
144
Wrapper Class:-
111 Karan 222 Aryan
146
Wrapper Class:-
111 Karan 222 Aryan
Example:
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer
class.
The it1 object can be used wherever k is required an object.
To unwrap (getting back int from Integer object) the object it1.
Example:
int m = it1.intValue();
System.out.println(m*m); // prints 10000
intValue() is a method of Integer class that returns an int data
type.
147
Wrapper Class:-
111 Karan 222 Aryan
148
Wrapper Class:-
111 Karan 222 Aryan
149
Wrapper Class:-
111 Karan 222 Aryan
150