Programming Language Types and Paradigm: CS1303 - Object Oriented Programming Unit - I Java Fundamentals
Programming Language Types and Paradigm: CS1303 - Object Oriented Programming Unit - I Java Fundamentals
Programming Language Types and Paradigm: CS1303 - Object Oriented Programming Unit - I Java Fundamentals
The programing paradigms are categorized in multiple categories yet most significant are only
two:
The imperative programming paradigm is the oldest paradigm and follows the most
basic idea of programming. The programs in these paradigms are executed step by step by
changing the current state of the program. An imperative program consists of some command
that the computer operates and changes the state of the program. Imperative programming
mainly focuses on how a program operates
Some of the programming languages that support the imperative paradigm are:
● C
● C++
● Java
● PHP
● Ruby
● Scala
● Pascal
Code example:
In the example below there is a code of language supporting imperative programming, it's a
C++ code. See how it changes the state of the program and has a very clear step reach to the
goal
#include<stdio.h>
int main() {
int result = 0;
for (int i = 0; i < 10; i++) {
result = result + i;
}
printf("Result = %d", result);
return 0;
}
The paradigm follows the Von Neumann architecture and consists of multiple statements and
variables which calculates and stores the result.
Advantage
Disadvantage
It is the same as imperative programming but with a procedure call that lets you reuse
the code. And this feature was an amazing advancement at that time. Example C, C++,
Java, etc.
2. Object Oriented Programming (OOP)
This is used to work on real-world entities in the form of class and objects. Class is the
blueprint of the object and you can replicate as many as the object you want. These
classes contain some properties and methods which all are replicated in objects.
Example C++, Python, etc.
3. Parallel processing
● Prolog
● javascript
● Scala
● Lisp
● SQL
● XQuery
● Clojure
Code Example:
WHERE Category='Programming'
AND language='english';
Declarative programing can further be subcategorized into 3 main categories:
Logic programming uses sentences in logical form and creates an expression by using
symbols. In machine learning and artificial intelligence, there are many models that use
these programs. The programs are executed very much like some mathematical
statement. It is mainly based on forming logic.
This programming is based on enquiring data, its modification, its movement, etc. The
most famous programming language that supports this is SQL. Popular language and
programming paradigms they support
programming paradigm
component-oriented
Classes are user-defined data types that act as the blueprint for individual objects, attributes
and methods.
Objects are instances of a class created with specifically defined data. Objects can correspond
to real-world objects or an abstract entity. When class is defined initially, the description is the
only object that is defined.
Methods are functions that are defined inside a class that describe the behaviors of an object.
Each method contained in class definitions starts with a reference to an instance object.
Additionally, the subroutines contained in an object are called instance methods. Programmers
use methods for reusability or keeping functionality encapsulated inside one object at a time.
Attributes are defined in the class template and represent the state of an object. Objects will
have data stored in the attributes field. Class attributes belong to the class itself.
1. Inheritance
Inheritance is a mechanism where programmers can derive a class from another class.
This concept of OOP can be useful in giving custom logic to existing frameworks and in
declaring different exceptions. Inheritance also allows programmers to reuse previously written
codes. This removes the burden of writing the same codes again, as programmers can make a
derived class inherit the property of its parent class.
For example, one can create two child classes and name them hatchback and sedan inherited
from the parent class car.
Single inheritance: It is the simplest form of inheritance where a class inherits only one
parent class. Single inheritance enables code reusability and adds new features to the
existing class.
Multiple inheritance: When a class inherits more than one parent class, it becomes a
multiple inheritance. As the child class inherits properties from different parent classes, it
has access to all of its objects. It is different from a single inheritance property, as it
allows an object or class to inherit from more than one object or class.
Multilevel inheritance: When one class inherits properties from a derived class, it is
multilevel inheritance. For example, class A extends class B and class B extends class
C.
2. Polymorphism
3. Abstraction
4. Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. Encapsulation of data leads to the OOP concept of data hiding and keeps them
safe from outside attention. One of the common examples of encapsulation is a calculator, as
anybody using a calculator understands its functions, but may not require an understanding of
how it works inside. Encapsulation can help in hiding irrelevant details from the outside world
and highlight the necessary characteristics of a class to the users.
History of Java
The project was born in 1991, behind the scenes of a Sun Microsystems team, when
three engineers, James Gosling, Mike Sheridan, and Patrick Naughton sought to design a
language applicable to small electrical devices.
Soon after, they launched the Green Project to study the impact of convergence
between digitally controlled home appliances and computers. Using a syntax similar to that of
C++, they made a digital remote control, equipped with a graphic and animated touch screen.
The fruit of several months of intense research, this remote control had the fantastic feature of
controlling a whole living room equipment. It was programmed in a new language, completely
independent of the processor it was running on, making the remote one-of-a-kind.
Ultimately, it was James Gosling, one of the members of the Green Project, who
originated this new language, which he called Oak. Afterward, the project gained ground when
American cable operators joined the project. Oak then became FirstPerson. Unfortunately, the
FirstPerson project had no commercial success, as it was certainly too far ahead of the industry,
whose priority was, above all, profitability
In 1993, the HTTP protocol and the Mosaic browser arrived, which was a crucial event
for the project. During this time, the team realized that the Internet would be the ideal network to
position their product. Then, in 1995, James Gosling unveiled a browser called WebRunner that
was capable of showing HTML content mixed with Applets. Things took off from there. First,
WebRunner became HotJava, then java.sun.com officially opened to the public.
Eventually, the name of this technology would become “Java” (meaning “coffee” in
American slang), in honor of the programmer's favorite drink, namely coffee, part of the
production of which comes from the island of Java. It was then that Sun and Netscape
announced their desire to integrate this new technology into their browsers, which definitively
launched the language. The versions would then follow one another from version 1 in 1996 to
version 18 in 2022
Java Buzzwords
Java is a high-level, object oriented and secured programming language originally
developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such
as Windows, Mac OS, and the various versions of UNIX.
The inventors of Java wanted to design a language which could offer solutions to some
of the problems encountered in modern programming. They wanted the language to be not only
reliable, portable and distributed but also simple, compact and interactive. The authors of Java
have written an influential White Paper that explains the features of java by all of the following
buzzwords
● Simple
● Object Oriented
● Platform Independent
● Distributed
● Robust
● Secure
● Architecture Neutral
● Portable
● Interpreted
● High Performance
● Multithreaded
● Dynamic
Simple
Java is an object-oriented programming language with syntax and keywords
almost identical to C++. When developing Java, its creators took all of the good features
of the existing object-oriented programming languages such as C++, Ada, and Smalltalk,
and removed most of their flaws and peculiarities. There are a lot of aspects of the Java
language that are consistent and make sense, thereby making it easier to learn.
Object Oriented
It supports all the four pillars of object oriented programming concepts viz;
Encapsulation, Abstraction, Inheritance, Polymorphism, so that language is an object
oriented programming language. E.g. java, C++
Platform independent
Java can run in any system line windows, Linux, mac etc. You do not need to
write a separate program for an individual platform/OS. Programs written in the Windows
platform can run on the Linux platform. Output of java compiler (javac.exe in windows) is
a bytecode (.calss file), but not native machine code. This bytecode is interpreted by a
virtual machine (not by a real computer) as a real computer interprets .exe files in
C/C++. Such a virtual machine is called a Java Virtual Machine (JVM).
Translating a Java program into Bytecode makes it much easier to run a program
in a wide variety of platforms/Environments, because only JVM needs to be
implemented. Once bytecode is ready, we can run it in windows, Linux, calculator,
mobile, watch etc.., but one thing is all environments require just JVM. Details of JVM
differ from environment to environment. (Platform to Platform)
Distributed
● A technology is said to be distributed if its business objects are geographically
dispersed into different locations and still communicate with one another.
● Networking capabilities of java are strong and easy to use.
● Onerous tasks like opening a socket connection are simple in Java.
● An elegant mechanism, called servlets, makes server-side processing in Java
extremely efficient. Many popular web servers support servlets.
Robust
Programming language is robust when it is reliable and strong. Below capabilities
make java robust:
● Java has a garbage collector which will automatically clean up unused objects
and memory. No need to chase memory corruption.
● In java you do not use pointers to access strings, arrays, objects, even files. Nor
do you need to worry about memory allocation for them.
● Java has an exception handling mechanism which is very useful in handling both
compile and run time errors. Without handling errors and exceptions, the entire
application would fail. With exception handling it just stops the current flows even
when failed, but rest all flows still run.
Secure
Java team has said that they will have a “zero tolerance” for security bugs and
will immediately go to work on fixing any bugs found. Java program will be first compiled
to byte code. This byte code will then be interpreted by Java Virtual Machine (JVM). JVM
makes java secure with below factors:
● JVM will not overrun the runtime stack.
● JVM will not corrupt memory outside its own process space.
● JVM will not read or write to local files when invoked through a security-
conscious class loader.
Architecture Neutral
The compiler generates architecture-neutral bytecode instructions which have
nothing to do with particular computer architecture. These bytecode instructions can be
run by only JVM. JVM is not same for platforms and architectures. Java will provide you
different JVMs for different platforms and architectures. So you just have to install
different JVMs. A bytecode once ready can be run by any JVM. A program written in 32
bit operating system can be run by JVM in 64 bit operating system.
Portable
In C/C++ data size varies from platform to platform. For example, an integer can
be a 16-bit integer, a 32-bit integer, or any other size that the compiler vendor likes. Java
has a fixed size for data that eliminates a major porting headache. Binary data is stored
and transmitted in a fixed format, eliminating the “big endian/little endian” confusion.
Strings are saved in a standard Unicode format. Java does this by JVM. Java facilitates
you to carry the Java bytecode to any platform. It doesn't require writing different
programs for different platforms line Windows, Linux etc…
Interpreted
Java Virtual Machine (JVM) is the java interpreter. The interpreter can execute
Java bytecodes directly on any machine to which the interpreter has been ported. Since
installing JVM is a lightweight process, the development process can be much more
rapid and exploratory.
High Performance
When Java was still a new language, it was criticized for being slow: Since Java
bytecode was executed by an interpreter, it seemed that Java bytecode programs could
never run as quickly as programs compiled into native machine language (that is, the
actual machine language of the computer on which the program is running). However,
this problem has been largely overcome by the use of just-in-time compilers (JIT) for
executing Java bytecode.
JIT is a part of JVM. A just-in-time compiler translates Java bytecode into native
machine language. It does this while it is executing the program. Just as for a normal
interpreter, the input to a just-in-time compiler is a Java bytecode program, and its task
is to execute that program.
It is important to understand that it is not practical to compile an entire Java
program into executable code all at once, because Java performs various run-time
checks that can be done only at run time. Instead, a JIT compiler compiles code as it is
needed, during execution. Furthermore, not all sequences of bytecode are compiled—
only those that will benefit from compilation. The remaining code is simply interpreted.
The translated parts of the program can then be executed much more quickly than they
could be interpreted. Since a given part of a program is often executed many times as
the program runs, a just-in-time compiler can significantly speed up the overall execution
time.
Even though dynamic compilation is applied to bytecode, the portability and
safety features still apply, because the JVM is still in charge of the execution
environment.
Multithreaded
A thread is defined as a separate path of execution inside any process. It is done
to use CPU idle time. A process consists of the memory space allocated by the
operating system that can contain one or more threads. A thread cannot exist on its own;
it must be a part of a process. Whenever a thread is created within a program it will not
occupy any separate space. It will share the same memory space of the program. It will
also not consume more resources.
Thread implementations on the major platforms differ widely, but Java makes no
effort to be platform independent in this regard. Only the code for calling multithreading
remains the same across machines; Java offloads the implementation of multithreading
to the underlying operating system or a thread library.
Dynamic
In a number of ways, Java is a more dynamic language than C or C++. It was
designed to adapt to an evolving environment. Libraries can freely add new methods
and instance variables without any effect on their clients. In Java, finding out run time
type information is straightforward. This is an important feature in those situations where
code needs to be added to a running program.
JVM Architecture
A Virtual Machine is a software implementation of a physical machine. Java was developed with
the concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler compiles
the Java file into a Java .class file, then that .class file is input into the JVM, which loads and
executes the class file. Below is a diagram of the Architecture of the JVM.
As shown in the above architecture diagram, the JVM is divided into three main subsystems:
1. ClassLoader Subsystem
2. Runtime Data Area
3. Execution Engine
1. ClassLoader Subsystem
JVM Architecture
1.2 Linking
Verify: Bytecode verifier will verify whether the generated bytecode is proper or
not if verification fails we will get the verification error.
Prepare: For all static variables memory will be allocated and assigned with
default values.
Resolve: All symbolic memory references are replaced with the original
references from Method Area.
1.3 Initialization: This is the final phase of ClassLoading; here, all static variables will be
assigned with the original values, and the static block will be executed.
i. Method Area: All the class-level data will be stored here, including static variables.
There is only one method area per JVM, and it is a shared resource.
Ii. Heap Area: All the Objects and their corresponding instance variables and arrays will
be stored here. There is also one Heap Area per JVM. Since the Method and Heap
areas share memory for multiple threads, the data stored is not thread-safe.
iii. Stack Area: For every thread, a separate runtime stack will be created. For every
method call, one entry will be made in the stack memory which is called Stack Frame. All
local variables will be created in the stack memory. The stack area is thread-safe since it
is not a shared resource. The Stack Frame is divided into three subentities:
Local Variable Array: Related to the method how many local variables are
involved and the corresponding values will be stored here.
Frame data: All symbols corresponding to the method is stored here. In the case
of any exception, the catch block information will be maintained in the frame
data.
iv. PC Registers – Each thread will have separate PC Registers, to hold the address of
current executing instruction once the instruction is executed the PC register will be
updated with the next instruction.
v. Native Method stacks: Native Method Stack holds native method information. For
every thread, a separate native method stack will be created.
3. Execution Engine
The bytecode, which is assigned to the Runtime Data Area, will be executed by the Execution
Engine. The Execution Engine reads the bytecode and executes it piece by piece.
i. Interpreter: The interpreter interprets the bytecode faster but executes slowly. The
disadvantage of the interpreter is that when one method is called multiple times, every
time a new interpretation is required.
ii. JIT Compiler: The JIT Compiler neutralizes the disadvantage of the interpreter. The
Execution Engine will be using the help of the interpreter in converting byte code, but
when it finds repeated code it uses the JIT compiler, which compiles the entire bytecode
and changes it to native code. This native code will be used directly for repeated method
calls, which improve the performance of the system.
iii. Garbage Collector: Collects and removes unreferenced objects. Garbage Collection
can be triggered by calling System.gc(), but the execution is not guaranteed. Garbage
collection of the JVM collects the objects that are created.
Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries and
provides the Native Libraries required for the Execution Engine.
Native Method Libraries: This is a collection of the Native Libraries, which is required for the
Execution Engine.
● Documentation Section
● Package Declaration
● Import Statements
● Interface Section
● Class Definition
● Class variables and Constants
● Main Method Class
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the
Java compiler ignores the statements during the execution of the program. To write the
statements in the documentation section, we use comments. The comments may be single-line,
multi-line, and documentation comments.
Single-line Comment: It starts with a pair of forwarding slash (//). For example:
Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:
/*It is an example of
multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed. Note that there can be
only one package statement in a Java program. It must be defined before any class and
interface declaration. It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these classes the package belongs
to a single parent directory. We use the keyword package to declare the package name. For
example:
package com.mypack; //where com is the root directory and mypack is the subdirectory
Import Statements
The package contains the many predefined classes and interfaces. If we want to use
any class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to import the
class. It is written before the class declaration and after the package statement. We use the
import statement in two ways, either import a specific class or import all classes of a particular
package. In a Java program, we can use multiple import statements. For example:
import java.util.*; //it imports all the class of the java.util package
Interface Section
interface car{
void start();
void stop();
}
Class Definition
In this section, we define the class. It is a vital part of a Java program. Without the class,
we cannot create any Java program. A Java program may contain more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a Java
program. It contains information about user-defined methods, variables, and constants. Every
Java program has at least one class that contains the main() method. For example:
}
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters. It is used during the
execution of the program. We can also decide and define the scope of variables by using the
modifiers. It defines the life of the variables. For example:
In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In other words, it is
an entry point of the class. It must be inside the class. Inside the main method, we create
objects and call the methods. We use the following statement to define the main() method:
}
For example:
Naming Convention
Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is
known as convention not rule. These conventions are suggested by several Java communities
such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language
are given according to the Java naming convention. If you fail to follow these conventions, it
may generate confusion or erroneous code.
The following table shows the popular conventions used for the different identifiers.
Java follows camel-case syntax for naming the class, interface, method, and variable. If the
name is combined with two words, the second word will start with uppercase letters such as
actionPerformed(), firstName, ActionEvent, ActionListener, etc.
Data Types
Every individual bit of data that is processed every day is categorized into types. The type of
data is known as datatype. Java uses various kinds of data types. However the data types are
mainly of two categories:
a. Primitive Data Types: These data types are already hard coded into the compiler to be
recognized when the program is executed.
b. Non-Primitive Data Types: These data types are special types of data which are user
defined, i,e, the program contains their definition.
Java primitive data types are the ones which are predefined by the programming language
which in this case is Java. Without primitive data types it would be impossible to frame
programs. Primitive data types are also the building blocks of Non-primitive data types
a. int
b. float
c. char
d. boolean
e. byte
f. short
g. long
h. double.
int data type
Example
int a=56;
Example
float a=98.7f;
● char as the name suggests is useful for storing single value characters.
● Its default value is ‘\u0000’ with the max value being ‘\uffff’
● It has a size of 2 bytes.
● ‘/u000’ is the unicode format which java uses inplace of ASCII
Example
char a=’D’;
● boolean is a special datatype which can have only two values ‘true’ and ‘false’.
● It has a default value of ‘false’
● size of the boolean is 1 byte.
● It comes in use for storing flag values
Example
boolean flag=true;
Example
byte a = 10;
Example
short a= 54;
Example
long a= 1273762;
● This is similar to the float data type. However it has one advantage over float data type
i.e, it has two bit precision over the float data type which has one bit precision.
● However it still shouldnt be used for precision sensitive data such as currency.
● It has a range of -2^31 to (2^31)-1.
● It has a size of 8 bytes
Example
double DataFlair=99.987d;
These are the datatypes which have instances like objects. Hence they are called
reference variables. They are primarily classes, arrays, strings and interfaces.
Classes
These are the special user defined data type. It has member variables and class methods. They
are blueprinted by objects
Arrays
Arrays are special memory locations that can store a collection of homogeneous data.
They are indexed. Arrays always start indexing from 0. Dynamic allocation of arrays is there in
Java. Arrays in Java can be passed as method parameters, local variables and static fields.
Example
Strings
Example:
String sub=s.substring(0,9);
Interfaces
These are similar to classes. However there is one prime difference, i,.e the methods are
abstract by default. i.e, they have no body. Similarly, like objects, interfaces are also the
blueprints of a class. If the class implements an interface, then it is supposed to add detail to
every function of the interface. If not, then we must declare the class as abstract.
Literals in Java
literals are the constant values that appear directly in the program. It can be assigned directly to
a variable to provide a value to the variable.
In the above code snippet, int is the datatype, age is the variable name and 21 is the
literal. So, we can say that the literal is providing the variable with a value of 21.
Generally, there are 5 types of literals that can be further expanded into various other literals.
● Integer Literal
● Float/Double Literal
● Character Literal
● Boolean Literal
● String Literal
Integer Literal: Integer literals are basically a number sequence that doesn’t contain any
decimal point in between them. There are four types of Integer Literals:
1. Decimal Integer: They are integers having a base value of 10; i.e; containing values
between 0 to 9. It can be a positive value(+) or a negative value(-) but it cannot contain any
point in between them.
int decimal_int=1234;
2. Octal Integer: They are integers having a base value of 8; i.e; containing values between 0
to 7. All octal numbers must start with a 0.
int octal_int=077;
3. Hexadecimal Integer: They are integers having a base value of 16; i.e; containing values
between 0 to 15. It is a special type of integer that contains both digits as well as characters.
The digits range from 0 to 9 and the numbers 10 to 15 are replaced by characters a to f. Any
integer starting with 0x or 0X is considered to be a hexadecimal integer.
int hexadec_int=0x1ff2;
4. Binary Integer: They are integers with a base value of 2; i.e; contains only two digits 0 and 1.
Binary integers start with a 0b indicating that it is a binary digit.
int binary_int=0b1010101;
Floating Point Literal: Floating-point literals are values that contain a decimal point in between
them. Floating-point literals are generally double data type by default. We can assign them to
float data types by adding an f at the end of the value.
float val_float=1.7732f;
float val_double=1.7732; //By default the compiler assigns double data type.
float val_double=1.7732d;
double val_double=1.7732;
Boolean Literal: A boolean literal is a literal that contains only two values true and false. It is
declared using the keyword boolean. It is a very useful literal to declare flag variables in different
programs to terminate a looping sequence.
Example
boolean flag1=true;
String Literal: A string is basically an array of characters. In java, we have a special class for
strings that allows users to implement strings to a program very easily. Anything written inside a
double quote is a string “”.
Example
Null Literal: Strings in java can also be declared void with a special literal known as null literal.
It is basically equivalent to an integer value of 0.
Example
String null_Literal=null;
Character Literal: Character Literals in java are represented with a single quote. The general
difference between string literal and character literal is that character literal contains only one
character whereas string literal contains a set of characters. A character literal can be
represented in four ways:
Example:
char ch = ‘A’;
Example:
Example:
\0 Null Character
When Java executes a program, the values are stored in containers called variables. It is the
name of a memory location. It is also a basic unit of storage. Variables must be declared before
they are used and the changes in variables make actual changes in the memory location.
<datatype><variable_name>=<Variable_value>
Example
int i=76;
String s=”DataFlair”;
Types of Variables and its Scope
● Instance Variables
● Class Variables
● Local Variables
Instance Variables: A variable which is declared inside a class, but is declared outside any
methods and blocks is known as instance variable.
Class Variables: A variable which is declared inside a class, outside all the blocks and is
declared as static is known as class variable.
Local Variables: All variables which are not instance or class variables are known as local
variables.
Operators in Java
Operator is a symbol used to perform operations. For example: +, -, *, / etc. There are many
types of operators in Java which are given below:
● Unary Operator
● Arithmetic Operator
● Shift Operator
● Relational Operator
● Bitwise Operator
● Logical Operator
● Ternary Operator
● Assignment Operator
Operator Category Precedence Associativity
Type
Control Statements
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 statements. Java
supports three types of control flow, viz., decision making, loop and jump statements.
Decision-Making statements
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.
● Simple if statement
● if-else statement
● if-else-if ladder
● Nested if-statement
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
if(condition) {
statement 1; //executes when condition is true
}
Example
public class SimpleIf {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output
x + y is greater than 20
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
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Example
x + y is greater than 20
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
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Example
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Example
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
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.
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
● for loop
● while loop
● do-while loop
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.
Syntax
//block of statements
Example
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.
Syntax
//statements
Example
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 the 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.
Syntax
while(condition){
//looping statements
}
Example.
Output
0
2
4
6
8
10
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 iterations is not known and we have to execute the loop
at least once, we can use a 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.
Syntax
do{
//statements
} while (condition);
Example
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.
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.
Syntax
break;
Example
}
}
}
Output
0
1
2
3
4
5
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.
Syntax
continue;
Example
Arrays in Java are index-based, the first element of the array is stored at the 0th index,
2nd element is stored on the 1st index and so on. Unlike C/C++, we can get the length of the
array using the length member.
In Java, an 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
dimensional or multidimensional arrays in Java.
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
Syntax
dataType arr[];
arrayRefVar=new datatype[size];
Example
//Java Program to illustrate how to declare, instantiate, initialize and traverse the array.
class Array{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
//Java Program to illustrate the use of declaration, instantiation and initialization of Java array in
//a single line
class Array{
public static void main(String args[]){
int a[]={33,3,4,5}; //declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output
33
3
4
5
The 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.
Passing Array to a Method: We can pass the java array to method so that we can reuse the
same logic on any array.
Anonymous Array: Java supports the feature of an anonymous array, so you don't need to
declare the array while passing an array to the method.
class ReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Output
10
30
50
90
60
dataType []arrayRefVar[];
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Array2D{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output
123
245
445
class JaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
class MatrixAddition{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
268
6 8 10
Multiplication of 2 Matrices
Strings
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In Java, string is
basically an object that represents a sequence of char values. An array of characters works the
same as Java string. In java, string is an immutable object which means it is constant and can
cannot be changed once it has been created
Creating a String
There are two ways to create a String in Java
● String literal
● Using new keyword
String literal: In java, Strings can be created by assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";
The problem with this approach: As I stated in the beginning that String is an object in Java.
However we have not created any string object using the new keyword above. The compiler
does that task for us: it creates a string object having the string literal (that we have provided , in
this case it is “Welcome”) and assigns it to the provided string instances.
But if the object already exist in the memory it does not create a new Object rather it assigns the
same old object to the new instance, that means even though we have two string instances
above(str1 and str2) compiler only created on string object (having the value “Welcome”) and
assigned the same to both the instances. For example there are 10 string instances that have
the same value, it means that in memory there is only one object having the value and all the 10
string instances would be pointing to the same object.
What if we want to have two different objects with the same string? For that we would need to
create strings using new keywords.
Using New Keyword: As we saw above, when we tried to assign the same string object to two
different literals, the compiler only created one object and made both of the literals point to the
same object. To overcome that approach we can create strings like this:
● char charAt(int index): It returns the character at the specified index. Specified index
value should be between 0 to length() -1 both inclusive. It throws
IndexOutOfBoundsException if index<0||>= length of String.
● boolean equals(Object obj): Compares the string with the specified string and returns
true if both matches else false.
● boolean equalsIgnoreCase(String string): It works the same as equals method but it
doesn’t consider the case while comparing strings. It does a case insensitive
comparison.
● int compareTo(String string): This method compares the two strings based on the
Unicode value of each character in the strings.
● int compareToIgnoreCase(String string): Same as CompareTo method however it
ignores the case during comparison.
● boolean startsWith(String prefix, int offset): It checks whether the substring (starting
from the specified offset index) is having the specified prefix or not.
● boolean startsWith(String prefix): It tests whether the string is having specified prefix,
if yes then it returns true else false.
● boolean endsWith(String suffix): Checks whether the string ends with the specified
suffix.
● int hashCode(): It returns the hash code of the string.
● int indexOf(int ch): Returns the index of first occurrence of the specified character ch in
the string.
● int indexOf(int ch, int fromIndex): Same as indexOf method however it starts
searching in the string from the specified fromIndex.
● int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
● int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts
searching from fromIndex.
● int indexOf(String str): This method returns the index of first occurrence of specified
substring str.
● int lastindexOf(String str): Returns the index of last occurrence of string str.
● String substring(int beginIndex): It returns the substring of the string. The substring
starts with the character at the specified index.
● String substring(int beginIndex, int endIndex): Returns the substring. The substring
starts with a character at beginIndex and ends with the character at endIndex.
● String concat(String str): Concatenates the specified string “str” at the end of the
string.
● String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
● boolean contains(CharSequence s): It checks whether the string contains the
specified sequence of char values. If yes then it returns true else false. It throws a
NullPointerException of ‘s’ is null.
● String toUpperCase(Locale locale): Converts the string to upper case string using the
rules defined by specified locale.
● String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
● public String intern(): This method searches the specified string in the memory pool
and if it is found then it returns the reference of it, else it allocates the memory space to
the specified string and assigns the reference to it.
● public boolean isEmpty(): This method returns true if the given string has 0 length. If
the length of the specified Java String is non-zero then it returns false.
● public static String join(): This method joins the given strings using the specified
delimiter and returns the concatenated Java String
● String replaceFirst(String regex, String replacement): It replaces the first occurrence
of a substring that fits the given regular expression “regex” with the specified
replacement string.
● String replaceAll(String regex, String replacement): It replaces all the occurrences of
substrings that fits the regular expression regex with the replacement string.
● String[] split(String regex, int limit): It splits the string and returns the array of
substrings that matches the given regular expression. limit is a result threshold here.
● String[] split(String regex): Same as split(String regex, int limit) method however it
does not have any threshold limit.
● String toLowerCase(Locale locale): It converts the string to lowercase string using the
rules defined by the given locale.
● public static String format(): This method returns a formatted java String
● String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
● String trim(): Returns the substring after omitting leading and trailing white spaces from
the original string.
● char[] toCharArray(): Converts the string to a character array.
● static String copyValueOf(char[] data): It returns a string that contains the characters
of the specified character array.
● static String copyValueOf(char[] data, int offset, int count): Same as above method
with two extra arguments – initial offset of subarray and length of subarray.
● void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the
characters of src array to the dest array. Only the specified range is being
copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
● static String valueOf(): This method returns a string representation of passed
arguments such as int, long, float, double, char and char array.
● boolean contentEquals(StringBuffer sb): It compares the string to the specified string
buffer.
● boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It
compares the substring of input to the substring of specified string.
● boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int
destoffset, int len): Another variation of regionMatches method with the extra boolean
argument to specify whether the comparison is case sensitive or case insensitive.
● byte[] getBytes(String charsetName): It converts the String into sequence of bytes
using the specified charset encoding and returns the array of resulted bytes.
● byte[] getBytes(): This method is similar to the above method; it just uses the default
charset encoding for converting the string into sequence of bytes.
● int length(): It returns the length of a String.
● boolean matches(String regex): It checks whether the String is matching with the
specified regular expression regex.
● int codePointAt(int index):It is similar to the charAt method however it returns the
Unicode code point value of specified index rather than the character itself
Immutable String in Java: A String is an unavoidable type of variable while writing any
application program. String references are used to store various attributes like username,
password, etc. In Java, String objects are immutable. Immutable simply means unmodifiable or
unchangeable. Once a String object is created its data or state can't be changed but a new
String object is created.
Let's try to understand the concept of immutability by the example given below:
class TestImmutableString{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin (strings are immutable objects)
}
}
Output
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar". But if we explicitly assign it to the reference
variable, it will refer to the "Sachin Tendulkar" object.
For example:
class TestImmutableStrings{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output
Sachin Tendulkar
StringBuffer
StringBuffer class is used to create a mutable string object. It means, it can be changed after it
is created. It represents a growable and writable character sequence. It is similar to the String
class in Java; both are used to create strings, but stringbuffer objects can be changed. So the
StringBuffer class is used when we have to make a lot of modifications to our string. It is also
thread safe i.e multiple threads cannot access it simultaneously.
● StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
● StringBuffer(int size): It creates an empty string and takes an integer argument to set
capacity of the buffer.
● StringBuffer(String str): It creates a stringbuffer object from the specified string.
● StringBuffer(charSequence []ch): It creates a stringbuffer object from the
charsequence array.
In this example, we are creating a string buffer object using the StringBuffer class and also
testing its mutability.
StringBuffer append(CharSequence csq, int start, int end) Appends the specified
portion of the character sequence to the original string
char charAt(int index) Returns the character at the specified index position
int codePointAt(int index) Returns the codepoint character at the specified index
StringBuffer delete(int start, int end) Deletes the characters from the StringBuffer
starting from the specified start index to end index
void ensureCapacity(int capacity) Ensures that the StringBuffer has the minimum specified
capacity
int indexOf(String str) Returns the index of the specified substring present in the string
StringBuffer insert(int offset, String str) Inserts the specified string at the specified index
int lastIndexOf(String str) Returns the index of the last occurrence of the specified substring
StringBuffer replace(int start, int end, String str) Replaces the substring with the specified
string starting from the start index till the end index
void setCharAt(int index, char ch) Sets the specified character at the specified index in the
input string
void setLength(int newLength) Sets the new length of the character string
String subString(int start, int end) Returns a substring of the string starting from the specified
start index to end index
https://www.tutorialstonight.com/
https://www.indeed.com/
https://www.baeldung.com/
https://dzone.com/
https://data-flair.training/
https://beginnersbook.com/
https://www.javatpoint.com/
https://www.tutorialcup.com/