0% found this document useful (0 votes)
12 views119 pages

Unit-2[Oop Using Java]-Dh Sirs Classroom

The document outlines the curriculum for a fourth-semester course on Object-Oriented Programming using Java, covering key topics such as primitive and user-defined data types, OOP concepts, and Java's history and features. It details programming constructs like variables, arrays, operators, and control statements, as well as the benefits of inheritance and encapsulation. Additionally, it discusses Java editions, types of applications, and the significance of comments and constants in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views119 pages

Unit-2[Oop Using Java]-Dh Sirs Classroom

The document outlines the curriculum for a fourth-semester course on Object-Oriented Programming using Java, covering key topics such as primitive and user-defined data types, OOP concepts, and Java's history and features. It details programming constructs like variables, arrays, operators, and control statements, as well as the benefits of inheritance and encapsulation. Additionally, it discusses Java editions, types of applications, and the significance of comments and constants in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

DH SIRS CLASSROOM

LEARNING MATERIALS
Department : Computer Science & Technology Semester : Fourth (4 th )

Subject : OBJECT ORIENTED PROGRAMMING USING JAVA

UNIT : (2) Building Blocks of the Language

__________________________________________________________________________
Content:
2.1 Primitive Data Types: Integers, Floating Point type, Characters, Booleans etc

2.2 User Defined Data Type

2.3 Identifiers & Literals

2.4 Declarations of constants & variables

2.5 Type Conversion and Casting

2.6 Scope of variables & default values of variables declared

2.7 Wrapper classes

2.8 Comment Syntax

2.9 Garbage Collection

2.10 Arrays of Primitive Data Types

2.11 Types of Arrays

2.12 Creation, concatenation and conversion of a string, changing case of string, character extraction, String Comparison, String Buffer

2.13 Different Operators: Arithmetic, Bitwise, Rational, Logical, Assignment, Conditional, Ternary, Increment and Decrement, Mathematical Functions

2.14 Decision & Control Statements: Selection Statement (if, if...else, switch), Loops(while, do-while, for), Jump statements (break,
continue, return & exit)

OOP Concepts

Object Oriented Programming is a paradigm that provides many concepts such as

inheritance,data binding,polymorphism etc.


Simula is considered as the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as truly object-oriented programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc.Object-Oriented Programmingis a
methodology or paradigm to design a program using classes and objects.Itsimplifies the software
development and maintenance by providing someconcepts:

o Object

Java Programming | UNIT-2 | Prepared By: Debasish Hati, Incharge, DCST


o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

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.

Class

Collection of objectsis called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent objecti.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionalityis known as abstraction. For example: phone
call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

Java Programming | UNIT-2 | Prepared By: Debasish Hati, Incharge, DCST


Benefits of Inheritance
 One of the key benefits of inheritance is to minimize the amount of duplicate code in

an application by sharing common code amongst several subclasses. Where equivalent

code exists in two related classes, the hierarchy can usually be refactored to move the

common code up to a mutual superclass. This also tends to result in a better

organization of code and smaller, simpler compilationunits.

 Inheritance can also make application code more flexible to change because

classesthat inherit from a common superclass can be used interchangeably. If the return type of a

method issuperclass

 Reusability- facility to use public methods of base class without rewriting thesame.

 Extensibility- extending the base class logic as per business logic of the derivedclass.

 Data hiding- base class can decide to keep some data private so that it cannotbe
altered by the derived class

Java Programming | UNIT-2 | Prepared By: Debasish Hati, Incharge, DCST


Procedural and object oriented programming paradigms

Java Programming | UNIT-2 | Prepared By: Debasish Hati, Incharge, DCST


Java Programming- History of Java

The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisionsetc.

For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-


business solutions etc. There are given the major points that describes the history
of java.

1) James Gosling,Mike Sheridan, and Patrick Naughton initiated the Java


language project in June 1991. The small team of sun engineers called Green
Team.

2) Originally designed for small, embedded systems in electronic appliances like


set- topboxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was.gt.

4) After that, it was called Oak and was developed as a part of the Green
project.

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE 8.

1. JDK Alpha and Beta (1995)

2. JDK 1.0 (23rd Jan, 1996)

3. JDK 1.1 (19th Feb, 1997)

4. J2SE 1.2 (8th Dec, 1998)

5. J2SE 1.3 (8th May, 2000)

6. J2SE 1.4 (6th Feb, 2002)

7. J2SE 5.0 (30th Sep,2004)

8. Java SE 6 (11th Dec,2006)

8. Java SE 7 (28th July, 2011)


10.Java SE 8 (18th March,2014)

Java Programming | UNIT-2 | Prepared By: Debasish Hati, Incharge, DCST


Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.

1. Simple

2. Object-Oriented

3. Portable

4. Platform independent

5. Secured

6. Robust

7. Architecture neutral

8. Dynamic

9. Interpreted

10.High Performance

11.Multithreaded

12.Distributed

What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming language developed by James
Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed
the name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation.

Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:

Java Standard Editions (JSE): It is used to create programs for a desktop computer.

Java Enterprise Edition (JEE): It is used to create large programs that run on the server and manages
heavy traffic and complex transactions.

Java Micro Edition (JME): It is used to develop applications for small devices such as set-top boxes,
phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java programming:
Standalone Applications: Java standalone applications uses GUI components such as AWT, Swing,
and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is also known as desktop
alienations.

Enterprise Applications: An application which is distributed in nature is called enterprise


applications.

Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.

Mobile Applications: Java ME is a cross-platform to develop mobile applications which run across
smartphones. Java is a platform for App Development in Android.

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single LineComment
2. Multi LineComment
3. DocumentationComment

Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

1. //This is single linecomment

Example:

public classCommentExample1 {
public static voidmain(String[] args)
{inti=10;//Here, i is a
variableSystem.out.println(i);
}
}

Output:

10

Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/*
This
is

multi line
comment

*/

Example:

public classCommentExample2 {
public static voidmain(String[] args) {
/* Let's declare and print
variable in java.*/
inti=10;
System.out.println(i);

}}

Output:

10
Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you
need to usejavadoc tool.

Syntax:

/**
This
is
documentatio
n comment
*/

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public classCalculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a,int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a,int b){return a-b;}
}

Compile it by javac tool:

javac Calculator.java

Create Documentation API by javadoc tool:

javadoc Calculator.java

Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.

Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:

o Primitive datatypes
o Non-primitive datatypes

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used for simple
flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:

1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves
space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767
(inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example:

short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-
2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example:

int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long
data type is used when you need a range of values more than those provided by int.
Example:

long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.
Example:

float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never be
used for precise values, such as currency. Its default value is 0.0d.
Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff' (or
65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'

DataType DefaultValue Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Java Variable Example: Add Two Numbers


Class Simple{
public static voidmain(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);

}}

Output:20

Variables and Data Types in Java

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

There are two types of data types in java: primitive and non-primitive.

Types of Variable

There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable which is declared inside the method is called local variable.


2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable . It is not
declared as static.

3) Static variable
A variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables in java

classA{
int data=50;//instance variable
static int m=100;//static variable
voidmethod(){
intn=90;//local variable

}//end of class

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the'final' keyword.

Syntax
modifierfinaldataType variableName = value;//global constant

modifierstatic finaldataType variableName = value;//constant within a c

Java Variables
A variable is a container which holds the value while the Java program
is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.
There are two types of data types in Java
: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.
int data=50;//Here data is variable

Types of Variables
There are three types of variables in Java
:
local variable
instance variable
static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within
that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It is not
declared as static
.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of
the static variable and share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
Example to understand the types of variables in java

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Java Variable Example: Add Two Numbers


public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
20

Java Variable Example: Widening


public class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10

Java Variable Example: Overflow


class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
Output:
130
-126

Java Variable Example: Adding Lower Type


class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}}
Output: 20
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a
code. These are predefined words by Java so they cannot be used as a variable or object name or class
name.

List of Java Keywords


A list of Java keywords or reserved words are given below:

1.abstract

: Java abstract keyword is used to declare an abstract class. An abstract class can provide the
implementation of the interface. It can have abstract and non-abstract methods.

2.boolean:

Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False
values only.

3.break

: Java break keyword is used to break the loop or switch statement. It breaks the current flow of
the program at specified conditions.

4.byte

: Java byte keyword is used to declare a variable that can hold 8-bit data values.

5.case

: Java case keyword is used with the switch statements to mark blocks of text.

6.catch

: Java catch keyword is used to catch the exceptions generated by try statements. It must be used
after the try block only.

7.char

: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters

8.class

: Java class keyword is used to declare a class.

9.continue

: Java continue keyword is used to continue the loop. It continues the current flow of the program
and skips the remaining code at the specified condition.

10.default
: Java default keyword is used to specify the default block of code in a switch statement.

11.do

: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.

12.double

: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.

13.else

: Java else keyword is used to indicate the alternative branches in an if statement.

14.enum

: Java enum keyword is used to define a fixed set of constants. Enum constructors are always
private or default.

15.extends

: Java extends keyword is used to indicate that a class is derived from another class or interface.

16.final

: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.

17.finally

: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.

18.float

