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

Java Unit-1

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

Java Unit-1

Hi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

OOP THROUGH JAVA

CSE II-I
BY
Dr.N.Lingareddy
Associate professor
UNIT-I
A way of viewing world
A way of viewing the world is an idea to illustrate the object-oriented programming concept with an
example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are at
my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. Look at the following image.
Agents and Communities
To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message containing my request. It is the responsibility of the agent (Zomato) to satisfy my
request. Here, the agent uses some method to do this. I do not need to know the method that the
agent has used to solve my request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which requires
the help of many individuals in the community. We may describe agents and communities as follows.
An object-oriented program is structured as a community of interacting agents, called
objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like
zomato, myself, and my family in the community.

Messages and Methods


To solve my problem, I started with a request to the agent zomato, which led to still more requestes
among the members of the community until my request has done. Here, the members of a
community interact with one another by making requests until the problem has satisfied.
In object-oriented programming, every action is initiated by passing a message to an agent
(object), which is responsible for the action. The receiver is the object to whom the message
was sent. In response to the message, the receiver performs some method to carry out the
request. Every message may include any additional information as arguments.
In our example, I send a request to zomato with a message that contains food items, the quantity of
food, and the hotel details. The receiver uses a method to food get delivered to my home.

Responsibilities
In object-oriented programming, behaviors of an object described in terms of
responsibilities.
In our example, my request for action indicates only the desired outcome (food
delivered to my family). The agent (zomato) free to use any technique that solves
my problem. By discussing a problem in terms of responsibilities increases the level
of abstraction. This enables more independence between the objects in solving
complex problems.

OOP Concepts in Java


OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python,
etc.

Encapsulation

Encapsulation is the process of combining data and code into a single unit (object / class). In OOP,
every object is associated with its data and code. In programming, data is defined as variables and
code is defined as methods. The java programming language uses the class concept to implement
encapsulation.
Inheritance

Inheritance is the process of acquiring properties and behaviors from one object to another object or
one class to another class. In inheritance, we derive a new class from the existing class. Here, the
new class acquires the properties and behaviors from the existing class. In the inheritance concept,
the class which provides properties is called as parent class and the class which recieves the
properties is called as child class. The parent class is also known as base class or supre class. The
child class is also known as derived class or sub class.

In the inheritance, the properties and behaviors of base class extended to its derived class, but the
base class never receive properties or behaviors from its derived class.
In java programming language the keyword extends is used to implement
inheritance.

Polymorphism

Polymorphism is the process of defining same method with different implementation.


That means creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement
polymorphism.
Method overloading - multiple methods with same name but different parameters.

Method overriding - multiple methods with same name and same parameters.

Abstraction

Abstraction is hiding the internal details and showing only esential functionality. In the abstraction
concept, we do not show the actual implemention to the end user, instead we provide only esential
things. For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system works? etc.
Java Buzz Words
ava is the most popular object-oriented programming language. Java has many advanced features,
a list of key features is known as Java Buzz Words. The java team has listed the following terms as
java buzz words.

 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic

Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming concepts
are similar to C++. In a java programming language, many complicated features like pointers,
operator overloading, structures, unions, etc. have been removed. One of the most useful features is
the garbage collector it makes java more simple.

Secure
Java is said to be more secure programming language because it does not have pointers concept,
java provides a feature "applet" which can be embedded into a web application. The applet in java
does not allow access to other parts of the computer, which keeps away from harmful programs like
viruses and unauthorized access.

Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide variety
of CPUs, operating systems, and browsers connected to the Internet.

Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It
supports all the features of the object-oriented programming paradigm. The primitive data types java
also implemented as objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has
a strong memory management mechanism (garbage collector), java is a strictly typed language, it
has a strong set of exception handling mechanism, and many more.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time, forever". The java provides JVM
(Java Virtual Machine) to to archive architectural-neutral or platform-independent. The JVM allows
the java program created using one operating system can be executed on any other operating
system.

Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.

Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code so that it
runs on the native machine.

