0% found this document useful (0 votes)
28 views180 pages

Module 1

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views180 pages

Module 1

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 180

OOPDP

Module I
Module I-Syllabus

• Introduction to Object Technology, Java, Understanding the


Java development environment, Programming in Java,
Memory concepts, Doing basic Arithmetic, Comparing
entities, Classes, Objects, Methods, Strings, Primitive vs
reference types.
INTRODUCTION TO OBJECT
TECHNOLOGY
• As the name suggests, Object-Oriented Programming or OOPs
refers to languages that uses objects in programming.

• The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function.
Object Oriented Programming Vs
Procedure Oriented Programming
OOP POP
Object Oriented Structure Oriented
Bottom UP Approach Top Down Approach
Program is divided into Objects Program is divided into functions
Object can move and communicate with Data can move freely from function to
each other through member functions function
Data and Functions of a particular object Every function contains different data
will act as a single unit
OOP CONCEPTS
• Object-Oriented Programming is a methodology or paradigm
to design a program using classes and objects.

• It simplifies software development and maintenance by


providing some concepts:

• Class
• Object
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
Class:

• A class is a user defined blueprint or prototype from which


objects are created.

• It represents the set of properties or methods that are


common to all objects of one type.
Object:

• An object is an instance of a class

• An object consists of:


– State : It is represented by attributes of an object.
– Behavior : It is represented by methods of an object
– Identity : It gives a unique name to an object and enables
one object to interact with other objects.
• Example1:
• Class/Object- Dogs
• State/Attributes- size, age, color, breed, etc.
• Methods/Behavior- eat, sleep, sit and run.

• Example 2:
• Class/Object: House
• State: Address, Color, Area
• Behavior: Open door, close door
• Polymorphism:

• Polymorphism refers to the ability of OOPs programming


languages to differentiate between entities with the same
name efficiently.

• Polymorphism in Java are mainly of 2 types:


1. Overloading in Java
2. Overriding in Java
• Overloading in Java

• Overloading allows different methods to have the same name,


but different signatures where the signature can differ by the
number of input parameters or type of input parameters or
both.
• Also a compile-time (or static) polymorphism.
• Overriding in Java

• Overriding is a feature that allows a subclass or child class to


provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes.

• When a method in a subclass has the same name, same


parameters or signature and same return type(or sub-type) as
a method in its superclass, then the method in the subclass is
said to override the method in the super-class.

• It is an example of Run time polymorphism in Java


• Inheritance:

• Inheritance is an important pillar of OOP(Object Oriented


Programming).

• It is the mechanism in java by which one class is allow to


inherit the features of another class.

• The class whose features are inherited is known as


superclass(or a base class or a parent class).

• The class that inherits the other class is known as subclass(or


a derived class, extended class, or child class).
• The subclass can add its own fields and methods in addition
to the superclass fields and methods.

• Advantage: Inheritance supports the concept of “reusability”.

• In Java the keyword used for inheritance is extends.


Example: Inheritance
• Encapsulation

• Encapsulation in Java is a mechanism of wrapping the data


(variables) and code acting on the data (methods) together as
a single unit.

• In encapsulation, the variables of a class will be hidden from


other classes, and can be accessed only through the methods
of their current class.
• Therefore, it is also known as data hiding.
• To achieve encapsulation in Java
– Declare the variables of a class as private.
– Provide public setter and getter methods to modify and view the
variables values.
• Data Abstraction:

• Data Abstraction is the property by virtue of which only the


essential details are displayed to the user.
• Ex: A car is viewed as a car rather than its individual
components.

• In java, abstraction is achieved by interfaces and abstract


classes.
JAVA
• Java is an object-oriented programming language developed
by James Gosling and colleagues at Sun Microsystems in the
early 1990s.

• The language itself borrows much syntax from C and C++ but
has a simpler object model and fewer low-level facilities.

• Java is not pure object oriented because it supports primitive