: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.

19.for

: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iteration is fixed, it is
recommended to use for loop.

20.if

: Java if keyword tests the condition. It executes the if block if the condition is true.

21.implements

: Java implements keyword is used to implement an interface.


22.import

: Java import keyword makes classes and interfaces available and accessible to the current source
code.

23.instanceof

: Java instanceof keyword is used to test whether the object is an instance of the specified class or
implements an interface.

24.int

: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.

25.interface

: Java interface keyword is used to declare an interface. It can have only abstract methods.

26.long

: Java long keyword is used to declare a variable that can hold a 64-bit integer.

27.native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).

28.new

: Java new keyword is used to create new objects.

29.null

: Java null keyword is used to indicate that a reference does not refer to anything. It removes the
garbage value.

30.package

: Java package keyword is used to declare a Java package that includes the classes.

31.private

: Java private keyword is an access modifier. It is used to indicate that a method or variable may
be accessed only in the class in which it is declared.

32.protected

: Java protected keyword is an access modifier. It can be accessible within the package and
outside the package but through inheritance only. It can't be applied with the class.

33.public

: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34.return

: Java return keyword is used to return from a method when its execution is complete.

35.short

: Java short keyword is used to declare a variable that can hold a 16-bit integer.

36.static

: Java static keyword is used to indicate that a variable or method is a class method. The static
keyword in Java is mainly used for memory management.

37.strictfp

: Java strictfp is used to restrict the floating-point calculations to ensure portability.

38.super

: Java super keyword is a reference variable that is used to refer to parent class objects. It can be
used to invoke the immediate parent class method.

39.switch

: The Java switch keyword contains a switch statement that executes code based on test value. The
switch statement tests the equality of a variable against multiple values.

40.synchronized

: Java synchronized keyword is used to specify the critical sections or methods in multithreaded
code.

41.this

: Java this keyword can be used to refer the current object in a method or constructor.

42.throw

: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly
used to throw custom exceptions. It is followed by an instance.

43.throws

: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated
with throws.

44.transient

: Java transient keyword is used in serialization. If you define any data member as transient, it will
not be serialized.

45.try
: Java try keyword is used to start a block of code that will be tested for exceptions. The try block
must be followed by either catch or finally block.

46.void: Java void keyword is used to specify that a method does not have a return value.

47.volatile

: Java volatile keyword is used to indicate that a variable may change asynchronously.

48.while

: Java while keyword is used to start a while loop. This loop iterates a part of the program several
times. If the number of iteration is not fixed, it is recommended to use the while loop.

operators in java

Operatorin java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

o UnaryOperator,
o ArithmeticOperator,
o shiftOperator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o Ternary Operatorand
o AssignmentOperator.

Operators Hierarchy
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
incrementing/decrementing a value by one

negating an expression

inverting the value of a boolean

Java Unary Operator Example: ++ and --

1. public class OperatorExample{


2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}
Output:
10
12
12
10

Java Unary Operator Example 2: ++ and --

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}
Output:
22
21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}
Output:
-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as
basic mathematical operations.

Java Arithmetic Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}
Output:
15

50
2

Java Arithmetic Operator Example: Expression

1. public class OperatorExample{


2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}
Output:
21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number
of times.

Java Left Shift Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}
Output:
40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by the number of bits
specified by the right operand.

Java Right Shift Operator Example

1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2

Java Shift Operator Example: >> vs >>>

1. public class OperatorExample{


2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
Output:
5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}
Output:
false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the first condition is true. It checks the second
condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true

true

true

10

true

11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
2
Another Example:

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
5

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value on its right to
the operand on its left.
Java Assignment Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:
14
16

Java Assignment Operator Example

1. public class OperatorExample{


2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
Output:
13
9
18
9

Java Assignment Operator Example: Adding short

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
Output:
Compile time error
After type cast:

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output: 20

Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are built
using values,variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

 Those that produce a value, i.e. the result of (1 + 1)


 Those that assign a variable, for example (v =10)
 Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators
that modify the state (i.e. memory) of aprogram.

Java Type casting and Type conversion

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This happens
when:

 The two data types arecompatible.


 When we assign value of a smaller data type to a bigger datatype.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform explicit type casting
or narrowing.

 This is useful for incompatible data types where automatic conversion cannot bedone.
 Here, target-type specifies the desired type to convert the specified valueto.

Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)

etc. The java enum constants are static and final implicitly. It is available from JDK 1.5. Java

Enums can be thought of as classes that have fixed set of constants.

Simple example of java enum


classEnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args)
{
for(Season s : Season.values()) System.out.println(s);
}
}

Output:
WINTER

SPRINGSUMMER
FALL

Control Flow Statements

The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The “if” Statement


The “if” statement in Java works exactly like in most programming languages. With the help of “if”
you can choose to execute a specific block of code when a predefined condition is met. The
structure of the “if” statement in Java looks like this:

if(condition) {
// execute this code
}

The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:
Java Control Statements | Control Flow in Java
Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the fundamental features of Java,
which provides a smooth flow of program.
Java provides three types of control flow statements.

1.Decision Making statements

if statements

switch statement

2.Loop statements

do while loop

while loop

for loop

for-each loop

3.Jump statements

break statement

continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. Decision-
making statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and
switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending
upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In
Java, there are four types of if-statements given below:

1.Simple if statement

2.if-else statement

3.if-else-if ladder

4.Nested if-statement
Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
Student.java

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
Output:
Delhi

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Consider the following example.
Student.java

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }
Output:
Delhi

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:

The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java

Cases cannot be duplicate

Default statement is executed when any of the case doesn't match the value of expression. It is
optional.

Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.

While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.

1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }
Output:
2
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates
to true. However, loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax
and condition checking time.

1.for loop

2.while loop

3.do-while loop
Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number of
times, we want to execute the block of code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each
loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }
Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However, if we don't
know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the
initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }

Consider the following example.


Calculation .java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the
do-while loop is given below.

1. do
2. {
3. //statements
4. } while (condition);

Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow of the program and transfer the
control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the
loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java

1. public class Calculation {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }
Output:
0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of
the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.

1. public class ContinueExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5

Creating a Stand-Alone Java Application


1. Write a main method that runs your program. You can write this method anywhere. In
this example, I'll writemymain method in a class called Main that has no other
methods.For example:
public classMain3. {
public static void main(String[]args) {

Game.play();

}}

2. Make sure your code is compiled, and that you have tested it thoroughly.
3. If you're using Windows, you will need to set your path to include
Java, if you haven't done so already. This is a delicate operation. Open
Explorer, and look inside C:\ProgramFiles\Java, and you should see some
version of the JDK. Open this folder, and then open the bin folder. Select
the complete path from the top of the Explorer window, and press Ctrl-C
to copyit.

Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button. Look
at the variables listed for all users, and click on the Path variable. Do not delete the contents of
this variable! Instead, edit the contents by moving the cursor to the right end, entering a
semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go ahead and save
your changes. (If you have any Cmd windows open, you will need to close them.)

4. If you're using Windows, go to the Start menu and type "cmd" to


run a program that brings up a command prompt window.Ifyou're
using a Mac or Linux machine, run the Terminal program to bring up
a commandprompt.
5. In Windows, type dir at the command prompt to list the contents of
the current directory. On a Mac or Linux machine, type ls to dothis.
8. Now we want to change to the directory/folder that contains your compiled code.
Look at the listing of sub-directories within this directory, and identify which one
contains your code. Type cd followed by the name of that directory, to change to that
directory. For example, to change to a directory called Desktop, you would type:

cd Desktop

To change to the parent directory, type:

cd ..

Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains

your .class files.

9. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll
needto recompile your code from the command line, bytyping:

javac -target 1.5 *.java

10. Now we'll create a single JAR file containing all of the files needed to run yourprogram.

How to Compile and Run Java Program


In this section, we learn how to compile and run java program step by step.
Step 1:
Write a program on the notepad and save it with .java (for example, DemoFile.java) extension.

1. class DemoFile
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello!");
6. System.out.println("Java");
7. }
8. }
Step 2:

Open Command Prompt.


Step 3:
Set the directory in which the .java file is saved. In our case, the .java file is saved in C:\\demo.

Step 4:
Use the following command to compile the Java program. It generates a .class file in the same folder. It
also shows an error if any.

1. javac DemoFile.java

Step 5:
Use the following command to run the Java program:

1. java DemoFile
Java vs JavaScript
Java is an object-oriented, general purpose programming language (though it is not entirely object-
oriented as it contains primitive types). Java codes are platform-independent, meaning java codes can run
on any platform which is supporting Java. There is no need for re-compilation of code. Java has become
one of the most used languages for client-server applications. Java code are converted to bytecode which
runs on the Java Virtual Machine (JVM) irrespective of the computer architecture.
Java was initially developed by James Gosling. He developed it at Sun Microsystems which got later
acquired by Oracle. Java was first released in 1995. The latest versions in use are java 11 and Java 12.

Features of Java
The main reason why Java came into existence was that the previously used C++ was a bit cumbersome
and not very feasible for client-server applications.
Following are the features of Java:

It is an object-oriented programming language which makes writing code easy.

Memory allocation takes place at run-time that is why a java program can be compiled even
without the main function.

It is platform independent, which is one of the most significant features of Java. The Java codes
are not compiled directly, they are first converted to a bytecode which can be run on any platform
which has JVM.

Java is an interpreted language which means that the Java code compiles and runs simultaneously.

Java is widely distributed due to its platform independent nature.


What is JavaScript?
JavaScript is a scripting language. It is a high level object-oriented scripting language which is used to
give instructions in run-time environment. It is interpreted language i.e. it is not compiled step by step
rather than instructions are interpreted line by line. This makes JavaScript very dynamic. JavaScript is used
in both client-side and server-side of web applications.
JavaScript along with the use of CSS and HTML makes websites responsive. JavaScript engines are
embedded in many host services, including web servers and databases.

Features of JavaScript
JavaScript is a versatile scripting language used in both server-side as well as client-side
technologies.

It forms basis to many web frameworks like Node.JS, Angular.JS, and React.JS etc.

It is light-weighted as it can be embedded within HTML of website.

It has event based approach to concurrency.

JavaScript is a case-sensitive language that means, if it has two members with same name but
different case, then they will be considered different and also there is a special schema for declaring
variable names.

It follows the object oriented paradigm.

Java vs. JavaScript


For a new programmer, both Java and JavaScript would probably look same but both of them are poles
apart. Even though they share many common attributes like object-oriented paradigm, libraries and
frameworks, still they are quite different when we talk in the context of their use cases.
Following are few differences between Java and JavaScript which would help you to draw a margin
between the two:-
Java JavaScript
Java is strongly typed and has strict rules. Also, JavaScript is weakly typed and does not have
variable type has to be declared before initializing strict rules. There is no need to declare the type
the variable. of variable during initialisation.

JavaScript is object-oriented scripting


Java is object-oriented programming language.
language.

JavaScript code run only on web browsers as


Java programmes are platform independent. They
they were developed to run only on web
can run on any device having Java Virtual Machine.
browsers.

Java objects are class based which means you have


JavaScript objects are prototype based.
got to make a class in order to make a program.

JavaScript files have extension ".js". These are


Java files have ".java" extension. These files are not compiled instead they are interpreted by
converted to bytecode which are executed by JVM. the JavaScript interpreter which is present in
every browser.

Java is a standalone language which means it does JavaScript is contained in web pages and is
not require any other thing to be embedded in. embedded in HTML content.

JavaScript is memory optimised and therefore


Java programs require large amount of memory.
is used in web pages.

When facing concurrency, then Java uses thread JavaScript uses event based approach to tackle
based approach to solve it. concurrency.

Java is vividly used for Android application JavaScript is vividly used for web
development development.

What is Java IDE?


Java IDE (Integrated Development Environment) is a software application that enables users to write and debug Java
programs more easily. Most IDEs have features such as syntax highlighting and code completion that helps users to code more
easily. Usually, Java IDEs include a code editor, a compiler, a debugger, and an interpreter that the developer may access via
a single graphical user interface. Java IDEs also provide language-specific elements such as Maven, Ant building tools, Junit,
and TestNG for testing.

The Java IDE or Integrated Development Environment provides considerable support for the application development process.
Through using them, we can save time and effort and set up a standard development process for the team or company. Eclipse,
NetBeans, IntelliJ IDEA, and many other IDE's are most popular in the Java IDE's that can be used according to our
requirements. In this topic, we will discuss the best Java IDE's that are used by the users.

Best Java IDEs


The following are the best Java IDEs that are mostly used in the world:

Eclipse
NetBeans
IntelliJ IDEA
BlueJ
JCreator
JDeveloper
MyEclipse
Greenfoot
DrJava
Xcode
Codenvy
Difference between JDK, JRE, and JVM
We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See
the brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see
the differences between the JDK, JRE, and JVM.

JVM
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. It can also run those programs which are written in other languages and compiled to Java
bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.
The JVM performs the following main tasks:

Loads code

Verifies code

Executes code

Provides runtime environment


More Details.

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of
libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform

Enterprise Edition Java Platform

Micro Edition Java Platform


The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.

C++ vs Java
There are many differences and similarities between the C++ programming language and Java. A list of
top differences between C++ and Java are given below:

Comparison Index C++ Java


Platform-independent C++ is platform-dependent. Java is platform-independent.

Java is mainly used for application


C++ is mainly used for programming. It is widely used in
Mainly used for
system programming. Windows-based, web-based,
enterprise, and mobile applications.

Java was designed and created as an


C++ was designed for
interpreter for printing systems but
systems and applications
later extended as a support network
Design Goal programming. It was an
computing. It was designed to be
extension of the C
easy to use and accessible to a
programming language.
broader audience.

C++ supports Java doesn't support the goto


Goto
the goto statement. statement.

Multiple inheritance C++ supports multiple Java doesn't support multiple


inheritance. inheritance through class. It can be
achieved by using interfaces in java.

C++ supports operator Java doesn't support operator


Operator Overloading
overloading. overloading.

Java supports pointer internally.


C++ supports pointers. You
However, you can't write the pointer
Pointers can write a pointer program
program in java. It means java has
in C++.
restricted pointer support in java.

Java uses both compiler and


C++ uses compiler only. interpreter. Java source code is
C++ is compiled and run converted into bytecode at
using the compiler which compilation time. The interpreter
Compiler and Interpreter
converts source code into executes this bytecode at runtime and
machine code so, C++ is produces output. Java is interpreted
platform dependent. that is why it is platform-
independent.

Call by Value and Call by C++ supports both call by Java supports call by value only.
reference value and call by reference. There is no call by reference in java.

C++ supports structures and Java doesn't support structures and


Structure and Union
unions. unions.

C++ doesn't have built-in


support for threads. It relies
Thread Support Java has built-in thread support.
on third-party libraries for
thread support.

C++ doesn't support Java supports documentation


Documentation comment
documentation comments. comment (/** ... */) to create
documentation for java source code.

C++ supports virtual Java has no virtual keyword. We can


keyword so that we can override all non-static methods by
Virtual Keyword
decide whether or not to default. In other words, non-static
override a function. methods are virtual by default.

Java supports unsigned right shift


>>> operator that fills zero at the top
C++ doesn't support >>>
unsigned right shift >>> for the negative numbers. For
operator.
positive numbers, it works same like
>> operator.

Java always uses a single inheritance


tree because all classes are the child
C++ always creates a new
Inheritance Tree of the Object class in Java. The
inheritance tree.
Object class is the root of
the inheritance tree in java.

Java is not so interactive with


Hardware C++ is nearer to hardware.
hardware.

Java is also an object-


C++ is an object-oriented oriented language. However,
language. However, in the C everything (except fundamental
Object-oriented
language, a single root types) is an object in Java. It is a
hierarchy is not possible. single root hierarchy as everything
gets derived from java.lang.Object.

Note

Java doesn't support default arguments like C++.

Java does not support header files like C++. Java uses the import keyword to include different
classes and methods.
JVM (Java Virtual Machine) Architecture
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM
It is:

1.A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Oracle
and other companies.

2.An implementation Its implementation is known as JRE (Java Runtime Environment).

3.Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.

What it does
The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment


JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine
etc.
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on
1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the
sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an
array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java


There are two types of array.

Single Dimensional Array

Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Output:
10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization


Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation


2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Output:
33
3
4
5

For-each Loop for Java Array


We can also print the Java array using for-each loop
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes
the body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
1. //Java Program to print the array elements using for-each loop
2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}
Output:
33
3
4
5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array


2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}

Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.

1. //Java Program to demonstrate the way of passing an anonymous array


2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to method
12. }}
Output:
10
22
44
66

Returning Array from the Method


We can also return an array from the method in Java.

1. //Java Program to return an array from the method


2. class TestReturnArray{
3. //creating method which returns an array
4. static int[] get(){
5. return new int[]{10,30,50,90,60};
6. }
7.
8. public static void main(String args[]){
9. //calling method which returns an array
10. int arr[]=get();
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++)
13. System.out.println(arr[i]);
14. }}
Output:
10
30
50
90
60

ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.

1. //Java Program to demonstrate the case of


2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]);
8. }
9. }}
Test it Now

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now

Output:
1 2 3
2 4 5
4 4 5

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is
an array of arrays with different number of columns.

1. //Java Program to illustrate the jagged array


2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<arr.length; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<arr.length; i++){
17. for (int j=0; j<arr[i].length; j++){
18. System.out.print(arr[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. }
23. }
Output:
0 1 2
3 4 5 6
7 8

What is the class name of Java array?


In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by
getClass().getName() method on the object.

1. //Java Program to get the class name of array in Java


2. class Testarray4{
3. public static void main(String args[]){
4. //declaration and initialization of array
5. int arr[]={4,4,5};
6. //getting the class name of Java array
7. Class c=arr.getClass();
8. String name=c.getName();
9. //printing the class name of Java array
10. System.out.println(name);
11.
12. }}
Copying a Java Array
We can copy an array to another by the arraycopy() method of System class.
Syntax of arraycopy method

1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of Copying an Array in Java

1. //Java Program to copy a source array into a destination array in Java


2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
6. 'i', 'n', 'a', 't', 'e', 'd' };
7. //declaring a destination array
8. char[] copyTo = new char[7];
9. //copying array using System.arraycopy() method
10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
11. //printing the destination array
12. System.out.println(String.valueOf(copyTo));
13. }
14. }
Output:
caffein