High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.

Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this
feature enables a program to invoke methods across a network.

Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).

Overview of Java
Java is a computer programming language. Java was created based on C and C++. Java uses C
syntax and many of the object-oriented features are taken from C++. Before Java was invented
there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These languages had
few disadvantages which were corrected in Java. Java also innovated many new features to solve
the fundamental problems which the previous languages could not solve. Java was invented by a
team of 13 employees of Sun Microsystems, Inc. which is lead by James Gosling, in 1991. The team
includes persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was
developed as a part of the Green project. Initially, it was called Oak, later it was changed to Java in
1995.

History of Java
 The C language developed in 1972 by Dennis Ritchie had taken a decade to become the
most popular language.
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included
OOP fundamentals and features.
 A project named “Green” was initiated in December of 1990, whose aim was to create a
programming tool that could render obsolete the C and C++ programming languages.
 Finally in the year of 1991 the Green Team was created a new Programming language
named “OAK”.
 After some time they found that there is already a programming language with the name
“OAK”.
 So, the green team had a meeting to choose a new name. After so many discussions they
want to have a coffee. They went to a Coffee Shop which is just outside of the Gosling’s
office and there they have decided name as “JAVA”.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.
Java Data Types
Java programming language has a rich set of data types. The data type is a category of data stored
in variables. In java, data types are classified into two types and they are as follows.

 Primitive Data Types


 Non-primitive Data Types
Primitive Data Types
The primitive data types are built-in data types and they specify the type of value stored in a variable
and the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.

Data Memory Default


type Meaning size Range Value

byte Whole numbers 1 byte -128 to +127 0

short Whole numbers 2 bytes -32768 to +32767 0

int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

long Whole numbers 8 bytes -9,223,372,036,854,775,808 to 0L


+9,223,372,036,854,775,807

float Fractional 4 bytes - 0.0f


numbers
Data Memory Default
type Meaning size Range Value

double Fractional 8 bytes - 0.0d


numbers

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)

Let's look at the following example java program to illustrate primitive data types in java and their
default values.

Example
public class PrimitiveDataTypes {

byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;

public static void main(String[] args) {

PrimitiveDataTypes obj = new PrimitiveDataTypes();

System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l =
" + obj.l);
System.out.println("m = " + obj.m + ", n = " + obj.n);
System.out.println("ch = " + obj.ch);
System.out.println("p = " + obj.p);
}
}

o/p

Non-primitive Data Types


In java, non-primitive data types are the reference data types or user-created data types. All non-
primitive data types are implemented using object concepts. Every variable of the non-primitive data
type is an object. The non-primitive data types may use additional methods to perform certain
operations. The default value of non-primitive data type variable is null.
In java, examples of non-primitive data types
are String, Array, List, Queue, Stack, Class, Interface, etc.

Primitive Vs Non-primitive Data Types


Primitive Data Type Non-primitive Data Type

These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all

Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are clasiffied as follows.

 Local variables
 Instance variables or Member variables or Global variables
 Static variables or Class variables

Local variables
The variables declared inside a method or a block are known as local variables. A local variable is
visible within the method in which it is declared. The local variable is created when execution control
enters into the method or block and destroyed after the method or block execution completed.

Instance variables or member variables or global variables


The variables declared inside a class and outside any method, constructor or block are known as
instance variables or member variables. These variables are visible to all the methods of the class.
The changes made to these variables by method affects all the methods in the class. These
variables are created separate copy for every object of that class.

Static variables or Class variables


A static variable is a variable that declared using static keyword. The instance variables can be
static variables but local variables can not. Static variables are initialized only once, at the start of the
program execution. The static variable only has one copy per class irrespective of how many objects
we create.
The static variable is access by using class name.

Java Arrays
An array is a collection of similar data values with a single name. An array can also be defined as, a
special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in java
is organized using index values. The index value of an array starts with '0' and ends with 'zise-1'. We
use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
 One Dimensional Array
 Multi Dimensional Array

Creating an array
In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.

Syntax

data_type array_name[ ] = new data_type[size];