data type like int,byte,long etc.,which are not objects.
FEATURES OF JAVA
• Simple

• Java syntax is based on C++ (so easier for programmers to


learn it after C++).

• Java has removed many complicated and rarely-used features,


for example, explicit pointers, operator overloading, etc.

• There is no need to remove unreferenced objects because


there is an Automatic Garbage Collection in Java.
• Object-oriented

• Java is an object-oriented programming language.

• Everything in Java is an object.

• Object-oriented means we organize our software as a


combination of different types of objects that incorporates
both data and behavior.
• Platform Independent

• The meaning of platform-independent is that the java


compiled code(byte code) can run on all operating systems.

• A program is written in a language that is a human-readable


language.

• The compiler converts the high-level language (human


language) into a format understood by the machines.
• The result of the JAVA compiler is the .class file or the
bytecode and not the machine native code (unlike C
compiler).

• The bytecode generated is a non-executable code and needs


an interpreter to execute on a machine.

• This interpreter is the JVM and thus the Bytecode is executed


by the JVM.
• Secured

• Classloader:
– Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine
dynamically.
– It adds security by separating the package for the classes of the local
file system from those that are imported from network sources.

• Bytecode Verifier:
– It checks the code fragments for illegal code that can violate access
right to objects.

• Security Manager:
– It determines what resources a class can access such as reading and
writing to the local disk.
• Robust

• Robust simply means strong.

• Java is robust because:


– It uses strong memory management.
– There is a lack of pointers that avoids security problems.
– There is automatic garbage collection in java which runs on the
Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
– There are exception handling and the type checking mechanism
in Java.
• Architecture-neutral
• Java is architecture neutral because there are no
implementation dependent features, for example, the size of
primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit
architecture.
• However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
• Portable

• Java is portable because it facilitates you to carry the Java bytecode


to any platform.

• It doesn't require any implementation.

• Distributed

• Java is distributed because it facilitates users to create distributed


applications in Java.

• RMI and EJB are used for creating distributed applications.


• Multi-threaded

• A thread is like a separate program, executing concurrently.

• We can write Java programs that deal with many tasks at once
by defining multiple threads.

• The main advantage of multi-threading is that it doesn't


occupy memory for each thread.

• It shares a common memory area.

• Threads are important for multi-media, Web applications, etc.


• Dynamic

• Java is a dynamic language.

• It supports dynamic loading of classes.

• It means classes are loaded on demand.

• Java supports dynamic compilation and automatic memory


management (garbage collection).
JAVA DEVELOPMENT ENVIRONMENT
JDK(JAVA DEVELOPMENT KIT)

• The Java Development Kit (JDK) is a software development


environment used for developing Java applications and
applets.

• It includes the Java Runtime Environment (JRE), an


interpreter/loader (Java), a compiler (javac), an archiver (jar),
a documentation generator (Javadoc) and other tools needed
in Java development.
JRE(JAVA RUNTIME ENVIRONMENT)

• JRE stands for “Java Runtime Environment” and may also be


written as “Java RTE.”

• The Java Runtime Environment provides the minimum


requirements for executing a Java application; it consists of
the Java Virtual Machine (JVM), core classes, and supporting
files.
JVM(Java Virtual Machine)

• JVM (Java Virtual Machine) is an abstract machine.

• It is called a virtual machine because it doesn't physically


exist.

• It is a specification that provides a runtime environment in


which Java bytecode can be executed.
JDK

JRE

JVM +Class Libraries +Development Tools


+
COMPILATION AND EXECUTION OF JAVA
PROGRAM
• Java, being a platform independent programming language,
doesn’t work on one-step-compilation.

• Instead, it involves a two-step execution, first through an OS


independent compiler; and second, in a virtual machine (JVM)
which is custom-built for every operating system.

• The two principle stages are explained below
– Compilation
– Execution
Compilation

• First, the source ‘.java’ file is passed through the compiler,