Cloning an Array in Java


Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create
the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the
actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java
array which means it copies the references.

1. //Java Program to clone the array


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. System.out.println("Printing original array:");
6. for(int i:arr)
7. System.out.println(i);
8.
9. System.out.println("Printing clone of the array:");
10. int carr[]=arr.clone();
11. for(int i:carr)
12. System.out.println(i);
13.
14. System.out.println("Are both equal?");
15. System.out.println(arr==carr);
16.
17. }}
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false

Addition of 2 Matrices in Java


Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java


2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}
Output:
2 6 8
6 8 10

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of
the second matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

1. //Java Program to multiply two matrices


2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}

Output:
6 6 6
12 12 12
18 18 18

PROGRAMMING PROBLEMS

Program to copy all elements of one array into another array


In this program, we need to copy all the elements of one array into another. This can be accomplished by
looping through the first array and store the elements of the first array into the second array at the
corresponding position.

1. ARRAY 1
2. 1 2 3 4 5
3.
4. ARRAY 2
5. 1 2 3 4 5

Algorithm
STEP 1: START

STEP 2: INITIALIZE arr1[] ={1, 2, 3, 4, 5}

STEP 3: CREATE arr2[] of size arr1[].


STEP 4: COPY elements of arr1[] to arr2[]

STEP 5: REPEAT STEP 6 UNTIL (i<arr1.length)

STEP 6: arr2[i] =arr1[i]

STEP 7: DISPLAY elements of arr1[].

STEP 8: REPEAT STEP 9 UNTIL (i<arr1.length)

STEP 9: PRINT arr1[i]

STEP 10: DISPLAY elements of arr2[].

STEP 11: REPEAT STEP 12 UNTIL (i<arr2.length)

STEP 12: PRINT arr2[i].

STEP 13: END

Program:
1. public class CopyArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr1 = new int [] {1, 2, 3, 4, 5};
5. //Create another array arr2 with size of arr1
6. int arr2[] = new int[arr1.length];
7. //Copying all elements of one array into another
8. for (int i = 0; i < arr1.length; i++) {
9. arr2[i] = arr1[i];
10. }
11. //Displaying elements of array arr1
12. System.out.println("Elements of original array: ");
13. for (int i = 0; i < arr1.length; i++) {
14. System.out.print(arr1[i] + " ");
15. }
16.
17. System.out.println();
18.
19. //Displaying elements of array arr2
20. System.out.println("Elements of new array: ");
21. for (int i = 0; i < arr2.length; i++) {
22. System.out.print(arr2[i] + " ");
23. }
24. }
25. }
Output:
Elements of original array
1 2 3 4 5
Elements of new array:
1 2 3 4 5

Program to find the frequency of each element in the array


In this program, we have an array of elements to count the occurrence of its each element. One of the
approaches to resolve this problem is to maintain one array to store the counts of each element of the array.
Loop through the array and count the occurrence of each element as frequency and store it in another array
fr.

1. 1 2 8 3 2 2 2 5 1
In the given array, 1 has appeared two times so its frequency be 2 and 2 has appeared four times so have
frequency 4 and so on.

Algorithm
STEP 1: START

STEP 2: INITIALIZE arr[] ={1, 2, 8, 3, 2, 2, 2, 5, 1 }.

STEP 3: CREATE fr[] of arr[] length.

STEP 4: SET visited = -1.

STEP 5: REPEAT STEP 6 to STEP 9 for(i=0;i<arr.length;i++)

STEP 6: SET count = 1

STEP 7: REPEAT STEP 8 for(j=i+1;j<arr.length;j++)

STEP 8: if(arr[i]==arr[j]) then


count++
fr[j] =visited

STEP 9: if(fr[i]!=visited) then


fr[i]=count

STEP 10: PRINT "------------"

STEP 11: PRINT "Element | Frequency"

STEP 12: PRINT "-------------"


STEP 13: REPEAT STEP 14 for(i=0;i<fr.length;i++)

STEP 14: if(fr[i]!=visited) then


PRINT arr[i] and fr[i]

STEP 15: PRINT "-------------"

STEP 16: END

Program:
1. public class Frequency {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
5. //Array fr will store frequencies of element
6. int [] fr = new int [arr.length];
7. int visited = -1;
8. for(int i = 0; i < arr.length; i++){
9. int count = 1;
10. for(int j = i+1; j < arr.length; j++){
11. if(arr[i] == arr[j]){
12. count++;
13. //To avoid counting same element again
14. fr[j] = visited;
15. }
16. }
17. if(fr[i] != visited)
18. fr[i] = count;
19. }
20.
21. //Displays the frequency of each element present in array
22. System.out.println("---------------------------------------");
23. System.out.println(" Element | Frequency");
24. System.out.println("---------------------------------------");
25. for(int i = 0; i < fr.length; i++){
26. if(fr[i] != visited)
27. System.out.println(" " + arr[i] + " | " + fr[i]);
28. }
29. System.out.println("----------------------------------------");
30. }}
Output:
----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------

Program to print the duplicate elements of an array


In this program, we need to print the duplicate elements present in the array. This can be done through two
loops. The first loop will select an element and the second loop will iteration through the array by
comparing the selected element with other elements. If a match is found, print the duplicate element.

In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2)
present at index 1. So, duplicate elements in the above array are 2, 3 and 8.

Algorithm
STEP 1: START

STEP 2: INITIALIZE arr[]= {1, 2, 3, 4, 2, 7, 8, 8, 3}.

STEP 3: PRINT "Duplicate elements in given array:"

STEP 4: REPEAT STEP 5 to STEP 7 for(i=0; i<arr.length; i++)

STEP 5: REPEAT STEP 6 and STEP 7 for(j=i+1; j<arr.length; j++)

STEP 6: if(arr[i] == arr[j])

STEP 7: PRINT arr[j]

STEP 8: END

Program:
1. public class DuplicateElement {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
5. System.out.println("Duplicate elements in given array: ");
6. //Searches for duplicate element
7. for(int i = 0; i < arr.length; i++) {
8. for(int j = i + 1; j < arr.length; j++) {
9. if(arr[i] == arr[j])
10. System.out.println(arr[j]);
11. }
12. }
13. }
14. }
Output:
Duplicate elements in given array:
2
3
8

Program to print the largest element in an array


In this program, we need to find out the largest element present in the array and display it. This can be
accomplished by looping through the array from start to end by comparing max with all the elements of an
array. If any of element is greater than max, then store a value of the element in max. Initially, max will hold
the value of the first element. At the end of the loop, max represents the largest element in the array.

In the above array, initially, max will hold the value 25. In the 1st iteration, max will be compared with 11,
since 11 is less than max. Max will retain its value. In the next iteration, it will be compared to 7, 7 is also
less than max, no change will be made to the max. Now, max will be compared to 75. 75 is greater than max
so that max will hold the value of 75. Continue this process until the end of the array is reached. At the end
of the loop, max will hold the largest element in the array.

Algorithm
1.STEP 1: START

2.STEP 2: INITIALIZE arr[] = {25, 11, 7, 75, 56}

3.STEP 3: max = arr[0]

4.STEP 4: REPEAT STEP 5 for(i=0; i< arr.length; i++)

5.STEP 5: if(arr[i]>max) max=arr[i]

6.STEP 6: PRINT "Largest element in given array:"


7.STEP 7: PRINT max

8.STEP 8: END

Program:
1. public class LargestElement_array {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {25, 11, 7, 75, 56};
6. //Initialize max with first element of array.
7. int max = arr[0];
8. //Loop through the array
9. for (int i = 0; i < arr.length; i++) {
10. //Compare elements of array with max
11. if(arr[i] > max)
12. max = arr[i];
13. }
14. System.out.println("Largest element present in given array: " + max);
15. }
16. }
Output:
Largest element present in given array: 75

Java Program to sort the elements of an array in ascending


order
In this program, we need to sort the given array in ascending order such that elements will be arranged from
smallest to largest. This can be achieved through two loops. The outer loop will select an element, and inner
loop allows us to compare selected element with rest of the elements.
Elements will be sorted in such a way that the smallest element will appear on extreme left which in this
case is 1. The largest element will appear on extreme right which in this case is 8.

Algorithm
STEP 1: START

STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.

STEP 3: SET temp =0

STEP 4: PRINT "Elements of Original Array"

STEP 5: REPEAT STEP 6 UNTIL i<arr.length


//for(i=0; i<arr.length; i++)

STEP 6: PRINT arr[i]

STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length


//for(i=0; i<arr.length; i++ )

STEP 8: REPEAT STEP 9 UNTIL j<arr.length


//for(j=i+1;j<arr.length;j++)

STEP 9: if(arr[i]>arr[j]) then