(or)
data_type[ ] array_name = new data_type[size];

Let's look at the following example program.

Example

public class ArrayExample {

public static void main(String[] args) {

int list[] = new int[5];

list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);

o/p
In java, an array can also be initialized at the time of its declaration. When an array is initialized at
the time of its declaration, it need not specify the size of the array and use of the new operator. Here,
the size is automatically decided based on the number of values that are initialized.

Example

int list[ ] = {10, 20, 30, 40, 50};

NullPointerException with Arrays


In java, an array created without size and initialized to null remains null only. It does not allow us to
assign a value. When we try to assign a value it generates a NullPointerException.
Look at the following example program.

Example

public class ArrayExample {

public static void main(String[] args) {

short list[] = null;

list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);

Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax to
create two-dimensional array.

Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];

When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.

Syntax

data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator. Here, the size is automatically decided based on the number of values that
are initialized.

Example

int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two columns.

Java Program to add two matrices


We can add two matrices in java using binary + operator. A matrix is also known as array of arrays.
We can add, subtract and multiply matrices.

To subtract two matrices, use - operator. Let's see a simple example to add two matrices of 3 rows
and 3 columns.

1. public class MatrixAdditionExample{


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

Output:

2 6 8
4 8 6
4 6 9

Java Program to multiply two matrices


We can multiply two matrices in java using binary * operator and executing another
loop. A matrix is also known as array of arrays. We can add, subtract and multiply
matrices.

In case of matrix multiplication, one row element of first matrix is multiplied by all
columns of second matrix.

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

1. public class MatrixMultiplicationExample{


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

Output:

6 6 6
12 12 12
18 18 18

Java Operators
Operator in 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 Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&


logical OR ||

Ternary ternary ? :

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

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o 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 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
5
50
2
0

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

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator
has two posible results either TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational operators.

Operato
r Meaning Example

< Returns TRUE if the first value is smaller than second value otherwise returns 10 < 5 is
FALSE FALSE

> Returns TRUE if the first value is larger than second value otherwise returns 10 > 5 is TRUE
FALSE

<= Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is
returns FALSE TRUE

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is


Operato
r Meaning Example

FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE

Look at the following example program.

Example

public class RelationalOperators {

public static void main(String[] args) {

boolean a;

a = 10<5;
System.out.println("10 < 5 is " + a);

a = 10>5;
System.out.println("10 > 5 is " + a);

a = 10<=5;
System.out.println("10 <= 5 is " + a);

a = 10>=5;
System.out.println("10 >= 5 is " + a);

a = 10==5;
System.out.println("10 == 5 is " + a);

a = 10!=5;
System.out.println("10 != 5 is " + a);
}
}

o/p

Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Operato
r Meaning Example

& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns false & true =>
FALSE false

| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns false | true =>
TRUE true

^ Logical XOR - Returns FALSE if all conditions are same otherwise returns true ^ true =>
TRUE false

! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false => true
TRUE

&& short-circuit AND - Similar to Logical AND (&), but once a decision is finalized false & true =>
it does not evaluate remianing. false

|| short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it false | true =>
does not evaluate remianing. true

Look at the following example program.

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

int x = 10, y = 20, z = 0;


boolean a = true;

a = x>y && (z=x+y)>15;


System.out.println("a = " + a + ", and z = " + z);

a = x>y & (z=x+y)>15;


System.out.println("a = " + a + ", and z = " + z);

o/p

Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the java programming
language.

Operato
r Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result into left-hand side variable A += 10

-= Subtract right-hand side value from left-hand side variable value and store the result A -= B
Operato
r Meaning Example

into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store the result into A *= B
left-hand side variable

/= Divide left-hand side variable value with right-hand side variable value and store the A /= B
result into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable value and store the A %= B
remainder into the left-hand side variable

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

Look at the following example program.

Example

public class AssignmentOperators {

public static void main(String[] args) {

int a = 10, b = 20, c;


boolean x = true;

System.out.println("a = " + a + ", b = " + b);

a += b;
System.out.println("a = " + a);
a -= b;
System.out.println("a = " + a);

a *= b;
System.out.println("a = " + a);

a /= b;
System.out.println("a = " + a);

a %= b;
System.out.println("a = " + a);

x |= (a>b);
System.out.println("x = " + x);

x &= (a>b);
System.out.println("x = " + x);
}
}

o/p

Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values. The
following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operato
r Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
Operato
r Meaning Example

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B


⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit (Flipping) ~A


⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the specified number A << 2
of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)

Look at the following example program.

Example

public class BitwiseOperators {

public static void main(String[] args) {

int a = 25, b = 20;

System.out.println(a + " & " + b + " = " + (a & b));

System.out.println(a + " | " + b + " = " + (a | b));

System.out.println(a + " ^ " + b + " = " + (a ^ b));

System.out.println("~" + a + " = " + ~a);


System.out.println(a + ">>" + 2 + " = " + (a>>2));

System.out.println(a + "<<" + 2 + " = " + (a<<2));

System.out.println(a + ">>>" + 2 + " = " + (a>>>2));


}

o/p

Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform
one operation out of the two operations based on the condition result. If the condition is TRUE the
first option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.

Syntax

Condition ? TRUE Part : FALSE Part;

Look at the following example program.

Example

public class ConditionalOperator {

public static void main(String[] args) {


int a = 10, b = 20, c;

c = (a>b)? a : b;

System.out.println("c = " + c);


}

o/p

Java Expressions
In any programming language, if we want to perform any calculation or to frame any condition etc.,
we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.

Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.

 Infix Expression
 Postfix Expression
 Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.

Example

Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.

Example
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a
part of the program again and again. To solve this problem, java provides control statements.

In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of execution
according to our requirements. Java provides several control statements, and they are classified as
follows.

Types of Control Statements


In java, the control statements are classified as follows.

 Selection Control Statements ( Decision Making Statements )


 Iterative Control Statements ( Looping Statements )
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based
on a condition. Java provides the following selection statements.

 if statement
 if-else statement
 if-elif statement
 nested if statement
 switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result. The if statement checks, the given condition then decides the
execution of a block of statements. If the condition is True, then the block of statements is executed
and if it is False, then the block of statements is ignored. The syntax and execution flow of if the
statement is as follows.

Java Program
import java.util.Scanner;

public class IfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}

System.out.println("We are outside the if-block!!!");

o/p

if-else statement in java


In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the given
condition then decides which block of statements to be executed based on the condition result. If the
condition is True, then the true block of statements is executed and if it is False, then the false block
of statements is executed. The syntax and execution flow of if-else statement is as follows.
Java Program
import java.util.Scanner;

public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}
else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}

System.out.println("We are outside the if-block!!!");

o/p
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement. The general syntax
of the nested if-statement is as follows.

Syntax

if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}