which then encodes the source code into a machine
independent encoding, known as Bytecode.

• The content of each class contained in the source file is stored


in a separate ‘.class’ file.
Execution

• The class files generated by the compiler are independent of


the machine or the OS, which allows them to be run on any
system.

• To run, the main class file (the class that contains the method
main) is passed to the JVM, and then goes through three main
stages before the final machine code is executed. These
stages are:
– Class Loader
– Byte Code Verifier
– Just In Time Compiler
• Class Loader:

• The main class is loaded into the memory by passing its ‘.class’
file to the JVM, through invoking the latter.

• All the other classes referenced in the program are loaded


through the class loader.
• Bytecode Verifier:

• After the bytecode of a class is loaded by the class loader, it


has to be inspected by the bytecode verifier, whose job is to
check that the instructions don’t perform damaging actions.

• The following are some of the checks carried out:


– Variables are initialized before they are used.
– Method calls match the types of object references.
– Rules for accessing private data and methods are not violated.
JIT(Just In-Time compiler)
• The interpretation of Java bytecode reduces the performance of the
native application.

• It is the reason to implement the JIT compiler.

• The JIT compiler aids in improving the performance of Java


programs by compiling bytecode into native machine code at run
time.

• The JIT compiler is enabled by default.

• When a method has been compiled, the JVM calls the compiled
code of that method directly instead of interpreting it.
JAVA PROGRAMMING
Object and Class Example
//Java Program to illustrate how to define a class and fields
class Student{
//defining fields
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
• Output
0
null
How to compile and execute

• Open a command prompt window and go to the directory where


you saved the java program (MyFirstJavaProgram.java).

• Type 'javac MyFirstJavaProgram.java' and press enter to compile


your code.

• If there are no errors in your code, the command prompt will take
you to the next line

• Now, type ' java MyFirstJavaProgram ' to run your program.

• You will be able to see the result printed on the window.


Class: Syntax
• A class is a collection of fields(data) and
methods(procedure or function) that operate on that
data.
• The basic syntax for a class definition:

[Access Specifier]class ClassName


{
[fields declaration]
[methods declaration]
}
Example2:
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
public class TestStudent{
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();
}
• Output
111 Karan
222 Aryan
ENCAPSULATION IN JAVA
Example

public class Person


{ private String name; // private = restricted access
// Getter
public String getName()
{ return name; }
// Setter
public void setName(String newName)
{ name = newName;
}
}
public class Main
{
public static void main(String[] args)
{
Person myObj = new Person();
myObj.name = "John"; // error System.out.println(myObj.name);
// error
}
}
public class Main
{
public static void main(String[] args)
{
Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());
}
}
• // Outputs "John"
MEMORY CONCEPTS
Java Constructors

• A constructor in Java is a special method that is used to


initialize objects.

• The constructor is called when an object of a class is created.

• It can be used to set initial values for object attributes


• There are few rules defined for the 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


Types of Java constructors

• There are two types of constructors in Java:

– Default constructor (no-arg constructor)

– Parameterized constructor
Default Constructor

• Java automatically creates default constructor if there is no


default or parameterized constructor written by user

• It will initialize the variables to its default value


Example

public class Tester


{ int a;
String b;

public static void main(String[] args) {


Tester t = new Tester();
System.out.println(t.a);
System.out.println(t.b);
}
}
• Output
0
null
Non-Parameterised Constructor

public class Main


{
int x;
public Main()
{
System.out.println("Constructor called");
}
public static void main(String[] args)
{ Main myObj = new Main();
System.out.println(myObj.x);
}
}
• Output
Constructor called
0
Parameterised Constructor
public class Main
{
int x;
public Main(int y)
{
x = y;
}
public static void main(String[] args)
{
Main myObj = new Main(5);
System.out.println(myObj.x);
}
}
// Outputs 5
Example2
public class Main
{
int x;
public Main(int a)
{
x=a;
}
public Main(Main ob)
{
x=ob.x;
}
public static void main(String[] args)
{ Main Obj1 = new Main(5);
System.out.println(Obj1.x);
Main Obj2 = new Main(Obj1);
System.out.println(Obj2.x);

}
}
• Output
5
5
JAVA DATA TYPES
Primitive Data Types

