0% found this document useful (0 votes)
23 views

JAVA - Module 2

Uploaded by

raniyadav123789
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

JAVA - Module 2

Uploaded by

raniyadav123789
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 127

OBJECT ORIENTED PROGRAMMING

USING JAVA
Course Code : 22EEE341

MODULE II
Objects, Classes and Constructors
Contents
• Working with Objects
• Implementing Classes
• Object Construction
• Static Variables and Methods
• Constructors
• Overloading
• Visibility modifiers
• Methods and objects
• Inbuilt classes like String
• Character
• String Buffer
• this reference
• nested classes
Class Fundamentals
• In object-oriented programming technique, a program is designed using
objects and classes.
• A class
• Core of OOP and java
• Defines shape and nature of an object
• Defines a new datatype, once defined it can be used to create objects of that type.
• Thus class is template, an object is an instance of a class.
• A class in Java is a logical entity only.
• An object
• In Java is the physical as well as a logical entity.
Class Fundamentals
Class Fundamentals
• Any concept you wish to implement in a Java program must be encapsulated
within a class.
• Methods that determine how a class’ data can be used
• Simple programs done so far was to encapsulate the main method.
Class in Java
• A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Class Fundamentals
Object in Java
• An entity that has state and behavior
is known as an object.

• Eg:- tangible objects :chair, bike, marker,


pen, table, car, etc.
• Eg:- intangible : banking system, music,
apps.
Object in Java
• An object has three characteristics:
• State: represents the data (value) of an object.

• Behavior: represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

• Identity: An object identity is a unique ID, which is not visible to the external user. It is
used internally by the JVM to identify each object uniquely.

• For Example, Pen is an object. Its name is Reynolds; color is white, It is used to write.
• State:- name and color
• Behavior:- writing
Class and Object
• A class is a group of
objects which have
common properties.
• It is a user defined
template or blueprint
from which objects
are created.
• Class is a logical
entity. It can't be
physical.
General Form of a Class
• To define a class
• Specify data it contains and
• Code that operates on that data
• defines interface to its data
• determines how class’ data can be used
• A class is declared by use of the class keyword.
• Syntax to declare a class:
class <class_name>{
field;
method;
}
General Form of a Class
• A simplified general form of a class definition is
class classname {
type instance-variable1;
type instance-variable2;

// ... type instance-variableN;

type methodname1(parameter-list) {
// body of method
}

type methodname2 (parameter-list) {


// body of method
}

// ... type methodnameN(parameter-list) {


// body of method
}
}
Object construction: using new keyword in Java

• The new keyword is used to allocate memory at runtime.


• All objects get memory in Heap memory area.

Reference Variable
Object and Class Example: main within the class
//Defining a Student class.
class Student{
int id; //defining field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through
System.out.println(s1.name);
reference variable
}
}
OUTPUT??
0
null
Object construction: using new keyword in Java

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}
Output:5
NHCE, EEE
Multiple Objects
You can create multiple objects of one class:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x); //you can access the attributes(variables)by creating
an object of a class and by using dot syntax(.)
}
}
Output: 5
5

NHCE, EEE
Modify Attributes
You can also modify attribute values:

public class Main {


int x;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}
}

NHCE, EEE
Override existing values:
public class Main {
int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}
NHCE, EEE
If you don't want the ability to override existing values, declare the
attribute as final:

public class Main {


final int x = 10;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}
NHCE, EEE
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
}
NHCE, EEE
Object construction: using Anonymous object
• An object which has no reference is known as an anonymous object.
• It can be used at the time of object creation only.
• Anonymous object in Java
• We can use a method on an object without assigning it to any reference.
• an anonymous object is a good approach, if you have to use an object
only once.
new Calculation(); //anonymous object
• Calling method through an anonymous object
new Calculation().fact(5);
Full example of an anonymous object in Java.
class Calculation {
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
Full example of an anonymous object in Java.
public class Tester {
public String message(){
return "Hello World!";
}
public static void main(String[] args) {
System.out.println(new Tester().message());
}
}
Object and Class Example: main outside the class
//Java Program to demonstrate having the main method in another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Creating multiple objects by one type only
• Create multiple objects by one type only, same as we do in case of
primitives.
• Initialization of primitive variables:
• int a=10, b=20;
• Initialization of reference variables:
• Rectangle r1=new Rectangle(), r2=new Rectangle(); //creating two objects
Methods
• Methods can be used to define reusable code and organize and
simplify coding.
• Methods define the interface to most classes.
• This allows the class implementer to hide the specific layout of
internal data structures.
• Methods are defined to
• provide access to data
• be used internally by the class itself.
Methods
• A method definition consists of its method name, parameters, return
value type, and body.
• General form of a method:
type name(parameter-list) {
// body of method
}
• Parameter and argument
• Parameters are variables that receive value of arguments passed to the
method when it is called.
• return value;
Defining a Method
Calling a method
Calling a method executes the code in the method.

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}

// Outputs "I just got executed!"


NHCE, EEE
A method can also be called multiple times:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
Output:
}
I just got executed!
public static void main(String[] args) { I just got executed!
myMethod(); I just got executed!
myMethod();
myMethod();
}
}

NHCE, EEE
JAVA METHOD PARAMETERS: Argument vs
Parameter
public class Example {
public static int multiply(int a, int b) //a,b are the parameters
{
return a * b;
}
public static void main(String[] args)
{
int x = 2;
int y = 5;
// the variables x and y are arguments
int product = multiply(x, y);
System.out.println("PRODUCT IS: " + product);
}
}

NHCE, EEE
NHCE, EEE
Methods
• Method without returning value
• Method with return value
• type of data returned by a method must be compatible with the return type
• variable receiving the value returned by a method must also be compatible
with the return type
• Method that takes parameters
• Parameters allow a method to be generalized.
• can operate on a variety of data and/or be used in a number of slightly
different situations.
Return Values
• The void keyword, indicates that the method should not return a
value.
• If you want the method to return a value, you can use a primitive
data type (such as int, char, etc.) instead of void, and use the return
keyword inside the method:

NHCE, EEE
Example for Return
public class Main {
static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

NHCE, EEE
This example returns the sum of a method's two parameters:

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
NHCE, EEE
3 Ways to initialize object

Initializing an object means storing data into the


object
There are 3 ways to initialize object in Java.
• By reference variable
• By method
• By constructor
1) Initialization through reference variable
class Student{
int id;
String name;
}

class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//
printing members with a white space
}
}
1) Initialization through reference variable
• Each time you create an instance of a class, you are creating an object that contains
its own copy of each instance variable defined by the class.
• Thus, every Student object will contain its own copies of the instance variables id,
name.
• These variables can be accessed using the dot (.) operator.
• The dot operator links the name of the object with the name of an instance variable.
s1.id=101;
• The compiler assign the copy of id that is contained within the s1 object the value,
101.
• The dot operator is used to access both the instance variables and the methods
within an object.
2) Initialization through method

s1.id=101;
s1.name="Sonoo";
• The above code works, it is troubling for two reasons.
• clumsy and error prone.
• in well-designed Java programs, instance variables should be accessed only
through methods defined by their class.
2) Initialization through method

• Create two objects of Student class


• Initializing value to objects by invoking
• insertRecord() method
• Displaying the state (data) of objects by invoking
• displayInformation() method.
2) Initialization through method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
2) Initialization through method

•Object gets the memory in heap memory area.