Java Program
import java.util.Scanner;

public class NestedIfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();

if (num < 100) {


System.out.println("\nGiven number is below 100");
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
} else
System.out.println("Given number is not below 100");
System.out.println("\nWe are outside the if-block!!!");

o/p

if-else if statement in java


Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax
of the an if-else-if statement is as follows.

Syntax

if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}

Java Program
import java.util.Scanner;

public class IfElseIfStatementTest {

public static void main(String[] args) {

int num1, num2, num3;


Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();

if( num1>=num2 && num1>=num3)


System.out.println("\nThe largest number is " + num1) ;

else if (num2>=num1 && num2>=num3)


System.out.println("\nThe largest number is " + num2) ;

else
System.out.println("\nThe largest number is " + num3) ;

System.out.println("\nWe are outside the if-block!!!");

o/p

switch statement in java


Using the switch statement, one can select only one option from more number of options very easily.
In the switch statement, we provide a value that is to be compared with a value associated with each
option. Whenever the given value matches the value associated with an option, the execution starts
from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Java Program
import java.util.Scanner;

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Press any digit: ");

int value = read.nextInt();

switch( value )
{
case 0: System.out.println("ZERO") ; break ;
case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}

o/p

Java Iterative Statements


The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true. The iterative
statements are also known as looping statements or repetitive statements. Java provides the
following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement

while statement in java


The while statement is used to execute a single statement or block of statements repeatedly as long
as the given condition is TRUE. The while statement is also known as Entry control looping
statement. The syntax and execution flow of while statement is as follows.
Java Program
ipublic class WhileTest {

public static void main(String[] args) {

int num = 1;

while(num <= 10) {


System.out.println(num);
num++;
}

System.out.println("Statement after while!");

o/p
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax.

Java Program
public class DoWhileTest {

public static void main(String[] args) {

int num = 1;

do {
System.out.println(num);
num++;
}while(num <= 10);

System.out.println("Statement after do-while!");


}

o/p

for statement in java


The for statement is used to execute a single statement or a block of statements repeatedly as long
as the given condition is TRUE. The for statement has the following syntax and execution flow
diagram.

In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Let's look at the following example java code.

Java Program
public class ForTest {
public static void main(String[] args) {

for(int i = 0; i < 10; i++) {


System.out.println("i = " + i);
}

System.out.println("Statement after for!");


}

o/p

Java Nested for Loop


If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.

NestedForExample.java

1. public class NestedForExample {


2. public static void main(String[] args) {
3. //loop of i
4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){
7. System.out.println(i+" "+j);
8. }//end of i
9. }//end of j
10. }
11. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:

PyramidExample.java

1. public class PyramidExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=5;i++){
4. for(int j=1;j<=i;j++){
5. System.out.print("* ");
6. }
7. System.out.println();//new line
8. }
9. }
10. }

Output:

*
* *
* * *
* * * *
* * * * *

Java Jump Statements


The java programming language supports jump statements that used to transfer execution control
from one line to another line. The java programming language provides the following jump
statements.

 break statement
 continue statement
 labelled break and continue statements
 return statement

break statement in java


The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while, do-
while, for, and for-each.
🔔 Using the break statement outside the switch or loop statement is not allowed.
The floowing picture depictes the execution flow of the break statement.

Java Program

public class JavaBreakStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}

o/p
continue statement in java
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning of the
loop. The continue statement can be used with looping statements like while, do-while, for, and for-
each.
When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop. The
continue statement flow of execution is as shown in the following figure.

Java Program
public class JavaContinueStatement {

public static void main(String[] args) {

int list[] = {10, 20, 30, 40, 50};

for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}

o/p

Labelled break and continue statement in java


The java programming langauge does not support goto statement, alternatively, the break and
continue statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.
Let's look at the following example java code.

Java Program

import java.util.Scanner;

public class JavaLabelledStatement {


public static void main(String args[]) {

Scanner read = new Scanner(System.in);

reading: for (int i = 1; i <= 3; i++) {


System.out.print("Enter a even number: ");
int value = read.nextInt();

verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");
break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more
options...");
continue reading;
}
}
}
}

o/p

return statement in java


In java, the return statement used to terminate a method with or without a value. The return
statement takes the execution control to the calling function. That means the return statement
transfer the execution control from called function to the calling function by carrying a value.
🔔 Java allows the use of return-statement with both, with and without return type methods.

In java, the return statement used with both methods with and without return type. In the case of a
method with the return type, the return statement is mandatory, and it is optional for a method
without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is
used without a return type, it does not carry any value. Instead, simply transfers the execution
control.
Let's look at the following example java code.

Java Program

import java.util.Scanner;
public class JavaReturnStatementExample {

int value;

int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt();
}

void showValue(int value) {


for(int i = 0; i <= value; i++) {
if(i == 5)
return;
System.out.println(i);
}
}

public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();

obj.showValue(obj.readValue());

}
}