• A primitive data type specifies the size and type of variable


values, and it has no additional methods.

• There are eight primitive data types in Java:


Rules for naming a Variable

• The rules and conventions for naming your variables can be


summarized as follows:
– Variable names are case-sensitive. A variable's name can be any legal
identifier: an unlimited-length sequence of Unicode letters and digits,
beginning with a letter, the dollar sign "$", or the underscore character
"_“
– Also keep in mind that the name you choose must not be a keyword or
reserved word.
– White space is not permitted.
Types of Variables

• There are three types of variables in Java:

1. Local Variables

2. Instance Variables

3. Static Variables
Local Variables:

• A variable defined within a block or method or constructor is


called local variable.

• These variable 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 these
variable only within that block.

• Initilization of Local Variable is Mandatory.


Example

public class StudentDetails


{
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}

public static void main(String args[])


{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
• Output:

Student age is : 5
Instance Variables:

• Instance variables are non-static variables and are 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.
• Initilisation of Instance Variable is not Mandatory.
• Instance Variable can be accessed only by creating objects.
class Marks {
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}
class MarksDemo {
public static void main(String args[])
{
// first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
// displaying marks for first object
System.out.println("Marks for first object:");
System.out.println(obj1.engMarks);
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);

}
}
• Output:
Marks for first object:
50
80
90
Static variables

• When a variable is declared as static, then a single copy of variable


is created and shared among all objects at class level.

• The static variable can be used to refer to the common property of


all objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.

• The static variable gets memory only once in the class area at the
time of class loading.

• Advantages of static variable


