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

Unit 1&2 Notes

Java is a high-level, object-oriented programming language developed by Sun Microsystems and released in 1995, featuring key concepts such as encapsulation, inheritance, and polymorphism. It is known for its portability, security, and robustness, allowing programs to run on any platform without modification. The document also covers Java's data types, control statements, operators, arrays, reference variables, method overloading and overriding, constructors, and inheritance types.

Uploaded by

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

Unit 1&2 Notes

Java is a high-level, object-oriented programming language developed by Sun Microsystems and released in 1995, featuring key concepts such as encapsulation, inheritance, and polymorphism. It is known for its portability, security, and robustness, allowing programs to run on any platform without modification. The document also covers Java's data types, control statements, operators, arrays, reference variables, method overloading and overriding, constructors, and inheritance types.

Uploaded by

Aman Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Overview of Java

Java is a high-level programming language originally developed by Sun Microsystems under the
guidance of James Gosling and there team, and released in 1995.

OOPs Concepts in Java


Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java
supports the following fundamental concepts –

1) Object: Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.

2) Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be physical.

3) Encapsulation: Binding (or wrapping) code and data together into a single unit is known as
encapsulation. A java class is the example of encapsulation.

4) Abstraction: Hiding internal details and showing functionality is known as abstraction.

5) Inheritance: The process by which one class acquires the properties and functionalities of
another class is called inheritance. It provides code reusability.

6) Polymorphism: When one task is performed by different ways i.e. known as polymorphism.
In java, we use method overloading and method overriding to achieve polymorphism.

Features of Java
1) Simple: The Java language is easy to learn and its coding style is easy to read and write.

2) Object Oriented: It has all OOP features such as abstraction, encapsulation, inheritance and
polymorphism.

3) Portable: Java programs can execute in any environment (Linux, Window, Mac etc.)

4) Platform Independent: Java is guaranteed to be Write Once, Run Anywhere language.

5) Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.

6) Robust: Its capability to handle Run-time Error, automatic garbage collection, the lack of
pointer concept, Exception Handling etc. makes java robust.

7) Architectural Neutral: To enable a Java application to execute anywhere on the network, the
compiler generates an architecture-neutral object file format.
8) Dynamic: It supports Dynamic memory allocation due to this memory wastage is reduce and
improve performance of the application.

9) Interpreted: The Java compiler generates byte-codes, rather than native machine code.

10) High Performance: Java enables high performance with the use of just-in-time compiler.

11) Multithreaded: It utilizes same memory and other resources to execute multiple threads at
the same time.

12) Distributed: It has networking facilities, so it can be transmit, run over internet.

JDK (Java Development Kit): JDK is a container of tools which are needed to develop java
programs.

JRE (Java Runtime Environment): JRE is an implementation of the JVM which actually executes
Java programs.

JVM (Java Virtual Machine): JVM is an abstract machine that enables your computer to run a
Java program

Data Types in Java


Data types represent the different values to be stored in the variable. In java, there are two
types of data types:
1. Primitive data types: Primitive data types are predefined by the language and named by a
keyword.
2. Non-primitive data types: These data types are those which are developed by programmers
by making use of appropriate features of the language.

Primitive Data Types

Sr. No. Data Type Size Contains


1. byte 1 byte Byte Length Integer
2. short 2 byte Short Integer
3. int 4 byte Integer
4. long 8 byte Long Integer
5. float 4 byte Single Precision Floating Point
6. double 8 byte Double Precision Floating Point
7. char 2 byte A Single Character(Unicode Character)
8. boolean 1 bit A Boolean Value(True or False)

Control Statements in Java


The control statements are used to control the flow of execution of the program. Java contains
the following types of control statements:
1) Branching Statements (Selection Statements)

Selection statements allow you to control the flow of program execution on the basis of the
outcome of an expression or state of a variable known during runtime.

Selection statements can be divided into the following categories:

• The if statements: It executes the if block if condition is true.


Syntax:
if(condition)
{
//code to be executed
}
• The if-else statements: It executes if block if condition is true otherwise else block is
executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
• The if-else-if statements (nested if-else statements): It executes one condition from
multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
• The switch statements: It is used when we have number of options (or choices) and we may
need to perform a different task for each choice.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
2) Looping Statements (Iteration Statements)

Iteration statements execute the same set of instructions until a termination condition is met.

Java provides the following loop for iteration statements:


• The while loop: while loop is used to execute statement(s) until a condition holds true.
Syntax:
while(condition)
{
Statements(s);
}
• The for loop: for loop is a statement which allows code to be repeatedly executed. For loop
contains 3 parts Initialization, Condition and Increment or Decrements
Syntax:
for( initialization; condition; increment )
{
statement(s);
}
• The do-while loop: A do-while loop is similar to a while loop, except that a do-while loop is
execute at least one time.
Syntax:
do
{
Statement(s);

increment/decrement (++ or --)


}while();
• The for each loop: It is mainly used to traverse array or collection elements.
Syntax:
for (type var : array)
{
statements using var;
}
3) Jump Statements
Jump statements are used to unconditionally transfer the program control to another part of
the program.
Java provides the following jump statements:
• break statement: This statement is used to jump out of a loop.
Syntax:
if(condition)
{
break;
}
• continue statement: This statement is used only within looping statements.
Syntax :
if(condition)
{
continue;
}
• return statement: The return statement is used to explicitly return from a method.
Syntax :
if(condition)
{
return;
}
Operators in java
Operators are special symbols that are used to perform mathematical or logical operations on
operands (variables or values).
Different types of Operators in java

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

Additive +-

Shift Shift << >> >>>

Relational comparison < > <= >= instanceof

Equality == !=

Bitwise bitwise AND &


bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary Ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

1. Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
2. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive
data types.
3. Shift Operators: These operators are used to shift the bits of a number left or right thereby
multiplying or dividing the number by two respectively.
4. Relational Operators: Relational Operators are used to determine the comparison between
two or more objects.
5. Bitwise Operators: These operators are used to perform manipulation of individual bits of a
number.
6. Logical Operators: These operators are used to perform “logical AND” and “logical OR”
operation
• Logical AND (&&): returns true when both conditions are true.
• Logical OR (||): returns true if at least one condition is true.
7. Ternary Operator: Ternary operator is a shorthand version of if-else statement. It has three
operands and hence the name ternary.
General format is-
condition ? if true : if false
8. Assignment Operator: Assignment operator is used to assign value to the variables, assign
memory to object.
General format is-
variable = value;
Array
An array is a collection of similar data types that have contiguous memory location.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
Disadvantage of Java Array
• Size Limit: We can store only fixed size of elements in the array.
Types of Array in java
There are two types of array:
Single Dimensional Array: A one-dimensional array is a linear list of elements of the same type.
Syntax :
datatype[ ] identifier;
or
datatype identifier[ ];
Example of single dimensional java array
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output: 10
20
70
40
50
Multidimensional Array: MultiDimensional Array is used to store the values in the rows as well
as in columns.
Syntax:
datatype[ ][ ] identifier;
or
datatype identifier[ ][ ];
Example of Multidimensional java array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}

}}
Output: 1 2 3
245
445

Java Reference Variable


Reference variables are used to refer to an object. They are declared with a specific type which
cannot be changed.
Types of reference variables
 Static Variable
 Instance Variable
 Method Parameter
 Local Variable
Method overloading
If two or more method in a class has same name but different parameters, it is known as
method overloading. Overloading always occur in the same class (unlike method overriding).
Method overloading is one of the ways through which java supports polymorphism.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways of Method overloading
There are three different ways of method overloading
• Method overloading by changing data type of Arguments
• Method overloading by changing no. of argument.
• Method overloading by changing sequence of data type of arguments
Example:
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
Output: 30
60
Method Overriding
Whenever same method name is existing in both base class and derived class with same types
of parameters or same order of parameters is known as method Overriding.
Note: Without Inheritance method overriding is not possible.
Advantage of Java Method Overriding
• Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
• Method Overriding is used for Runtime Polymorphism
Example:
class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
class Man extends walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}
class OverridingDemo
{
public static void main(String args[])
{
Man obj = new Man();
obj.walk();
}
}
Output: Man walking slowly
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1) Default Constructor: A constructor that have no parameter is known as default constructor.
Syntax:
<class_name>(){}
Example:
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
Output: Bike is created
2) Parameterized constructor: A constructor that has parameters is known as parameterized
constructor.
Syntax:
<class_name>(parameters){}
Example:
class Student
{
int id;
String name;
Student(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output: 111 Karan
222 Aryan
Constructor Overloading
Constructor overloading is a concept of having more than one constructor with different
parameters list, in such a way so that each constructor performs a different task.
Example:
class Student{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output: 111 Karan 0
222 Aryan 25

Inheritance in Java
Inheritance in java is a mechanism in which one class acquires the properties(data members)
and functionalities(methods) of another class.

Syntax :

class derived-class extends base-class

//methods and fields

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

1) Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.
2) Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class.
3) Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class.