temp = arr[i]
arr[i]=arr[j]
arr[j]=temp

STEP 10: PRINT new line

STEP 11: PRINT "Elements of array sorted in ascending order"

STEP 12: REPEAT STEP 13 UNTIL i<arr.length


//for(i=0;i<arr.length;i++)

STEP 13: PRINT arr[i]

STEP 14: END

Program:
1. public class SortAsc {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {5, 2, 8, 7, 1};
6. int temp = 0;
7.
8. //Displaying elements of original array
9. System.out.println("Elements of original array: ");
10. for (int i = 0; i < arr.length; i++) {
11. System.out.print(arr[i] + " ");
12. }
13.
14. //Sort the array in ascending order
15. for (int i = 0; i < arr.length; i++) {
16. for (int j = i+1; j < arr.length; j++) {
17. if(arr[i] > arr[j]) {
18. temp = arr[i];
19. arr[i] = arr[j];
20. arr[j] = temp;
21. }
22. }
23. }
24.
25. System.out.println();
26.
27. //Displaying elements of array after sorting
28. System.out.println("Elements of array sorted in ascending order: ");
29. for (int i = 0; i < arr.length; i++) {
30. System.out.print(arr[i] + " ");
31. }
32. }
33. }
Output:
Elements of original array:
5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8

Java Program to transpose matrix


Converting rows of a matrix into columns and columns of a matrix into row is called transpose of a matrix.
Let's see a simple example to transpose a matrix of 3 rows and 3 columns.
1. public class MatrixTransposeExample{
2. public static void main(String args[]){
3. //creating a matrix
4. int original[][]={{1,3,4},{2,4,3},{3,4,5}};
5.
6. //creating another matrix to store transpose of a matrix
7. int transpose[][]=new int[3][3]; //3 rows and 3 columns
8.
9. //Code to transpose a matrix
10. for(int i=0;i<3;i++){
11. for(int j=0;j<3;j++){
12. transpose[i][j]=original[j][i];
13. }
14. }
15.
16. System.out.println("Printing Matrix without transpose:");
17. for(int i=0;i<3;i++){
18. for(int j=0;j<3;j++){
19. System.out.print(original[i][j]+" ");
20. }
21. System.out.println();//new line
22. }
23. System.out.println("Printing Matrix After Transpose:");
24. for(int i=0;i<3;i++){
25. for(int j=0;j<3;j++){
26. System.out.print(transpose[i][j]+" ");
27. }
28. System.out.println();//new line
29. }
30. }}
Output:
Printing Matrix without transpose:
1 3 4
2 4 3
3 4 5
Printing Matrix After Transpose:
1 2 3
3 4 4
4 3 5
Java Program to subtract the two matrices
In this program, we need to get the result of subtraction of two matrices.
Two matrices A and B can be subtracted if and only if they have same dimensions that are, the same number
of rows and columns. It is not possible to subtract a 2 × 3 matrix from a 3 × 2 matrix. Subtraction of two
matrices can be performed by subtracting their corresponding elements as

1. (A - B)<sub>ij</sub>= A<sub>ij</sub> - B<sub>ij</sub>

Subtraction of two matrices can be performed by looping through the first and second matrix. Calculating
the difference between their corresponding elements and store the result in the third matrix.

Algorithm
STEP 1: START

STEP 2: DEFINE rows, cols

STEP 3: INITIALIZE first matrix a[][] ={{4,5,6},{3,4,1}, {1,2,3}}

STEP 4: INITIALIZE second matrix b[][] ={{2,0,3}, {2,3,1}{1,1,1}}

STEP 5: rows = a.length

STEP 6: cols = a[0].length

STEP 7: DEFINE diff[][]

STEP 8: REPEAT STEP 9 to STEP 10 UNTIL i<rows


//for(i=0;i<rows; i++)

STEP 9: REPEAT STEP 10 UNTIL j<cols


//for(j=0;j<cols; j++)

STEP 10: diff[i][j] =a[i][j] - b[i][j]

STEP 11: PRINT "Subtraction of two matrices:"

STEP 12: REPEAT STEP 13 to STEP 14 UNTIL i<rows


//for(i=0;i<rows; i++)
STEP 13: REPEAT STEP 14 UNTIL j<cols
//for(j=0; j<cols; j++)

STEP 13: PRINT diff[i][j]

STEP 14: PRINT new line

STEP 15: END

Program:
1. public class Sub_Matrix
2. {
3. public static void main(String[] args) {
4. int rows, cols;
5.
6. //Initialize matrix a
7. int a[][] = {
8. {4, 5, 6},
9. {3, 4, 1},
10. {1, 2, 3}
11. };
12.
13. //Initialize matrix b
14. int b[][] = {
15. {2, 0, 3},
16. {2, 3, 1},
17. {1, 1, 1}
18. };
19.
20. //Calculates number of rows and columns present in given matrix
21. rows = a.length;
22. cols = a[0].length;
23.
24. //Array diff will hold the result
25. int diff[][] = new int[rows][cols];
26.
27. //Performs subtraction of matrices a and b. Store the result in matrix diff
28. for(int i = 0; i < rows; i++){
29. for(int j = 0; j < cols; j++){
30. diff[i][j] = a[i][j] - b[i][j];
31. }
32. }
33.
34. System.out.println("Subtraction of two matrices: ");
35. for(int i = 0; i < rows; i++){
36. for(int j = 0; j < cols; j++){
37. System.out.print(diff[i][j] + " ");
38. }
39. System.out.println();
40. }
41. }
42. }
Output:
Subtraction of two matrices:
1 5 3
1 1 0
0 1 2

Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:

1. String s="javatpoint";

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.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces
.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder
classes implement it. It means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
We will discuss immutable string later. Let's first understand what String in Java is and how to create the
String object.

What is String 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.

How to create a string object?


There are two ways to create String object:

1.By string literal


2.By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. 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. For example:

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

In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".

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).

2) By new keyword
1. 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).
Java String Example
StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on
console using println() method.

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No. Method Description
1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale.

5 String substring(int beginIndex) It returns substring for given begin index.

It returns substring for given begin index and end


6 String substring(int beginIndex, int endIndex)
index.

It returns true or false after matching the sequence


7 boolean contains(CharSequence s)
of char value.

8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.


static String join(CharSequence delimiter, Iterable<? extends
9 It returns a joined string.
CharSequence> elements)

It checks the equality of string with the given


10 boolean equals(Object another)
object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

It replaces all occurrences of the specified char


13 String replace(char old, char new)
value.

It replaces all occurrences of the specified


14 String replace(CharSequence old, CharSequence new)
CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

It returns the specified char value index starting


20 int indexOf(int ch, int fromIndex)
with given index.

21 int indexOf(String substring) It returns the specified substring index.

It returns the specified substring index starting with


22 int indexOf(String substring, int fromIndex)
given index.

23 String toLowerCase() It returns a string in lowercase.

It returns a string in lowercase using specified


24 String toLowerCase(Locale l)
locale.

25 String toUpperCase() It returns a string in uppercase.

It returns a string in uppercase using specified


26 String toUpperCase(Locale l)
locale.

27 String trim() It removes beginning and ending spaces of this


string.

It converts given type into string. It is an overloaded


28 static String valueOf(int value)
method.

Java String charAt()


The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this
string length or a negative number.

Syntax

1. public char charAt(int index)


The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index
position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or
greater than this string length.
Specified by
CharSequence interface, located inside java.lang package.

Internal implementation

1. public char charAt(int index) {


2. if ((index < 0) || (index >= value.length)) {
3. throw new StringIndexOutOfBoundsException(index);
4. }
5. return value[index];
6. }

Java String charAt() Method Examples


Let's see Java program related to string in which we will use charAt() method that perform some operation
on the give string.
FileName: CharAtExample.java

1. public class CharAtExample{


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

Let's see the example of the charAt() method where we are passing a greater index value. In such a case, it
throws StringIndexOutOfBoundsException at run time.
FileName: CharAtExample.java

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="javatpoint";
4. char ch=name.charAt(10);//returns the char value at the 10th index
5. System.out.println(ch);
6. }}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Accessing First and Last Character by Using the charAt() Method


Let's see a simple example where we are accessing first and last character from the provided string.
FileName: CharAtExample3.java
1. public class CharAtExample3 {
2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. int strLength = str.length();
5. // Fetching first character
6. System.out.println("Character at 0 index is: "+ str.charAt(0));
7. // The last Character is present at the string length-1 index
8. System.out.println("Character at last index is: "+ str.charAt(strLength-1));
9. }
10. }
Output:
Character at 0 index is: W
Character at last index is: l

Print Characters Presented at Odd Positions by Using the charAt()


Method
Let's see an example where we are accessing all the elements present at odd index.
FileName: CharAtExample4.java

1. public class CharAtExample4 {


2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. for (int i=0; i<=str.length()-1; i++) {
5. if(i%2!=0) {
6. System.out.println("Char at "+i+" place "+str.charAt(i));
7. }
8. }
9. }
10. }
Output:
Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place
Char at 23 place o
Char at 25 place t
Char at 27 place l
The position such as 7 and 21 denotes the space.