o/p

Java Classes
Java is an object-oriented programming language, so everything in java program must be based on
the object concept. In a java programming language, the class concept defines the skeleton of an
object.
The java class is a template of an object. The class defines the blueprint of an object. Every class in
java forms a new data type. Once a class got created, we can generate as many objects as we
want. Every class defines the properties and behaviors of an object. All the objects of a class have
the same properties and behaviors that were defined in the class.
Every class of java programming language has the following characteristics.

 Identity - It is the name given to the class.


 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

Look at the following picture to understand the class and object concept.

Creating a Class
In java, we use the keyword class to create a class. A class in java contains
properties as variables and behaviors as methods. Following is the syntax of class in
the java.

Syntax

class <ClassName>{
data members declaration;
methods defination;
}
🔔 The ClassName must begin with an alphabet, and the Upper-case letter is
preferred.
🔔 The ClassName must follow all naming rules.

Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the
class is said to be instantiated. All the objects that are created using a single class
have the same properties and methods. But the value of properties is different for
every object. Following is the syntax of class in the java.

Syntax

<ClassName> <objectName> = new <ClassName>( );

🔔 The objectName must begin with an alphabet, and a Lower-case letter is


preferred.
🔔 The objectName must follow all naming rules.

Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.

 returnType - Specifies the data type of a return value.


 name - Specifies a unique name to identify it.
 parameters - The data values it may accept or recieve.
 { } - Defienes the block belongs to the method.