In java programming, multiple and hybrid inheritance is supported through interface only.

4) Multiple Inheritance (Through Interfaces): In Multiple inheritance, one class can have more
than one superclass and inherit features from all parent classes. Please note that Java does
not support multiple inheritance with classes. In java, we can achieve multiple inheritance
only through Interfaces.
5) Hybrid Inheritance (Through Interfaces): It is a mix of two or more of the above types of
inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid
inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.
Access Modifiers
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members.

There are four types of access modifiers available in java:

Default (No keyword required): When we do not mention any access modifier, it is called
default access modifier. The default modifier is accessible only within package.

Private: Private Data members and methods are only accessible within the class. Class and
Interface cannot be declared as private. If a class has private constructor then you cannot
create the object of that class from outside of the class.

Protected: Protected data member and method are only accessible by the classes of the same
package and the subclasses present in any package.

Public: The members, methods and classes that are declared public can be accessed from
anywhere. Public are also called universal access modifiers.

Packages in Java
Packages in Java are groups of similar types of classes, interface and sub packages.

Syntax:-

package;

Advantage of Java Package

 Reusability: The classes contained in the packages of another program can be easily reused.
 Better Organization: Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
 Protection: Java package provides access protection.
 Name Conflicts: Java package removes naming collision.

Types of Packages
Built-in Package: Existing Java package for example java.lang, java.util etc.

User-defined-package: Java package created by user to categorize their project's classes and
interface.

Steps to create a Java package:


1. Create a package name.
2. Pick up a base directory.
3. Make a subdirectory from the base directory that matches your package name.
4. Place your source files into the package subdirectory.
5. Use the package statement in each source file.
6. Compile your source files from the base directory.
7. Run your program from the base directory.

Example of Java packages

//save as FirstProgram.java

package learnjava;