Counting Frequency of a character in a String by Using the charAt()


Method
Let's see an example in which we are counting frequency of a character in the given string.
FileName: CharAtExample5.java

1. public class CharAtExample5 {


2. public static void main(String[] args) {
3. String str = "Welcome to Javatpoint portal";
4. int count = 0;
5. for (int i=0; i<=str.length()-1; i++) {
6. if(str.charAt(i) == 't') {
7. count++;
8. }
9. }
10. System.out.println("Frequency of t is: "+count);
11. }
12. }
Output:
Frequency of t is: 4

Counting the Number of Vowels in a String by Using the chatAt()


Method
Let's see an example where we are counting the number of vowels present in a string with the help
of the charAt() method.
FileName: CharAtExample6.java

1. // import statement
2. import java.util.*;
3.
4. public class CharAtExample6
5. {
6. ArrayList<Character> al;
7.
8. // constructor for creating and
9. // assigning values to the ArrayList al
10. CharAtExample6()
11. {
12. al = new ArrayList<Character>();
13. al.add('A'); al.add('E');
14. al.add('a'); al.add('e');
15. al.add('I'); al.add('O');
16. al.add('i'); al.add('o');
17. al.add('U'); al.add('u');
18. }
19.
20. // a method that checks whether the character c is a vowel or not
21. private boolean isVowel(char c)
22. {
23. for(int i = 0; i < al.size(); i++)
24. {
25. if(c == al.get(i))
26. {
27. return true;
28. }
29. }
30. return false;
31. }
32. // a method that calculates vowels in the String s
33. public int countVowels(String s)
34. {
35. int countVowel = 0; // store total number of vowels
36. int size = s.length(); // size of string
37. for(int j = 0; j < size; j++)
38. {
39. char c = s.charAt(j);
40. if(isVowel(c))
41. {
42. // vowel found!
43. // increase the count by 1
44. countVowel = countVowel + 1;
45. }
46. }
47.
48. return countVowel;
49. }
50.
51. // main method
52. public static void main(String argvs[])
53. {
54. // creating an object of the class CharAtExample6
55. CharAtExample6 obj = new CharAtExample6();
56.
57. String str = "Javatpoint is a great site for learning Java.";
58.
59. int noOfVowel = obj.countVowels(str);
60.
61. System.out.println("String: " + str);
62.
63. System.out.println("Total number of vowels in the string are: "+ noOfVowel + "\n");

64.
65. str = "One apple in a day keeps doctor away.";
66.
67. System.out.println("String: " + str);
68.
69. noOfVowel = obj.countVowels(str);
70.
71. System.out.println("Total number of vowels in the string are: "+ noOfVowel);
72. }
73. }
Output:
String: Javatpoint is a great site for learning Java.
Total number of vowels in the string are: 16

String: One apple in a day keeps doctor away.


Total number of vowels in the string are: 13

Java String length()


The Java String class length() method finds the length of a string. The length of the Java string is
the same as the Unicode code units of the string.
Signature
The signature of the string length() method is given below:

1. public int length()

Specified by
CharSequence interface

Returns
Length of characters. In other words, the total number of characters present in the string.

Internal implementation

1. public int length() {


2. return value.length;
3. }
The String class internally uses a char[] array to store the characters. The length variable of the
array is used to find the total number of elements present in the array. Since the Java String class
uses this char[] array internally; therefore, the length variable can not be exposed to the outside
world. Hence, the Java developers created the length() method, the exposes the value of the length
variable. One can also think of the length() method as the getter() method, that provides a value of
the class field to the user. The internal implementation clearly depicts that the length() method
returns the value of then the length variable.

Java String length() method example


FileName: LengthExample.java

1. public class LengthExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. String s2="python";
5. System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string
6. System.out.println("string length is: "+s2.length());//6 is the length of python string
7. }}
Output:
string length is: 10
string length is: 6

Java String length() Method Example 2


Since the length() method gives the total number of characters present in the string; therefore, one
can also check whether the given string is empty or not.
FileName: LengthExample2.java

1. public class LengthExample2 {


2. public static void main(String[] args) {
3. String str = "Javatpoint";
4. if(str.length()>0) {
5. System.out.println("String is not empty and length is: "+str.length());
6. }
7. str = "";
8. if(str.length()==0) {
9. System.out.println("String is empty now: "+str.length());
10. }
11. }
12. }
Output:
String is not empty and length is: 10
String is empty now: 0

Java String length() Method Example 3


The length() method is also used to reverse the string.
FileName: LengthExample3.java

1. class LengthExample3
2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = "Welcome To JavaTpoint";
7. int size = str.length();
8.
9. System.out.println("Reverse of the string: " + "'" + str + "'" + " is");
10.
11. for(int i = 0; i < size; i++)
12. {
13. // printing in reverse order
14. System.out.print(str.charAt(str.length() - i - 1));
15. }
16.
17. }
18. }
Output:
Reverse of the string: 'Welcome To JavaTpoint' is
tniopTavaJ oT emocleW

Java String length() Method Example 4


The length() method can also be used to find only the white spaces present in the string. Observe
the following example.
FileName: LengthExample4.java

1. public class LengthExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str = " Welcome To JavaTpoint ";
7. int sizeWithWhiteSpaces = str.length();
8.
9. System.out.println("In the string: " + "'" + str + "'");
10.
11. str = str.replace(" ", "");
12. int sizeWithoutWhiteSpaces = str.length();
13.
14. // calculating the white spaces
15. int noOfWhieSpaces = sizeWithWhiteSpaces - sizeWithoutWhiteSpaces;
16.
17. System.out.print("Total number of whitespaces present are: " + noOfWhieSpaces);
18. }
19. }
Output:
In the string: ' Welcome To JavaTpoint '
Total number of whitespaces present are: 4

Java String substring()


The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method where beginIndex
is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the
endIndex starts from 1.
There are two types of substring methods in Java string.
Signature

1. public String substring(int startIndex) // type - 1


2. and
3. public String substring(int startIndex, int endIndex) // type - 2
If we don't specify endIndex, the method will return all the characters from startIndex x

Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive

Returns
specified string

Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.

if the start index is negative value

end index is lower than starting index.

Either starting or ending index is greater than the total number of characters present in the
string.

Internal implementation substring(int beginIndex)

1. public String substring(int beginIndex) {


2. if (beginIndex < 0) {
3. throw new StringIndexOutOfBoundsException(beginIndex);
4. }
5. int subLen = value.length - beginIndex;
6. if (subLen < 0) {
7. throw new StringIndexOutOfBoundsException(subLen);
8. }
9. return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
10. }

Internal implementation substring(int beginIndex, int endIndex)

1. public String substring(int beginIndex, int endIndex)


2. {
3. if (beginIndex < 0)
4. {
5. throw new StringIndexOutOfBoundsException(beginIndex);
6. }
7. if (endIndex > value.length)
8. {
9. throw new StringIndexOutOfBoundsException(endIndex);
10. }
11. int subLen = endIndex - beginIndex;
12. if (subLen < 0)
13. {
14. throw new StringIndexOutOfBoundsException(subLen);
15. }
16. return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(valu
e, beginIndex, subLen);
17. }

Java String substring() method example


FileName: SubstringExample.java

1. public class SubstringExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}
Output:
va
vatpoint

Java String substring() Method Example 2


FileName: SubstringExample2.java

1. public class SubstringExample2 {


2. public static void main(String[] args) {
3. String s1="Javatpoint";
4. String substr = s1.substring(0); // Starts with 0 and goes to end
5. System.out.println(substr);
6. String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
7. System.out.println(substr2);
8. String substr3 = s1.substring(5,15); // Returns Exception
9. }
10. }
Output:
Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5,
end 15, length 10

Applications of substring() Method


1) The substring() method can be used to do some prefix or suffix extraction. For example, we can
have a list of names, and it is required to filter out names with surname as "singh". The following
program shows the same.
FileName: SubstringExample3.java

1. public class SubstringExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6. String str[] =
7. {
8. "Praveen Kumar",
9. "Yuvraj Singh",
10. "Harbhajan Singh",
11. "Gurjit Singh",
12. "Virat Kohli",
13. "Rohit Sharma",
14. "Sandeep Singh",
15. "Milkha Singh"
16. };
17.
18. String surName = "Singh";
19. int surNameSize = surName.length();
20.
21. int size = str.length;
22.
23. for(int j = 0; j < size; j++)
24. {
25. int length = str[j].length();
26. // extracting the surname
27. String subStr = str[j].substring(length - surNameSize);
28.
29. // checks whether the surname is equal to "Singh" or not
30. if(subStr.equals(surName))
31. {
32. System.out.println(str[j]);
33. }
34. }
35.
36. }
37. }
Output:
Yuvraj Singh
Harbhajan Singh
Gurjit Singh
Sandeep Singh
Milkha Singh
2) The substring() method can also be used to check whether a string is a palindrome or not.
FileName: SubstringExample4.java

1. public class SubstringExample4