Creating a method
A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Following is the syntax for creating methods in java.

Syntax

class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}

🔔 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
🔔 The methodName must follow all naming rules.
🔔 If you don't want to pass parameters, we ignore it.
🔔 If a method defined with return type other than void, it must contain the return statement,
otherwise, it may be ignored.

Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call must be
made, as to the method name with parentheses (), and it must terminate with a semicolon.

Syntax

<objectName>.<methodName>( actualArguments );

🔔 The method call must pass the values to parameters if it has.


🔔 If the method has a return type, we must provide the receiver.
Let's look at the following example java code.

Example

import java.util.Scanner;
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner(System.in);

void readData() {
System.out.print("Enter Serial Number: ");
sNo = read.nextInt();
System.out.print("Enter the Name: ");
name = read.next();
}

static void showData(int sNo, String name) {


System.out.println("Hello, " + name + "! your serial number is " + sNo);
}

public static void main(String[] args) {

JavaMethodsExample obj = new JavaMethodsExample();

obj.readData(); // method call using object

showData(obj.sNo, obj.name); // method call without using object

o/p
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit method
call. A constructor may have parameters and access specifiers too. In java, if you do not provide any
constructor the compiler automatically creates a default constructor.
Let's look at the following example java code.

Example

public class ConstructorExample {

ConstructorExample() {
System.out.println("Object created!");
}
public static void main(String[] args) {

ConstructorExample obj1 = new ConstructorExample();


ConstructorExample obj2 = new ConstructorExample();
}

o/p

Method Overloading in Java

When a class has two or more methods by the same name but different parameters, at the
time of calling based on the parameters passed respective method is called (or respective
method body will be bonded with the calling line dynamically). This mechanism is known as
method overloading.
Example of Method Overloading
If you observe the following example, here we have created a class called Sample and this
class has two methods with the same name (add) and return type, the only difference is the
parameters they accept (one method accepts two integer variables and other accepts three
integer variables).
When you invoke the add() method based on the parameters you pass respective method
body gets executed.
public class Sample {
public static void add(int a, int b) {
System.out.println(a+b);
}
public static void add(int a, int b, int c) {
System.out.println(a+b+c);
}
public static void main(String args[]) {
Sample obj = new Sample();
obj.add(20, 40);
obj.add(40, 50, 60);
}
}
Output

On execution, it will produce the following output −

60
150

Method Overriding in Java

In method overriding, Super class and subclass have methods with the same name
including parameters. JVM calls the respective method based on the object used to call the
method. In overriding, the return types should also be same.

Example of Method Overriding

Let's take an example to understand how method overriding works in Java −

class SuperClass {
public static void sample() {
System.out.println("Method of the super class");
}
}
public class SubClass extends SuperClass {
public static void sample() {
System.out.println("Method of the sub class");
}
public static void main(String args[]) {
SuperClass obj1 = new SubClass();
SubClass obj2 = new SubClass();
obj1.sample();
obj2.sample();
}
}

Here we have a SuperClass and a SubClass. Both the classes have a method called
Sample() with the same signature. In the main class, we created obj1 for SuperClass and
obj2 for SubClass. The JVM calls the respective method based on the object used to call the
method.

Output

On execution, it will produce the following output −

Method of the super class


Method of the sub class

Difference between Overloading and Overriding

The following table highlights the major differences between Method Overloading and
Method Overriding −

Method Overloading Method Overriding

Method overloading is known as Method overriding is known


compile-time polymorphism. as runtime polymorphism.

For overloading to come into picture, For overriding to work, we need to


there must be at least two methods of have at least one method with the
the same name. same name in both the parent class as
well as the child class.

The methods must have different Both the methods must have the same
number of parameters. If both the number of parameters with the same
methods have the same number of type.
parameters, then their type must be
different.

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can
be defined as the concept of having more than one constructor with different
parameters so that every constructor can perform a different task.

Consider the following Java program, in which we have used different constructors in
the class.

Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

Access control(modifiers) in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Difference Between this and this() in Java


The below table shows the point-to-point difference between both this keyword and this().
this this()

this keyword is used with the objects


this() is used with constructors only.
only.

It refers to the constructor of the same class


It refers to the current object. whose parameters matches with the parameters
passed to this(parameters).

Dot(.) operator is used to access the


No Dot(.) operator is used. Only the matching
members.
parameters are passed.
For example, this.variableName;

It is used to differentiate between the


It is used to refer to the constructor belonging to
local variable and the instance variable
the same class.
in the method.

Java String Handling


A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append more
characters after its definition, but it can be modified.
Let's look at the following example java code.

Example

char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);

The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Let's look at the following example java code.

Example

String siteName = "btechsmartclass.com";


siteName = "www.btechsmartclass.com";

Creating String object in java


In java, we can use the following two ways to create a string object.

 Using string literal


 Using String constructor

Let's look at the following example java code.

Example
String title = "Java Tutorials"; // Using literals

String siteName = new String("www.btechsmartclass.com"); // Using constructor

🔔 The String class constructor accepts both string and character array as an argument.

String handling methods


In java programming language, the String class contails various methods that can be used to handle
string data values. It containg methods like concat( ), compareTo( ), split( ), join( ), replace( ), trim( ),
length( ), intern( ), equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.

Return
Method Description Value

charAt(int) Finds the character at given index char

length() Finds the length of given string int

compareTo(String) Compares two strings int

compareToIgnoreCase(String Compares two strings, ignoring case int


)

concat(String) Concatenates the object string with argument string. String

contains(String) Checks whether a string contains sub-string boolean

contentEquals(String) Checks whether two strings are same boolean

equals(String) Checks whether two strings are same boolean

equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
Return
Method Description Value

startsWith(String) Checks whether a string starts with the specified string boolean

endsWith(String) Checks whether a string ends with the specified string boolean

getBytes() Converts string value to bytes byte[]

hashCode() Finds the hash code of a string int

indexOf(String) Finds the first index of argument string in object string int

lastIndexOf(String) Finds the last index of argument string in object string int

isEmpty() Checks whether a string is empty or not boolean

replace(String, String) Replaces the first string with second string String

replaceAll(String, String) Replaces the first string with second string at all occurrences. String

substring(int, int) Extracts a sub-string from specified start and end index String
values

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends String

toString(int) Converts the value to a String object String


Return
Method Description Value

split(String) splits the string matching argument string String[]

intern() returns string from the pool String

join(String, String, ...) Joins all strings, first string as delimiter. String

Java Program
public class JavaStringExample {

public static void main(String[] args) {


String title = "Java Tutorials";
String siteName = "www.btechsmartclass.com";

System.out.println("Length of title: " + title.length());


System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Last index of 'a': " + title.lastIndexOf('a'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Ends with '.com': " + siteName.endsWith(".com"));
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}

o/p

You might also like