•The reference variable refers to the object allocated in the heap memory
area.
•Here, s1 and s2 both are reference variables that refer to the objects
allocated in memory.
Initialization through method: Example
Employee
class Employee{
int id; public class TestEmployee {
public static void main(String[] args) {
String name;
Employee e1=new Employee();
float salary;
Employee e2=new Employee();
void insert(int i, String n, float s) { Employee e3=new Employee();
id=i; e1.insert(101,"ajeet",45000);
name=n; e2.insert(102,"irfan",25000);
salary=s; e3.insert(103,"nakul",55000);
} e1.display();
void display(){ e2.display();
System.out.println(id+" "+name+" "+salary);} e3.display();
}
} }
Initialization through method : Example Rectangle
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
What is constructor?
• Constructor are like methods, but having the same name as that of
its class.
• Constructors are a special kind of method. They have three
peculiarities:
■ A constructor must have the same name as the class itself.
■ Constructors do not have a return type—not even void.
■ Constructors are invoked using the new operator when an object is created.
• Constructors play the role of initializing objects.
• a constructor also contains collection of statements(i.e.
instructions) that are executed at time of Object creation.
• Thus constructor is a method having same name as the class in which
it resides and is syntactically similar to a method.
Constructor
Why Constructors??
• Consider a class Box, with 3 variables and its object is created.

• Can there be a box with no value defined for its dimensions. The
answer is no.

• Constructors are used to assign values to the variables in a class at


the time of object creation
• Either explicitly done by the programmer

• or by Java compiler itself (default constructor).


Why Constructors??
• Tedious to initialize all of the variables in a class each time an
instance is created.

• Thus automatic initialization done with use of a constructor.

• A constructor initializes an object immediately upon creation.


When Constructors are invoked??
• Every time an object is created using the new() keyword, at least one
constructor is called.
• Java compiler provides a default constructor by default, if no constructor
available in the class.
• The constructor is automatically called immediately after the object is created,
before the new operator completes.
• Constructors have no return type, not even void.
• This is because the implicit return type of a class’ constructor is the class type
itself.
Constructors
Rules for creating Java constructor
• Constructor name must be the same as its class name
• A constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final, and synchronized
• Access modifiers can be used while declaring a constructor.

• Types of Java constructors


• Default constructor (no-arg constructor)
• Parameterized constructor
Default constructor in Java
• Java compiler automatically creates a default constructor (Constructor with no
arguments) in case no constructor is present in the java class.
• Following are the motive behind a default constructor.
• Create the Object
• Call the super class constructor() -> only when we have inheritance
• Initialize all the instance variables of the class object.
public class Tester {
int a;
String b;
public static void main(String[] args) {
//Default constructor is called to create a new object
Tester t = new Tester();
//print the default values
System.out.println(t.a);
System.out.println(t.b);
}}
Constructors without Parameters
• Example of default constructor

A constructor without any parameters. class Bike1{

//creating a default constructor

Syntax of default constructor: Bike1(){


System.out.println("Bike is created");
class_name(){} }

//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Parameterized Constructors
• To construct objects of various dimensions.

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


int id;
//creating objects and passing values
String name;
//creating a parameterized constructor Student4 s1 = new Student4(111,"Karan");
Student4(int i,String n){ Student4 s2 = new Student4(222,"Aryan");
id = i;
name = n; //
} calling method to display the values of object
//method to display the values
s1.display();
void display(){
System.out.println(id+" "+name); s2.display();
} }
Difference between constructor and method in Java
Java Constructor Java Method
• used to initialize the state of an object. •used to expose the behavior of an object.

• must not have a return type. •must have a return type.


• invoked implicitly. •invoked explicitly.
• The Java provides a default constructor if
•is not provided by the compiler in any case.
you don't have any constructor in a class.