public class FirstProgram{

public static void main(String args[]) {

System.out.println("Welcome to package");

Output: Welcome to package

How to access package from another package?


import keyword

import keyword is used to import built-in and user-defined packages into your java source file
so that your class can refer to a class that is in another package by directly using its name.

There are 3 different ways to refer to any class that is present in a different package:

1. Using fully qualified name

If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, there is no need to use
the import statement.

Example :

//save by A.java
package pack;

public class A {

public void msg() {

System.out.println("Hello");

//save by B.java

package mypack;

class B {

public static void main(String args[]) {

pack.A obj = new pack.A(); //using fully qualified name

obj.msg();

Output: Hello

2. Using packagename.classname

To import only the class/classes you want to use.

Example :

//save by A.java

package pack;

public class A {

public void msg() {

System.out.println("Hello");

}
}

//save by B.java

package mypack;

import pack.A;

class B {

public static void main(String args[]) {

A obj = new A();

obj.msg();

Output: Hello

3. Using packagename.*

To import all the classes from a particular package but the classes and interface inside the
subpackages will not be available for use.

Example :

//save by First.java

package learnjava;

public class First{

public void msg() {

System.out.println("Hello");

//save by Second.java

package Java;
import learnjava.*;

class Second {

public static void main(String args[]) {

First obj = new First();

obj.msg();

Output: Hello

Subpackage
A package created inside another package is known as a subpackage. When we import a
package, subpackages are not imported by default. They have to be imported explicitly. In the
following statement :

import java.util.*;

util is a subpackage created inside java package.

Example of Subpackage

package com.javatpoint.core;

class Simple{

public static void main(String args[]){

System.out.println("Hello subpackage");

Output: Hello subpackage

Abstract class in Java

 A class that is declared with abstract keyword, is known as abstract class in java.
 It can have abstract and non-abstract methods.
 It cannot be instantiated. Abstract classes can have Constructors, Member variables and
Normal methods.
 When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.

Syntax :

abstract class class_name { }

abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.

Syntax :

abstract return_type function_name (); // No definition

Example of Abstract class

abstract class A

abstract void callme();

class B extends A

void callme()

System.out.println("this is callme.");

public static void main(String[] args)

B b = new B();
b.callme();

Output : this is callme.

Interface in Java

 Interface is a pure abstract class.


 They are syntactically similar to classes, but you cannot create instance of an Interface and
their methods are declared without any body.
Properties of Interface
• An interface does not contain any constructors.
• The methods declared in interface are by default abstract (only method signature, no
body)
• The variables declared in an interface are public, static & final by default.

Use of interface in Java

• Interface is used to achieve complete abstraction in Java.


• By using Interface, you can achieve multiple inheritance in java.
• It can be used to achieve loose coupling.

Syntax :

interface interface_name { }

Declaring Interfaces

The interface keyword is used to declare an interface.

Example of Interface

interface Person

datatype variablename=value;

//Any number of final, static fields

returntype methodname(list of parameters or no parameters)


//Any number of abstract method declarations

Implementing Interfaces

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

Example:

interface Person

void run(); // abstract method

class A implements Person

public void run()

System.out.println("Run fast");

public static void main(String args[])

A obj = new A();

obj.run();

Output: Run fast

Interface extends other Interface


Classes implements interfaces, but an interface extends other interface.

Example

interface NewsPaper

news();

interface Magazine extends NewsPaper

colorful();

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

Example:

interface Developer

void disp();

interface Manager

void show();

class Employee implements Developer, Manager

{
public void disp()

System.out.println("Hello Good Morning");

public void show()

System.out.println("How are you ?");

public static void main(String args[])

Employee obj=new Employee();

obj.disp();

obj.show();

Output: Hello Good Morning

How are you?

Final Keyword in Java

Final is a keyword in Java that is used to restrict the user and can be used in many respects. It is
a non-access modifier. The final keyword can be used in following way:

1.) Final at variable level: When a variable is declared with final keyword, it’s value can’t be
modified, essentially, a constant.
Example:
class FinalVariable
{
public static void main(String[] args)
{
final int hours=24;
System.out.println("Hours in 6 days = " + hours * 6);
}
}
Output: Hours in 6 days = 144
2.) Final at method level: When a method is declared with final keyword, method cannot be
overridden.
Example:
class X
{
final void getMethod()
{
System.out.println(“X method has been called”);
}
}
class Y extends X
{
void getMethod() //cannot override
{
System.out.println(“Y method has been called”);
}
}
class FinalMethod
{
public static void main(String[] args)
{
Y obj = new Y();
obj.getMethod();
}
}

Output: error: “getMethod() in Y cannot override getMethod() in X; overridden method


is final.”

3.) Final at class level: When a class is declared with final keyword, class cannot be extended
(inherited).

Example:

final class X
{

//properties and methods of class X

class Y extends X

//properties and methods of class Y

class FinalClass

public static void main(String args[]) {}

Output: error: cannot inherit from final X

Super Keyword in Java

Super keyword in java is a reference variable that is used to refer parent class object.

The use of super keyword

1) To access the data members of parent class when both parent and child class have member
with same name

2) To explicitly call the no-arg and parameterized constructor of parent class

3) To access the method of parent class when child class has overridden that method.

1. Use of super with variables: When you have a variable in child class which is already present
in the parent class then in order to access the variable of parent class, you need to use the
super keyword.

Example:

class Employee

{
float salary=10000;

class HR extends Employee

float salary=20000;

void display()

System.out.println("Salary: "+super.salary);//print base class salary

class Supervarible

public static void main(String[] args)

HR obj=new HR();

obj.display();

Output: Salary: 10000.0

2. Use of super with methods: The super keyword can also be used to invoke parent class
method. It should be used if subclass contains the same method as parent class. In other words,
it is used if method is overridden.

Example:

class Student

{
void message()

System.out.println("Good Morning Sir");

class Faculty extends Student

void message()

System.out.println("Good Morning Students");

void display()

message();//will invoke or call current class message() method

super.message();//will invoke or call parent class message() method

public static void main(String args[])

Student s=new Student();

s.display();

Output: Good Morning Students

Good Morning Sir


3. Use of super with constructors: The super keyword can also be used to invoke the parent
class constructor.

Example:

class Employee

Employee()

System.out.println("Employee class Constructor");

class HR extends Employee

HR()

super(); //will invoke or call parent class constructor

System.out.println("HR class Constructor");

class Supercons

public static void main(String[] args)

HR obj=new HR();

}
}

Output: Employee class Constructor

HR class Constructor

transient keyword in Java

transient is a variables modifier used in serialization. At the time of serialization, if we don’t


want to save value of a particular variable in a file, then we use transient keyword.

Example of Java Transient Keyword

import java.io.Serializable;

public class Student implements Serializable{

int id;

String name;

transient int age;//Now it will not be serialized

public Student(int id, String name,int age) {

this.id = id;

this.name = name;

this.age=age;

Static keyword in java

The static keyword is used in java mainly for memory management. static is a non-access
modifier in Java which is applicable for the blocks, variables, methods, nested classes.

1) 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. Static variables are, essentially,
global variables. All instances of the class share the same static variable.

Syntax for declare static variable:


public static variableName;

2) static method: When a method is declared with static keyword, it is known as static
method. The most common example of a static method is main( ) method. Any static
member can be accessed before any objects of its class are created, and without
reference to any object. Methods declared as static have several restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.

Syntax for declare static method:

public static void methodName()

.......

.......

3) static block: static block is used for initializing the static variables. This block gets
executed when the class is loaded in the memory. A class can have multiple Static
blocks, which will execute in the same sequence in which they have been written into
the program.

Example of static block

class A{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("Hello main");

Output: static block is invoked

Hello main
Volatile Keyword in Java

Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache
value of this variable and always read it from main memory.

Java volatile keyword cannot be used with method or class and it can only be used with
variable.

If the variable keeps on changing such type of variables we have to declare with volatile
modifier.

If a variable declared as volatile then for every thread a separate local copy will be created.

Example:

public class MyClass

private volatile int value;

public int getValue() {

return value;

public void setValue(int value)

this.value = value;

Synchronization in java is the capability to control the access of multiple threads to any shared
resource. If a method or block declared as a Synchronized then at a time only one thread is
allowed to operate on the given object. The synchronization is mainly used to

 To prevent thread interference.


 To prevent consistency problem.

The syntax for a synchronized method is as follows:


<method modifier> synchronized <method signature> {

// synchronized code block

The syntax for a synchronized statement is as follows:

synchronized (expression) {

// synchronized code block

Examples:

The following code example shows instance methods are synchronized:

class BankAccount {

private double balance;

synchronized void withdraw(double amount) {

this.balance -= amount;

synchronized void deposit(double amount) {

this.balance += amount;

The following code example shows a synchronized statement is applied for a code block, not a
method:

Object lock = new Object();

synchronized (lock) {

System.out.println("Synchronized statement");

}
String Handling in Java
The basic aim of String Handling concept is storing the string data in the main memory (RAM),
manipulating the data of the String, retrieving the part of the String etc. String Handling
provides a lot of concepts that can be performed on a string such as concatenation of string,
comparison of string, find sub string etc.

String: String is a sequence of characters enclosed within double quotes (" ") is known as String.

Example: "Java Programming".

How to create String object?

There are two ways to create String object:

1. By string literal: Java String literal is created by using double quotes.

For Example: String s="welcome";

2. By new keyword: In such case, JVM will create a new string object.

For Example: String s=new String("Welcome");

In java programming to store the character data we have a fundamental datatype called char.
Similarly to store the string data and to perform various operations on String data, we have
three predefined classes they are:

1. String class: It is a predefined class in java.lang package can be used to handle the String.
String class is immutable that means whose content can not be changed at the time of
execution of program.String class object is immutable that means when we create an object
of String class it never changes in the existing object.
Example:
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output: java
Methods of String class
 length(): This method is used to get the number of character of any string.
 charAt(): This method is used to get the character at a given index value.
 toUpperCase(): This method is use to convert lower case string into upper case.
 toLowerCase(): This method is used to convert lower case string into upper case.
 concat(): This method is used to combined two string.
 equals(): This method is used to compare two strings, It return true if strings are same
otherwise return false. It is case sensitive method.
 equalsIgnoreCase(): This method is case insensitive method, It return true if the contents of
both strings are same otherwise false.
 compareTo(): This method is used to compare two strings by taking unicode values, It
return 0 if the string are same otherwise return +ve or -ve integer values.
 compareToIgnoreCase(): This method is case insensitive method, which is used to compare
two strings similar to compareTo().
 startsWith(): This method return true if string is start with given another string, otherwise it
returns false.
 endsWith(): This method return true if string is end with given another string, otherwise it
returns false.
 subString(): This method is used to get the part of given string.
 indexOf(): This method is used find the index value of given string. It always gives starting
index value of first occurrence of string.
 lastIndexOf(): This method used to return the starting index value of last occurence of the
given string.
 trim(): This method remove space which are available before starting of string and after
ending of string.
 split(): This method is used to divide the given string into number of parts based on
delimiter (special symbols like @ space , ).
 replace(): This method is used to return a duplicate string by replacing old character with
new character.

2. StringBuffer: It is a predefined class in java.lang package can be used to handle the String,
whose object is mutable that means content can be modify. StringBuffer class is working
with thread safe mechanism that means multiple thread are not allowed simultaneously to
perform operation of StringBuffer. StringBuffer class object is mutable that means when we
create an object of StringBuilder class it can be change.

Example:

You might also like