• It makes your program memory efficient (i.e., it saves memory).
Example
class Student{
int rollno;
String name;
static String college ="ITS";//static variable
Student(int r, String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
• Output:
111 Karan ITS
222 Aryan ITS
OPERATORS IN JAVA
• Simple Assignment Operator
• = Simple assignment operator

• Arithmetic Operators
• + Additive operator (also used for String concatenation)
• - Subtraction operator
• * Multiplication operator
• / Division operator
• % Remainder operator
• Unary Operators
• + Unary plus operator; indicates positive value (numbers
are positive without this, however)
• - Unary minus operator; negates an expression
• ++ Increment operator; increments a value by 1
• -- Decrement operator; decrements a value by 1
• ! Logical complement operator; inverts the value of a
boolean
• Equality and Relational Operators
• == Equal to
• != Not equal to
• > Greater than
• >= Greater than or equal to
• < Less than
• <= Less than or equal to

• Conditional Operators
• && Conditional-AND
• || Conditional-OR
• ?: Ternary (shorthand for if-then-else statement)
• Type Comparison Operator
• instanceof Compares an object to a specified type

• Bitwise and Bit Shift Operators


• ~ Unary bitwise complement
• << Signed left shift
• >> Signed right shift
• >>> Unsigned right shift
• & Bitwise AND
• ^ Bitwise exclusive OR
• | Bitwise inclusive OR
Java instanceof

• The java instanceof operator is used to test whether the


object is an instance of the specified type

• An object of subclass type is also a type of parent class. For


example, if Dog extends Animal then object of Dog can be
referred by either Dog or Animal class.

• If we apply instanceof operator with a variable that have null


value, it returns false.
Example1

class Simple{
public static void main(String args[]){
Simple s=new Simple();
System.out.println(s instanceof Simple);
}
}
// Outputs true
class D{
public static void main(String args[]){
D d=null;
System.out.println(d instanceof D);
}
}
//Outputs false
JAVA WRAPPER CLASSES
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.

• Since J2SE5.0, autoboxing and unboxing feature convert


primitives into objects and objects into primitives
automatically.

• The automatic conversion of primitive into an object is known


as autoboxing and vice-versa unboxing.

• The wrapper classes are part of the java. lang package, which
is imported by default into all Java programs.
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Wrapper class Example: Primitive to Wrapper

public class WrapperExample1{


public static void main(String args[]){

int a=20;
Integer i=Integer.valueOf(a);
Integer j=a;//autoboxing
System.out.println(a+" "+i+" "+j);
}
}
• Output:
20 20 20
Example: Wrapper to Primitive

public class WrapperExample2{


public static void main(String args[]){
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a; //unboxing,
System.out.println(a+" "+i+" "+j);
}
}
• Output:
333
PRIMITIVE AND REFERENCE VARIABLES IN
JAVA
Primitive variable

• A primitive variable has as its declared data type one of the


eight primitive data types.

• These are data types that are built into the Java language and
identified by Java keywords.
• A primitive variable is a direct reference to its datum, meaning
that the datum is stored immediately within the variable’s
associated memory location.

• Example:
• double radius = 6.25;
• double diameter = 2 * radius;
• int topScore = 100;
Reference variable

• A reference variable has as its declared data type a Java class.

• A reference variable is an indirect reference to an object,


meaning that it holds the address of where the object is
stored in the computer’s internal memory.

• The JVM retrieves the object in two steps:


• (1) it uses the reference variable to retrieve the object’s
address and
• (2) uses the address to retrieve the object.
• Reference variables are handles to the object which is created
in heap memory.

• The main difference between heap and stack is that stack


memory is used to store local variables and function calls
while heap memory is used to store objects in Java.

• No matter, where the object is created in code e.g. as a


member variable, local variable, or class variable, they are
always created inside heap space in Java.
Difference between Primitive vs Reference variable

• First difference between primitive and reference type is that


former can never be null if no value is assigned they take their
default value

• When you assign a value to primitive data types, the primitive


value is copied, but when you assign an object to reference
type, the handle is copied. which means for reference type
object is not copied only the handle is copied, i.e. the object is
shared between two reference variable
• To compare primitive variables using equality (==) operator,
their primitive values are compared but when you compare
reference variable, their address is compared, which means
two objects which are logically equal e.g. two String object
with same content may be seen as not equal
• When you pass primitive values to a method the values are
passed to the method, but when you pass reference variable,
only the handle is copied.

• Which means for primitives, changing the formal parameter's


value doesn't affect the actual parameter's value

• While in case of reference types, changing the formal


parameter's handle doesn't affect the actual parameter's
address but changing the formal parameter's internal values
does affect actual parameter's object, because they refer to
the same object in memory.
• When you return primitive types from a method then the
primitive value is returned but when you return a reference
type, again only handle to the is returned.

• This means a locally created object can survive even after


method finishes its execution

• Because object is always created in heap memory.


WAYS TO READ INPUT FROM CONSOLE IN
JAVA
1.Using Buffered Reader Class

• This is the Java classical method to take input, Introduced in


JDK1.0.
• This method is used by wrapping the System.in (standard
input stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the
command line.
• The BufferedReader class of Java is used to read the stream of
characters from the specified source (character-input stream).
• The constructor of this class accepts an InputStream object as
a parameter.
• This class provides a method known as readLine() which reads
and returns the next line from the source and returns it in
String format.
• The BufferedReader class doesn’t provide any direct method
to read an integer from the user you need to rely on the
readLine() method to read integers too. i.e. Initially you need
to read the integers in string format.
• The parseInt() method of the Integer class accepts a String
value, parses it as a signed decimal integer and returns it.
Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Employee
{
String name;
int id;
int age;
Employee(String name, int age, int id)
{
this.name = name;
this.age = age;
this.id = id; }
public void displayDetails(){
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Id: "+this.id);
}}
public class ReadData {
public static void main(String args[]) throws IOException
{
BufferedReader reader =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your name: ");
String name =reader.readLine();
System.out.println("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("Enter your Id: ");
int id = Integer.parseInt(reader.readLine());
Employee std = new Employee(name, age, id);
std.displayDetails();
}}
2. Using Scanner Class

• Scanner class in Java is found in the java.util package.

• The main purpose of the Scanner class is to parse primitive


types and strings using regular expressions, however it is also
can be used to read input from the user in the command line.
Example
import java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

int a = in.nextInt();
System.out.println("You entered integer "+a);

float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
Difference between Scanner class and BufferedReader
class

• BufferedReader is synchronous while Scanner is not.


BufferedReader should be used if we are working with
multiple threads.
• BufferedReader has significantly larger buffer memory
than Scanner.
• The Scanner has a little buffer (1KB char buffer) as
opposed to the BufferedReader (8KB byte buffer), but it’s
more than enough.
• BufferedReader is a bit faster as compared to scanner
because scanner does parsing of input data and
BufferedReader simply reads sequence of characters.
3. Java Console Class

• The Java Console class is be used to get input from console.

• It provides methods to read texts and passwords.

• If you read password using Console class, it will not be


displayed to the user.
Example1

import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
• Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Example2

import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string

System.out.println("Password is: "+pass);


}
}
• Output
Enter password:
Password is: 123
STRINGS IN JAVA
• Generally, String is a sequence of characters.
• But in Java, string is an object that represents a sequence of
characters.
• The java.lang.String class is used to create a string object.
• There are two ways to create String object:

1. By string literal

2. By new keyword
String Literal

• Java String literal is created by using double quotes.

• String s="welcome";

• Each time you create a string literal, the 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.
Example

• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance

• It makes Java more memory efficient (because no new objects


are created if it exists already in the string constant pool).
By new keyword

• String s=new String("Welcome");//creates two objects and


one reference variable

• In such case, 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).


Example

public class Main{


public static void main(String[] args)
{
String s=new String("Welcome");
String s1="Welcome";
String s2="Welcome";
String s3=new String("Welcome");
System.out.println(s==s1);
System.out.println(s2==s1);
System.out.println(s==s3);
System.out.println(s2==s3);
}}
• Output
false
true
false
false
IMMUTABILITY OF JAVA STRINGS
• 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.
Example1

class Test{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s);
}
}
• Output
Sachin
Sachin is not changed but a new object is created as Sachin Tendulkar
Example2