2. {
3. public boolean isPalindrome(String str)
4. {
5. int size = str.length();
6.
7. // handling the base case
8. if(size == 0 || size == 1)
9. {
10. // an empty string
11. // or a string of only one character
12. // is always a palindrome
13. return true;
14. }
15. String f = str.substring(0, 1);
16. String l = str.substring(size - 1);
17. // comparing first and the last character of the string
18. if(l.equals(f))
19. {
20. // recursively finding the solution using the substring() method
21. // reducing the number of characters of the by 2 for the next recursion
22. return isPalindrome(str.substring(1, size - 1));
23. }
24. return false;
25. }
26. // main method
27. public static void main(String argvs[])
28. {
29. // instantiating the class SubstringExample4
30. SubstringExample4 obj = new SubstringExample4();
31. String str[] =
32. {
33. "madam",
34. "rock",
35. "eye",
36. "noon",
37. "kill"
38. };
39. int size = str.length;
40.
41. for(int j = 0; j < size; j++)
42. {
43. if(obj.isPalindrome(str[j]))
44. {
45. System.out.println(str[j] + " is a palindrome.");
46. }
47. else
48. {
49. System.out.println(str[j] + " is not a palindrome.");
50. }
51. }
52. }
53. }
Output:
madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.

Java String substring()


The Java String class substring() method returns a part of the string.
We pass beginIndex and endIndex number position in the Java substring method where beginIndex
is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the
endIndex starts from 1.
There are two types of substring methods in Java string.

Signature

1. public String substring(int startIndex) // type - 1 and


2. public String substring(int startIndex, int endIndex) // type - 2
If we don't specify endIndex, the method will return all the characters from startIndex.

Parameters
startIndex : starting index is inclusive
endIndex : ending index is exclusive

Returns
specified string

Exception Throws
StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.

if the start index is negative value

end index is lower than starting index.

Either starting or ending index is greater than the total number of characters present in the
string.

Internal implementation substring(int beginIndex)

1. public String substring(int beginIndex) {


2. if (beginIndex < 0) {
3. throw new StringIndexOutOfBoundsException(beginIndex);
4. }
5. int subLen = value.length - beginIndex;
6. if (subLen < 0) {
7. throw new StringIndexOutOfBoundsException(subLen);
8. }
9. return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
10. }

Java String substring() method example


FileName: SubstringExample.java

1. public class SubstringExample{


2. public static void main(String args[]){
3. String s1="javatpoint";
4. System.out.println(s1.substring(2,4));//returns va
5. System.out.println(s1.substring(2));//returns vatpoint
6. }}
Test it Now

Output:
va
vatpoint

Java String substring() Method Example 2


FileName: SubstringExample2.java

1. public class SubstringExample2 {


2. public static void main(String[] args) {
3. String s1="Javatpoint";
4. String substr = s1.substring(0); // Starts with 0 and goes to end
5. System.out.println(substr);
6. String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
7. System.out.println(substr2);
8. String substr3 = s1.substring(5,15); // Returns Exception
9. }
10. }
Output:
Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin
5, end 15, length 10

Java String concat


The Java String class concat() method combines specified string at the end of this string. It returns
a combined string. It is like appending another string.

Signature
The signature of the string concat() method is given below:

1. public String concat(String anotherString)

Parameter
anotherString : another string i.e., to be combined at the end of this string.

Returns
combined string

Internal implementation

1. public String concat(String str) {


2. int otherLen = str.length();
3. if (otherLen == 0) {
4. return this;
5. }
6. int len = value.length;
7. char buf[] = Arrays.copyOf(value, len + otherLen);
8. str.getChars(buf, len);
9. return new String(buf, true);
10. }

Java String concat() method example


FileName: ConcatExample.java

1. public class ConcatExample{


2. public static void main(String args[]){
3. String s1="java string";
4. // The string s1 does not get changed, even though it is invoking the method
5. // concat(), as it is immutable. Therefore, the explicit assignment is required here.
6. s1.concat("is immutable");
7. System.out.println(s1);
8. s1=s1.concat(" is immutable so assign it explicitly");
9. System.out.println(s1);
10. }}
Output:
java string
java string is immutable so assign it explicitly

Java String concat() Method Example 2


Let's see an example where we are concatenating multiple string objects.
FileName: ConcatExample2.java

1. public class ConcatExample2 {


2. public static void main(String[] args) {
3. String str1 = "Hello";
4. String str2 = "Javatpoint";
5. String str3 = "Reader";
6. // Concatenating one string
7. String str4 = str1.concat(str2);
8. System.out.println(str4);
9. // Concatenating multiple strings
10. String str5 = str1.concat(str2).concat(str3);
11. System.out.println(str5);
12. }
13. }
Output:
HelloJavatpoint
HelloJavatpointReader

Java String concat() Method Example 3


Let's see an example where we are concatenating spaces and special chars to the string object. It is
done using the chaining of the concat() method.
FileName: ConcatExample3.java

1. public class ConcatExample3 {


2. public static void main(String[] args) {
3. String str1 = "Hello";
4. String str2 = "Javatpoint";
5. String str3 = "Reader";
6. // Concatenating Space among strings
7. String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
8. System.out.println(str4);
9. // Concatenating Special Chars
10. String str5 = str1.concat("!!!");
11. System.out.println(str5);
12. String str6 = str1.concat("@").concat(str2);
13. System.out.println(str6);
14. }
15. }
Output:
Hello Javatpoint Reader
Hello!!!

Java String concat() Method Example 4


Till now, we have seen that the concat() method appends the string at the end of the string that
invokes the method. However, we can do a bit of workaround to append the string at the beginning
of a string using the concat() method.
FileName: ConcatExample4.java

1. // A Java program that shows how to add


2. // a string at the beginning of another string
3. public class ConcatExample4
4. {
5. // main method
6. public static void main(String argvs[])
7. {
8. String str = "Country";
9.
10. // we have added the string "India is my" before the String str;
11. // Also, observe that a string literal can also invoke the concat() method
12. String s = "India is my ".concat(str);
13.
14. // displaying the string
15. System.out.println(s);
16.
17. }
18. }
Output:
India is my Country
Java String replace()
The Java String class replace() method returns a string replacing all the old char or CharSequence
to new char or CharSequence.
Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char
values.

Signature
There are two types of replace() methods in Java String class.

1. public String replace(char oldChar, char newChar)


2. public String replace(CharSequence target, CharSequence replacement)
The second replace() method is added since JDK 1.5.

Parameters
oldChar : old character
newChar : new character
target : target sequence of characters
replacement : replacement sequence of characters

Returns
replaced string

Exception Throws
NullPointerException: if the replacement or target is equal to null.

Internal implementation

1. public String replace(char oldChar, char newChar) {


2. if (oldChar != newChar) {
3. int len = value.length;
4. int i = -1;
5. char[] val = value; /* avoid getfield opcode */
6.
7. while (++i < len) {
8. if (val[i] == oldChar) {
9. break;
10. }
11. }
12. if (i < len) {
13. char buf[] = new char[len];
14. for (int j = 0; j < i; j++) {
15. buf[j] = val[j];
16. }
17. while (i < len) {
18. char c = val[i];
19. buf[i] = (c == oldChar) ? newChar : c;
20. i++;
21. }
22. return new String(buf, true);
23. }
24. }
25. return this;
26. }
1. public String replace(CharSequence target, CharSequence replacement)
2. {
3. return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
4. this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
5. }

Java String replace(char old, char new) method example


FileName: ReplaceExample1.java

1. public class ReplaceExample1{


2. public static void main(String args[]){
3. String s1="javatpoint is a very good website";
4. String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
5. System.out.println(replaceString);
6. }}
Output:
javatpoint is e very good website

Java String replace(CharSequence target,


CharSequence replacement) method example
FileName: ReplaceExample2.java

1. public class ReplaceExample2{


2. public static void main(String args[]){
3. String s1="my name is khan my name is java";
4. String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
5. System.out.println(replaceString);
6. }}
Test it Now

Output:
my name was khan my name was java

Java String replace() Method Example 3


FileName: ReplaceExample3.java

1. public class ReplaceExample3 {


2. public static void main(String[] args) {
3. String str = "oooooo-hhhh-oooooo";
4. String rs = str.replace("h","s"); // Replace 'h' with 's'
5. System.out.println(rs);
6. rs = rs.replace("s","h"); // Replace 's' with 'h'
7. System.out.println(rs);
8. }
9. }
Output:
oooooo-ssss-oooooo
oooooo-hhhh-oooooo

Java String replace() Method Example 4


The replace() method throws the NullPointerException when the replacement or target is null. The
following example confirms the same.
FileName: ReplaceExample4.java

1. public class ReplaceExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = "For learning Java, JavaTpoint is a very good site.";
8. int size = str.length();
9.
10. System.out.println(str);
11. String target = null;
12.
13. // replacing null with JavaTpoint. Hence, the NullPointerException is raised.
14. str = str.replace(target, "JavaTpoint ");
15.
16. System.out.println(str);
17.
18. }
19. }
Output:
For learning Java, JavaTpoint is a very good site.
Exception in thread "main" java.lang.NullPointerException
at java.base/java.lang.String.replace(String.java:2142)
at ReplaceExample4.main(ReplaceExample4.java:12)