• The constructor name must be same as the •Can have any other name than keyword
class name.
•Can be invoked any no: of times
• Is invoked when ever object is created
Method Overloading
• Class having multiple methods having same name but different in
parameters, it is known as Method Overloading.
• Increases the readability of the program
• can perform only one operation, with same name of the methods
• Different ways to overload the method
• By changing number of arguments
• By changing the data type
• By changing the sequence of arguments with different data type
• In java, Method Overloading is not possible by changing the return type of
the method only- to avoid ambiguity
Method Overloading
public class Addition{
// Overloaded sum(). This sum takes two int parameters
// Driver code
public int sum(int x, int y) { return (x + y); }
public static void main(String args[])
{
// Overloaded sum(). This sum takes three int parameters
Addition s = new Addition();
public int sum(int x, int y, int z)
System.out.println(s.sum(10, 20));
{
System.out.println(s.sum(10, 20, 30));
return (x + y + z);
System.out.println(s.sum(10.5, 20.5));
}
}
}
// Overloaded sum(). This sum takes two double parameters

public double sum(double x, double y)


{
return (x + y);
}
Constructor Overloading
• The constructor overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task.

• For initializing an object in different ways

• Box mybox1 = new Box(10, 20, 15);

• Box mybox2 = new Box();

• Box mycube = new Box(7);