class Test {
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
} }
• Output
Sachin Tendulkar

//Explicitly assigned the variable to Sachin Tendulkar


//Object Sachin is still not modified
Why string objects are immutable in java?

• Because java uses the concept of string literal.

• Suppose there are 5 reference variables,all referes to one


object "sachin".

• If one reference variable changes the value of the object, it


will be affected to all the reference variables.

• That is why string objects are immutable in java.


STRING CLASS METHODS
length()

• The java string length() method returns length of the string.

• Length is the count of total number of characters.


Example

public class Example{


public static void main(String args[]){
String s1="java";
String s2="python";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}}

Output
string length is: 4
string length is: 6
charAt()

• The java string charAt() method returns a char value at the


given index number.

• It returns StringIndexOutOfBoundsException if given index


number is greater than or equal to this string length or a
negative number.
Example

public class Example{


public static void main(String args[]){
String name=“Welcome";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}

Output
o
substring()

• String substring(int beginIndex)


• returns substring for given begin index.

• String substring(int beginIndex, int endIndex)


• returns substring for given begin index and end index.
Example

public class SubstringExample{


public static void main(String args[]){
String s1=“helloworld";
System.out.println(s1.substring(2,4));//returns ll
System.out.println(s1.substring(2));//returns lloworld
}}
Contains()

• The java string contains() method searches the sequence of


characters in this string.

• It returns true if sequence of char values are found in this


string otherwise returns false.
Example

class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}

Output
true
true
false
equals()

• The java string equals() method compares the two given


strings based on the content of the string.

• If any character is not matched, it returns false.

• If all characters are matched, it returns true.


Example

public class Main{


public static void main(String[] args)
{
String name="abc";
String name1=new String("abc");
System.out.println(name.equals(name1));
}}

Output
true
valueOf()

• The java string valueOf() method converts different types of


values into string.
• By the help of string valueOf() method, you can convert int to
string, long to string, boolean to string, character to string,
float to string, double to string and char array to string.
Example

public class StringValueOfExample{


public static void main(String args[]){
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);
}}