Java String indexOf()


The Java String class indexOf() method returns the position of the first occurrence of the specified
character or string in a specified string.

Signature
There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given
below:

No. Method Description


1 int indexOf(int ch) It returns the index position for the given char value

2 int indexOf(int ch, int fromIndex) It returns the index position for the given char value and from index

3 int indexOf(String substring) It returns the index position for the given substring

4 int indexOf(String substring, int fromIndex) It returns the index position for the given substring and from index

Parameters
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.

Returns
Index of the searched string or character.
Internal Implementation

1. public int indexOf(int ch) {


2. return indexOf(ch, 0);
3. }

Java String indexOf() Method Example


FileName: IndexOfExample.java

1. public class IndexOfExample{


2. public static void main(String args[]){
3. String s1="this is index of example";
4. //passing substring
5. int index1=s1.indexOf("is");//returns the index of is substring
6. int index2=s1.indexOf("index");//returns the index of index substring
7. System.out.println(index1+" "+index2);//2 8
8.
9. //passing substring with from index
10. int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
11. System.out.println(index3);//5 i.e. the index of another is
12.
13. //passing char value
14. int index4=s1.indexOf('s');//returns the index of s char value
15. System.out.println(index4);//3
16. }}
Output:
2 8
5
3
We observe that when a searched string or character is found, the method returns a non-negative
value. If the string or character is not found, -1 is returned. We can use this property to find the total
count of a character present in the given string. Observe the following example.
FileName: IndexOfExample5.java

1. public class IndexOfExample5


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = "Welcome to JavaTpoint";
8. int count = 0;
9. int startFrom = 0;
10. for(; ;)
11. {
12.
13. int index = str.indexOf('o', startFrom);
14.
15. if(index >= 0)
16. {
17. // match found. Hence, increment the count
18. count = count + 1;
19.
20. // start looking after the searched index
21. startFrom = index + 1;
22. }
23.
24. else
25. {
26. // the value of index is - 1 here. Therefore, terminate the loop
27. break;
28. }
29.
30. }
31.
32. System.out.println("In the String: "+ str);
33. System.out.println("The 'o' character has come "+ count + " times");
34. }
35. }
Output:
In the String: Welcome to JavaTpoint
The 'o' character has come 3 times

Java String indexOf(String substring) Method Example


The method takes substring as an argument and returns the index of the first character of the
substring.
FileName: IndexOfExample2.java

1. public class IndexOfExample2 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing Substring
5. int index = s1.indexOf("method"); //Returns the index of this substring
6. System.out.println("index of substring "+index);
7. }
8.
9. }
Output:
index of substring 16

Java String indexOf(String substring, int fromIndex)


Method Example
The method takes substring and index as arguments and returns the index of the first character that
occurs after the given fromIndex.
FileName: IndexOfExample3.java

1. public class IndexOfExample3 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing substring and index
5. int index = s1.indexOf("method", 10); //Returns the index of this substring
6. System.out.println("index of substring "+index);
7. index = s1.indexOf("method", 20); // It returns -1 if substring does not found
8. System.out.println("index of substring "+index);
9. }
10. }
Output:
index of substring 16
index of substring -1

Java String indexOf(int char, int fromIndex) Method


Example
The method takes char and index as arguments and returns the index of the first character that
occurs after the given fromIndex.
FileName: IndexOfExample4.java

1. public class IndexOfExample4 {


2. public static void main(String[] args) {
3. String s1 = "This is indexOf method";
4. // Passing char and index from
5. int index = s1.indexOf('e', 12); //Returns the index of this char
6. System.out.println("index of char "+index);
7. }
8. }
Output:
index of char 17

Java String toLowerCase()


The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally
uses the default locale.

Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:

1. public String toLowerCase()


2. public String toLowerCase(Locale locale)
The second method variant of toLowerCase(), converts all the characters into lowercase using the
rules of given Locale.

Returns
string in lowercase letter.

Java String toLowerCase() method example


1. public class StringLowerExample{
2. public static void main(String args[]){
3. String s1="JAVATPOINT HELLO stRIng";
4. String s1lower=s1.toLowerCase();
5. System.out.println(s1lower);
6. }}
Output:
javatpoint hello string
Java String toUpperCase()
The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.

Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:

1. public String toUpperCase()


2. public String toUpperCase(Locale locale)
The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.

Returns
string in uppercase letter.

Java String toUpperCase() method example


1. public class StringUpperExample{
2. public static void main(String args[]){
3. String s1="hello string";
4. String s1upper=s1.toUpperCase();
5. System.out.println(s1upper);
6. }}
Test it Now

Output:
HELLO STRING

Java String toUpperCase(Locale locale) Method


Example 2
1. import java.util.Locale;
2. public class StringUpperExample2 {
3. public static void main(String[] args) {
4. String s = "hello string";
5. String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
6. String english = s.toUpperCase(Locale.forLanguageTag("en"));
7. System.out.println(turkish);//will print I with dot on upper side
8. System.out.println(english);
9. }
10. }
Output:
HELLO STR?NG
HELLO STRING

Java String trim()


The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of
space character is '\u0020'. The trim() method in Java string checks this Unicode value before and
after the string, if it exists then the method removes the spaces and returns the omitted string.

The string trim() method doesn't omit middle spaces.

Signature
The signature or syntax of the String class trim() method is given below:

1. public String trim()

Returns
string with omitted leading and trailing spaces

Java String trim() Method Example


FileName: StringTrimExample.java
1. public class StringTrimExample{
2. public static void main(String args[]){
3. String s1=" hello string ";
4. System.out.println(s1+"javatpoint");//without trim()
5. System.out.println(s1.trim()+"javatpoint");//with trim()
6. }}
Output
hello string javatpoint
hello stringjavatpoint

Java String trim() Method Example 2


The example demonstrates the use of the trim() method. This method removes all the trailing spaces so
the length of the string also reduces. Let's see an example.
FileName: StringTrimExample2.java

1. public class StringTrimExample2 {


2. public static void main(String[] args) {
3. String s1 =" hello java string ";
4. System.out.println(s1.length());
5. System.out.println(s1); //Without trim()
6. String tr = s1.trim();
7. System.out.println(tr.length());
8. System.out.println(tr); //With trim()
9. }
10. }
Output
22
hello java string
17
hello java string

Java String trim() Method Example 3


The trim() can be used to check whether the string only contains white spaces or not. The following
example shows the same.
FileName: TrimExample3.java

1. public class TrimExample3


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. String str = " abc ";
8.
9. if((str.trim()).length() > 0)
10. {
11. System.out.println("The string contains characters other than white spaces \n");
12. }
13. else
14. {
15. System.out.println("The string contains only white spaces \n");
16. }
17.
18. str = " ";
19.
20. if((str.trim()).length() > 0)
21. {
22. System.out.println("The string contains characters other than white spaces \n");
23. }
24. else
25. {
26. System.out.println("The string contains only white spaces \n");
27. }
28.
29. }
30. }
Output
The string contains characters other than white spaces

The string contains only white spaces

Java String trim() Method Example 4


Since strings in Java are immutable; therefore, when the trim() method manipulates the string by
trimming the whitespaces, it returns a new string. If the manipulation is not done by the trim() method,
then the reference of the same string is returned. Observe the following example.
FileName: TrimExample4.java

1. public class TrimExample4


2. {
3. // main method
4. public static void main(String argvs[])
5. {
6.
7. // the string contains white spaces
8. // therefore, trimming the spaces leads to the
9. // generation of new string
10. String str = " abc ";
11.
12. // str1 stores a new string
13. String str1 = str.trim();
14.
15. // the hashcode of str and str1 is different
16. System.out.println(str.hashCode());
17. System.out.println(str1.hashCode() + "\n");
18.
19. // no white space present in the string s
20. // therefore, the reference of the s is returned
21. // when the trim() method is invoked
22. String s = "xyz";
23. String s1 = s.trim();
24.
25. // the hashcode of s and s1 is the same
26. System.out.println(s.hashCode());
27. System.out.println(s1.hashCode());
28.
29. }
30. }
Output
The string contains characters other than white spaces

The string contains only white spaces

Java String contains()


The Java String class contains() method searches the sequence of characters in this string. It
returns true if the sequence of char values is found in this string otherwise returns false.

Signature
The signature of string contains() method is given below:

1. public boolean contains(CharSequence sequence)

Parameter
sequence : specifies the sequence of characters to be searched.

Returns
true if the sequence of char value exists, otherwise false.

Exception
NullPointerException : if the sequence is null.

Java String contains() Method Example


FileName: ContainsExample.java

1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}
Output:
true
true
false

Java String contains() Method Example 2


The contains() method searches case-sensitive char sequence. If the argument is not case sensitive, it
returns false. Let's see an example.
FileName: ContainsExample2.java

1. public class ContainsExample2 {


2. public static void main(String[] args) {
3. String str = "Hello Javatpoint readers";
4. boolean isContains = str.contains("Javatpoint");
5. System.out.println(isContains);
6. // Case Sensitive
7. System.out.println(str.contains("javatpoint")); // false
8. }
9. }
Output:
true
false

You might also like