Constructor Overloading
• java compiler invokes a default constructor when we do not
use(defined) any constructor in the class.
• However, the default constructor is not invoked if we have used any
constructor in the class, whether it is default or parameterized.
• In this case, the java compiler throws an exception saying the
constructor is undefined.
Constructor Overloading – Error:2
class Box6 {
double width; double height; double depth;
// This is the constructor for Box.
Box6(double w, double h, double d) {
C:\NHCE\COURSES\JAVA\javapgms>javac
width = w;
Box6.java
height = h;
Box6.java:15: error: constructor Box6 in class Box6
depth = d;
cannot be applied to given types;
}
Box6 ob1= new Box6();
// compute and return volume ^
double volume() { required: double,double,double
return width * height * depth; found: no arguments
} reason: actual and formal argument lists differ in
public static void main(String args[]) { length
Box6 ob1= new Box6(); 1 error
System.out.println("volume: "+ob1.volume());
}
}
Constructor Overloading
// Java program to illustrate // Driver code
// Constructor Overloading public class Test {
class Box { public static void main(String args[])
double width, height, depth; {
// constructor used when all dimensions specified
Box(double w, double h, double d)
// create boxes using the various constructors
{ Box mybox1 = new Box(10, 20, 15);
width = w; Box mybox2 = new Box();
height = h; Box mycube = new Box(7);
depth = d;
} double vol;
// constructor used when no dimensions specified
Box() { width = height = depth = 0; } // get volume of first box
vol = mybox1.volume();
// constructor used when cube is created System.out.println("Volume of mybox1 is " + vol);
Box(double len) { width = height = depth = len; }
// get volume of second box
// compute and return volume
vol = mybox2.volume();
double volume() { return width * height * depth; }
} System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Important points on Constructor
Overloading :
• Constructor calling must be the first statement of constructor in Java.
• If we have defined any parameterized constructor, then compiler will
not create default constructor.
• and vice versa if we don’t define any constructor, the compiler
creates the default constructor(also known as no-arg constructor) by
default during compilation
• Recursive constructor calling is invalid in java.
Static Variables
• Declared with static keyword, outside method but inside class.

• All the static variables are allocated and initialized only once at the
start of the program.

• Is independent of object of that class, only one instance is created


which is shared by every object of the class.

• So memory consumption is very less.

• Eg: variables that are common to all objects can be made static, like

• Interest rate in banking operations of specific type of accounts


Static Variables
• e.g: static int x;
int y;
• are declared in a class and 10 objects are created.
• 10 instances of y will be created in the 10 objects i.e 40 bytes of memory.
• This 40 byte memory is allocated from stack segment.
• And only 1 instance of x is created i.e 4 bytes of memory, which is shared
by the 10 objects.
• So each object can modify it and the modified value will be reflected for
other objects too.
• This 4 byte memory is allocated from data segment.
Static Variables
• When a member is declared static,
• it can be accessed before any objects of its class are created, and without
reference to any object.

• You can declare both methods and variables to be static.

• The most common example of a static member is main( ).

• main( ) is declared as static because it must be called before any objects


exist.
• Static variables and methods belong to a class and are called with the Class
Name rather than using object variables, like ClassName.methodName();

• There is only one copy of a static variable or method for the whole class.
For example, the main method is static because there should only be 1
main method.

• Static methods can be public or private.

• Static methods only have access to other static variables and static
methods.

NHCE, EEE
Non-Static Variables
• Local Variables: A variable defined within a block or method or
constructor is called local variable.
• These variables are created when the block in entered or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
• The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access this variable only within that
block.
• Initialisation of Local Variable is Mandatory.
Non-Static Variables
• Instance Variables: declared in a class outside any method, constructor or
block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier then the default access specifier will be used.
• Initialisation of Instance Variable is not Mandatory. Its default value is 0

• Instance Variable can be accessed only by creating objects.


Static variables and methods in Java

NHCE, EEE
Static variables and methods in Java

NHCE, EEE
Static variable example in Java
class VariableDemo {
static int count=0;
public void increment() { Ob1 Ob2
count++;
}
public static void main(String args[]) {
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment(); Count=0
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Static Variable can be accessed directly in a static
method
class JavaExample{
static int age;
static String name;

static void disp() { //This is a Static Method


System.out.println("Age is: "+age);
System.out.println("Name is: "+name);
}
public static void main(String args[]) { // This is also a static method
age = 30;
name = "Steve";
disp();
}
}
Static Variables Initialization
// Demonstrate static variables, methods, and blocks. To assigning values for static variables
• Directly assigning
class UseStatic {
• Through static method
static int a = 3; // direct initialization • Through static block.
static int b; // default value
static float y;

static { // thru static block


static void math(int x ,float y) { System.out.println("Static block initialized.");
System.out.println("x = " + x); b = a * 4;
}
System.out.println("y = " + y);
public static void main(String args[]) {
System.out.println("a = " + a); math(42,50); // thru method
System.out.println("b = " + b); }
}
}
Static Variables Initialization
• As soon as the UseStatic class is loaded, all of the static statements are run.

1.a is set to 3

2.Then the static block executes, which prints a message and then initializes b
to a * 4 or 12.

3.Then main( ) is called, which calls meth( ), passing 42 to x, 50.0 stored in y.

4.The three println( ) statements refer to the two static variables a and b, as
well as to the local variable x.
Static Methods
Methods declared as static have several restrictions:
• They can only call other static methods.

• They must only access static data.

• They cannot refer to this or super in any way.


Static variable and method - Access outside a class
• Static methods and variables can be used independently of any object.

• Only specify the name of their class followed by the dot operator.

classname.method( )

• Here, classname is the name of the class in which the static method is
declared.

• This is how Java implements a controlled version of global methods and


global variables.
Static variable and method - Access outside a class
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
output is : a = 42 b = 99
Non-Static Variables
Static variable Non static variable

Static variables can be accessed using class name Non static variables can be accessed using instance of a class

Static variables can be accessed by static and non static methods Non static variables cannot be accessed inside a static method.

Static variables reduce the amount of memory used by a Non static variables do not reduce the amount of memory used
program. by a program

In Static variable Memory is allocated only once, at the time of In non Static variable Memory is allocated each time an instance
class loading. of the class is created.

Non Static variables Can be accessed only within the class or its
Static variables Can be accessed from any part of the program.
instance.

Static variables Exists for the entire lifetime of the program. Non Static variables Exists for the lifetime of the object.

Static variables Default value is assigned automatically. Non Static variables Default value is not assigned automatically.

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class.

Static variable is like a global variable and is available to all Non static variable is like a local variable and they can be
methods. accessed through only instance of a class.
Visibility modifiers- Introduction to access
control
• Encapsulation links data with the code that manipulates it –
thru Class and object
• Encapsulation provides another important attribute:
access control.
• Through encapsulation, you can control
• what parts of a program can access the members of a class.
• Thus can prevent misuse.
• Eg: restricting data access only through a set of methods.
• Thus class creates a “black box”
Access Modifiers in Java
• Access modifiers in Java helps to restrict the scope of
• a class, constructor , variable , method or data member.

• There are four types of access modifiers available in java:

• Default – No keyword required

• Private

• Protected

• Public
Access Modifiers in Java
Access Modifiers in Java

• Public:
• specified using the keyword public.

• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods or data members which are declared as public
are accessible from every where in the program.
• There is no restriction on the scope of a public data members.
Visibility modifiers
public access modifier

• Member of a class is modified by the public specifier- can be accessed by


any other code.

• main( ) has always been preceded by the public specifier.

• It is called by code that is outside the program—that is, by the java run-
time system.

• When no access specifier is used, then by default the member of a class is


public within its own package, but cannot be accessed outside of its
package.
Access Modifiers in Java

• Default:
• When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default.
• Having default access modifier are accessible only within the same package
Access Modifiers in Java
//error while using class from different package
package p1;
// with default modifier
// Class Geek is having Default access modifier
package p2;
class Geek
import p1.*;
{ // This class is having default access modifier
class GeekNew
void display()
{
{ public static void main(String args[])
{
System.out.println("Hello World!");
// Accessing class Geek from package p1
} Geek obj = new Geek();
obj.display();
}
}
}
Access Modifiers in Java
• Private: package p1;

• specified using the class A


{
keyword private private void display()
{
• The methods or data members System.out.println("GeeksforGeeks");
}
declared as private are accessible }
only within the class in which they
class B
are declared. {
public static void main(String args[])
• Any other class of same package {
A obj = new A();
will not be able to access these // Trying to access private method of another class
members. obj.display();
}
}
Access Modifiers in Java: Protected

• Protected:
• specified using the keyword protected.

• The methods or data members declared as protected are accessible within


same package or sub classes in different package.
Protected
package p2;
package p1;
import p1.*; // importing all classes in package p1
// Class A
// Class B is subclass of A
public class A
class B extends A
{
{
protected void display()
public static void main(String args[])
{
{
System.out.println("GeeksforGeeks");
B obj = new B();
}
obj.display();
}
}

}
The this Keyword
• In Java, this is a reference variable that refers to the current object on
which the method or constructor is being invoked.
• It can be used to access instance variables and methods of the
current object.
The this Keyword
• Using the ‘this’ keyword to refer to current class instance variables.
• Using this() to invoke the current class constructor
• Using ‘this’ keyword to return the current class instance
• Using ‘this’ keyword as the method parameter
• Using ‘this’ keyword to invoke the current class method
• Using ‘this’ keyword as an argument in the constructor call
• to differentiate between the local and instance variables
Using ‘this’ keyword to refer current class instance variables.
Local Variable has same name as Instance Variable

void display()
class Test
{
{
//Displaying value of variables a and b
int a;
System.out.println("a = " + a + " b = " + b);
int b;
}
// Parameterized constructor
public static void main(String[] args)
Test(int a, int b)
{
{
Test object = new Test(10, 20);
this.a = a;
object.display();
this.b = b;
}
}
}
Using this() to invoke current class constructor
[default constructor calling parameterized constructor]

//Parameterized constructor
class Test Test(int a, int b)
{ {
int a; this.a = a;
int b; this.b = b;
Test() //Default constructor System.out.println("Inside parameterized constructor");
{ }
this(10, 20); public static void main(String[] args)
System.out.println("Inside default {
constructor \n"); Test object = new Test();
} }
}
Using ‘this’ keyword to invoke the current class method
class Test {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display function");
}
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
Ways to use ‘this’ keyword in java
Using this() to invoke current class constructor[parameterized constructor calling default constructor]

// constructor used when only boxNo specified


class Box
Box(int num)
{
{
double width, height, depth;
/* this() is used for calling the default
int boxNo;
// constructor used when all dimensions and boxNo specified
constructor from parameterized constructor*/
Box(double w, double h, double d, int num) this();
{
width = w; boxNo = num;
height = h; }
depth = d;
boxNo = num; public static void main(String[] args)
} {
// constructor used when no dimensions specified // create box using only boxNo
Box() Box box1 = new Box(1);
{
// an empty box // getting initial width of box1
width = height = depth = 0; System.out.println(box1.width);
} }
}
Inbuilt classes- String, Character
StringBuffer
Java provides StringBuffer, String, Character classes along with java.lang
package.

• String class is used to manipulate character strings that cannot be changed.


• Objects of type String are read only and immutable.

• StringBuffer class is used to represent characters that can be modified.

• Character class generally wraps the value of all the primitive type char into an
object.
• Any object of the type Character may contain a single field whose type is
char.
Java String
• String is a sequence of characters,
• for e.g. “Hello” is a string of 5 characters.

• In java, string is an immutable object


• which means it is constant and can cannot be changed once it has been created.

• String is probably the most commonly used class in Java’s class library.

• Every string you create is actually an object of type String.

• Even string constants are actually String objects.


Java String
• 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',‘l',‘e',‘a',‘r','n',‘e‘, ‘r’};

String s=new String(ch);

• is same as:
String s="javatlearner";
Java String
Two Important points about string

1.Every string you create is actually an object of type String.


• string constants are actually String objects.

• Eg: System.out.println("This is a String, too");

“This is a String, too” is a string constant

2. In java, objects of type String are immutable


• which means it is constant and once a String object is created, its contents
cannot be altered.
Creating a String
There are two ways to create a String in Java
• String literal
• Using new keyword
String literal
• Java String literal is created by using double quotes, assigning a String literal
to a String instance.
String str1 = "Welcome";
String str2 = "Welcome";
• Not yet created any string object using new keyword in the above example.
• The compiler creates a String object with its value in this case, "Welcome“
• Note: String objects are stored in a special memory area known as the
"string constant pool".
Creating a String
• Each time you create a string literal, JVM checks the "string constant pool"
first.
• If the string already exists in the pool, a reference to the pooled instance is
returned.
• If the string doesn't exist in the pool, a new string instance is created and
placed in the pool.
• For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Creating a String-Using String literal
Creating a String-Using String literal

• Why Java uses the concept of String literal?


• To make Java more memory efficient
• (because no new objects are created if it exists already
in the string constant pool).
Creating a String-By new keyword
• String s="welcome"; // using literal

• String s=new String("Welcome");


• //creates two objects and one reference variable

• JVM will create


• a new string object in normal (non-pool) heap memory, and
• the literal "Welcome" will be placed in the string constant pool.
• The variable s will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
public static void main(String args[]){ Output
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'}; java
String s2=new String(ch);//converting char array to string strings
String s3=new String("example");// example
creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Methods in String class

• 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.
• https://www.javatpoint.com/methods-of-string-class
Immutable String in Java
• In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
• Once string object is created its data or state can't be changed but a new string
object is created.

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//
will print Sachin because strings are immutable objects
}
}
• Output: Sachin
Immutable String in Java

As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
Immutable String in Java
• But if we explicitily assign it to the reference variable, it will refer to "Sachin
Tendulkar" object.
• For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin Tendulkar

Note:In such case, s points to the "Sachin Tendulkar". Please notice that still sachin
object is not modified.
Why string objects are immutable in java?
• Because java uses the concept of string literal.

• Suppose there are 5 reference variables,all refers to one object


"sachin“.If one reference variable changes the value of the object, it
will be affected to all the reference variables.

• Java defines a peer class of String, called StringBuffer


• allows strings to be altered, so all of the normal string manipulations are still
available in Java.
Java StringBuffer class

• To create mutable (modifiable) string.

• The StringBuffer class in java is same as String class except it is


mutable i.e. it can be changed.
StringBuffer append() method
• The append() method concatenates the given argument with this string.

class StringBufferExample {

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java");

//now original string is changed

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

}
StringBuffer insert() method
• The insert() method inserts the given string with this string at the given position.

class StringBufferExample2{

public static void main(String args[]){

StringBuffer sb = new StringBuffer("Hello ");

sb.insert(1,"Java"); //now original string is changed

System.out.println(sb); //prints HJavaello

}
StringBuffer replace() method
• The replace() method replaces the given string from the specified
beginIndex(including) and endIndex(excluding).

class StringBufferExample3{

public static void main(String args[]){

StringBuffer sb = new StringBuffer("Hello");

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo

}
StringBuffer delete() method
• The delete() method of StringBuffer class deletes the string from the specified
beginIndex(including) to endIndex(excluding).

class StringBufferExample4{

public static void main(String args[]){

StringBuffer sb = new StringBuffer("Hello");

sb.delete(1,3);

System.out.println(sb);//prints Hlo

}
Character Class
• Creating a Character object :
• You can create a Character object with the Character constructor

Character ch = new Character('a');

• There is only one constructor in Character class which expect an


argument of char data type.
Character Class
• 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.
• Example
Character ch = 'a'; // Here following primitive char 'a' is boxed into the
Character object ch.
char c = test('x'); // Here primitive 'x' is boxed for method test, return is unboxed
to char 'c‘. (autoboxing/unboxing char to Character)
Methods in Character Class
• The Character class offers a number of useful class (i.e., static) methods for
manipulating characters.

1)boolean isLetter(char ch) :


Syntax : boolean isLetter(char ch)
Parameters : ch - a primitive character
Returns : returns true if ch is a alphabet, otherwise return false

2) boolean isDigit(char ch) :


Syntax : boolean isDigit(char ch)
Parameters : ch - a primitive character
Returns : returns true if ch is a digit, otherwise return false
Methods in Character Class
public class JavaCharacterExample2{ String str1 = " The first character is a letter: " + b1;
public static void main(String[] args) { String str2 = " The second character is a lower-case: " + b2;
// Create four char primitives ch1, ch2, ch3 and ch4. String str3 = " The third character is for space: " + b3;
char ch1, ch2, ch3, ch4; String str4 = " Fourth character is defined in Java identifier: " + b4;
// Assign the values to ch1, ch2, ch3 and ch4. // Print the values of b1, b2, b3 and b4.
System.out.println( str1 );
ch1 = 'T';
System.out.println( str2 );
ch2 = 'k'; System.out.println( str3 );
ch3 = '\n'; System.out.println( str3 );
ch4 = 'G'; }
// Create four boolean primitives b1, b2, b3 and b4. }
boolean b1, b2, b3,b4;
// Assign the results to b1, b2, b3 and b4.
b1 = Character.isLetter(ch1); Output
b2 = Character.isLowerCase(ch2); The first character is a letter: true
The second character is a lower-case: true
b3 = Character.isSpace(ch3);
The third character has a space: true
b4 = Character.isDefined(ch4); Fourth character is defined in Java identifier: true
Nested classes
• Defining a class within another class

• To logically group classes that are only used in one place


• thus this increases the use of encapsulation, and create more
readable and maintainable code.

class OuterClass {
...

class NestedClass {
...
}
}
Nested classes
• Scope of a nested class is bounded by the scope of its enclosing class.

• If class B is defined within class A, then scope of B is bounded by scope of A,


and B does not exist independently /without of A.[B not available outside A] .

• A nested class (B) has access to the members, including private members, of the
class in which it is nested (A).
• Eg: If B is a class defined inside class A, then B can access private members of
class A.

• The enclosing class does not have access to the members of the nested class.

• Eg: Class A cannot access members of class B. [need to create object]


Nested classes
Types of nested class
Nested classes
• Static classes- with static keyword

• A static class must access the members of its enclosing class through an object.
• it cannot refer to members of its enclosing class directly, so static nested
classes are seldom used.

• Inner class
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its outer class and may
refer to them directly.
THANK YOU

You might also like