Output
3010
compareTo()

• The java string compareTo() method compares the given


string with current string lexicographically.
• It returns positive number, negative number or 0.
• If first string is lexicographically greater than second string, it
returns positive number (difference of character value).
• If first string is less than second string lexicographically, it
returns negative number
• And if first string is lexicographically equal to second string, it
returns 0.
Example

public class CompareToExample{


public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));"
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s5));
}}
• Output
0
-5
-1
2
toCharArray()

• The java string toCharArray() method converts this string into


character array.
• It returns a newly created character array, its length is similar
to this string and its contents are initialized with the
characters of this string.
Example

public class StringToCharArrayExample{


public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
}}
//Outputs hello
String class in Java: Complete Reference

• https://docs.oracle.com/javase/7/docs/api/java/lang/String.h
tml
STRINGBUFFER CLASS IN JAVA
• Java StringBuffer class is used 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.


Important Constructors of StringBuffer class

• StringBuffer()
– creates an empty string buffer with the initial capacity of
16.

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

• StringBuffer(int capacity)
– creates an empty string buffer with the specified capacity
as length.
Example

public class Main


{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer();
sb1.append("hello");
System.out.println(sb1);
StringBuffer sb2=new StringBuffer("java");
System.out.println(sb2);
StringBuffer sb3=new StringBuffer(20);
sb3.append("Java StringBuffer class");
System.out.println(sb3);
}}
• Output
hello

java

Java StringBuffer class


• StringBuffer sb1=new StringBuffer();
• sb1="hello"; //error

• error: incompatible types: String cannot be converted to


StringBuffer
METHODS OF STRINGBUFFER CLASS
insert()

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

class Main {
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
}
}
replace()

• The replace() method replaces the given string from the


specified beginIndex and endIndex.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
delete()

• The delete() method of StringBuffer class deletes the string


from the specified beginIndex to endIndex.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
reverse()

• The reverse() method of StringBuilder class reverses the


current string.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); //prints olleH
}
}
capacity()

• The capacity() method of StringBuffer class returns the


current capacity of the buffer.

• The default capacity of the buffer is 16.

• If the number of character increases from its current capacity,


it increases the capacity by (oldcapacity*2)+2.

• For example if your current capacity is 16, it will be


(16*2)+2=34.
Example

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());
sb.append("Hello");
System.out.println(sb.capacity());
sb.append("java is my favourite language");
System.out.println(sb.capacity());
}
}
• Output
16
16
34
ensureCapacity()

• The ensureCapacity() method of StringBuffer class ensures that the given


capacity is the minimum to the current capacity.

• If it is greater than the current capacity, it increases the capacity by


(oldcapacity*2)+2.

• For example if your current capacity is 16, it will be (16*2)+2=34.


Example
class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");
System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10); //now no change
System.out.println(sb.capacity()); //now 34
sb.ensureCapacity(50); //now (34*2)+2
System.out.println(sb.capacity()); //now 70
}
}
SAMPLE QUESTIONS
1. Describe the relevance of passing a String array to the main
method in java?

2. Differentiate between Object Oriented Programming and


Procedure Oriented Programming methodologies

3. Explain the significance of default constructor in java with


example.

4. Identify the advantages behind keeping Strings as immutable in


Java

5. Explain how Java achieves major object-oriented features, using


examples.

6. Describe the significance of wrapper classes in Java.

You might also like