Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views52 pages

Programming Language Types and Paradigm: CS1303 - Object Oriented Programming Unit - I Java Fundamentals

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

CS1303 – Object Oriented Programming

Unit - I Java Fundamentals

Programming Language types and paradigms – Object Oriented Programming Concepts-


History of Java - Java buzzwords- JVM architecture – Java Source File Structure – Naming
Convention – Data Types – Literals in Java- Scope and life time of variables – Operators in
Java- Control Statements in Java - Array – String and StringBuffer

Programming Language types and Paradigm

A programming paradigm is a way, an approach, a style by which we write programs in a


specific programming language to solve some problem, otherwise Programming paradigms are
a way to classify programming languages based on their features

Types of Programming Paradigms

The programing paradigms are categorized in multiple categories yet most significant are only
two:

1. Imperative programming paradigm


2. Declarative programming paradigm

1. Imperative programming paradigm

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

● Simple to implement and manually visualize


● Use of control flow statements
● Easy to read and learn

Disadvantage

● Unable to solve complex problems


● Programs can't execute parallel
● Less productive, can't difficult to tackle modern day problems
● More risk of error

The imperative is broadly divided into 3 subcategories:

1. Procedural programming paradigm

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

In this type of programming, a program is processed by dividing it into multiple


processors. The system contains multiple processors to solve the problem in less time.

2. Declarative programming paradigm

A declarative programming paradigm are those paradigms in which the programmer


describes the property of the result without focusing on how to achieve it (imperative
programming focuses on how to achieve the task by changing the state of the program). The
approach of this programming is to create some object or elements within the program. The
main focus in this kind of programming is what is to be done rather than how it should be done.
It does not talk about the work process of the result and only describes what the program must
accomplish.

Declarative programming is used in programming languages used in a database query,


regular expression, functional programming, logical programming, etc. Some of the
programming languages that support the declarative paradigm are:

● Prolog
● javascript
● Scala
● Lisp
● SQL
● XQuery
● Clojure

Code Example:

In the example below there is a code of language supporting declarative programming,


it's an SQL code. See how it talks about selecting a specific book without focusing on how to
achieve it.

SELECT * FROM Books

WHERE Category='Programming'

AND language='english';
Declarative programing can further be subcategorized into 3 main categories:

1. Logic programming paradigm

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.

2. Functional programming paradigm

Functional programming is the programming in which a program is constructed by


creating and using functions. Rather than a series of statements functional programming
uses function to map and change one value to another value. Functional programming is
the key feature of JavaScript.

const sumOfSquaresOfEven = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

.filter(num => num % 2 === 0)

.map(even => even * even)

.reduce((x, y) => x + y);

3. Database programming approach

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

List of programming languages and the programming paradigms they support.

C++ Monolithic, Structured-oriented, Procedural-oriented and, Object-oriented

programming paradigm

Python Object Oriented, Procedure, and Functional programming paradigms

Java Procedural and object oriented paradigm

JavaScript functional, object-oriented, procedural, and prototypal programming

C# imperative, declarative, functional, generic, object-oriented (class-based), and

component-oriented

PHP Procedural, Object-Oriented, and functional paradigm

Ruby procedural, object-oriented, and functional programming

Visual Basic object-oriented


Object Oriented Programming Concepts

Object-oriented programming: It is a programming model based on the concept of objects


and classes. In this model, programmers define the functions that can be applicable to the data
structures and their data type. Object-oriented programming turns data structure into an object,
including both data and functions. It encourages the reusing of these objects in the same and
other programmes as well

Building blocks of Object Oriented Programming

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.

Basic concept of Object Oriented Programming

The four basic concepts of object-oriented programming are inheritance, polymorphism,


abstraction and encapsulation.

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.

There are the five different variations in inheritance in OOP languages:

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.

Hierarchical inheritance: In this variation of inheritance, the different child classes


inherit a single parent class. For example, a parent class C can have three subclasses,
D, E and F.

Hybrid inheritance: If there is a combination of more than one type of inheritance, it is a


hybrid inheritance. It can be a combination of simple, multiple and hierarchical
inheritances

2. Polymorphism

If one task is performed in different ways, it is known as polymorphism. Polymorphism is


the core concept of the object-oriented programming language that allows programmers to build
logical codes. In this concept of OOP, programmers can access objects of different types
through the same interface where each type provides its own implementation of the interface.

The following two types of polymorphism are useful in OOP:

Compile-time polymorphism: Also called static binding polymorphism, it means


binding occurs at compile time. Method overloading is an example of compile-time
polymorphism. It allows programmers to use objects of the same name while their
parameters can be different.

Runtime polymorphism: Runtime polymorphism involves dynamic binding. Method


overriding is an example of runtime polymorphism. In this process, an object binds with
the functionality at the run time

3. Abstraction

Hiding internal details and showing functionality is known as abstraction. It allows


programmers to be abstract or pick out common features of the objects and procedures. The
primary aim of programmers behind using abstraction is to handle complexity by hiding
irrelevant details. It is an extension of encapsulation.

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.

Java Virtual Machine


Java Virtual Machine (JVM) is an engine that provides a runtime environment to drive
the Java Code or applications. It converts Java bytecode into machine language. JVM is a part
of Java Runtime Environment (JRE). In other programming languages, the compiler produces
machine code for a particular system. However, Java compiler produces code for a Virtual
Machine known as Java Virtual Machine

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

Java's dynamic class loading functionality is handled by the ClassLoader subsystem. It


loads links. and initializes the class file when it refers to a class for the first time at
runtime, not compile time.
1.1 Loading: Classes will be loaded by this component. BootStrap ClassLoader,
Extension ClassLoader, and Application ClassLoader are the three ClassLoaders that
will help in achieving it.
BootStrap ClassLoader: Responsible for loading classes from the bootstrap classpath,
nothing but rt.jar. Highest priority will be given to this loader.
Extension ClassLoader: Responsible for loading classes which are inside the ext folder
(jre\lib).
Application ClassLoader: Responsible for loading Application Level Classpath, path
mentioned Environment Variable, etc.
The above ClassLoaders will follow Delegation Hierarchy Algorithm while loading the
class files.

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.

2. Runtime Data Area

The Runtime Data Area is divided into five major components:

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.

Operand stack: If any intermediate operation is required to perform, operand


stack acts as runtime workspace to perform the operation.

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.

Intermediate Code Generator – Produces intermediate code

Code Optimizer – Responsible for optimizing the intermediate code generated


above

Target Code Generator – Responsible for Generating Machine Code or Native


Code
Profiler – A special component, responsible for finding hotspots, i.e. whether the
method is called multiple times or not.

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.

Java Source File Structure

A typical structure of a Java program contains the following elements:

● 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:

//First Java Program

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:

/**It is an example of documentation comment*/


Package Declaration

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 mypack; //where mypack is the package name

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.Scanner; //it imports the Scanner class only

import java.util.*; //it imports all the class of the java.util package

Interface Section

It is an optional section. We can create an interface in this section if required. We use


the interface keyword to create an interface. An interface is slightly different from the class. It
contains only constants and method declarations. Another difference is that it cannot be
instantiated. We can use interfaces in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword. For example:

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 Student{ //class definition

}
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:

class Student{ //class definition

String sname; //variable


int id;
double percentage;
}

Main Method Class

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:

public static void main(String args[]) {

}
For example:

public class Student{ //class definition


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

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.

Identifier Naming Rule Example


Type

Class ● It should start with the uppercase public class Employee{


letter. //code snippet
● It should be a noun such as Color, }
Button, System, Thread, etc.
● Use appropriate words, instead of
acronyms.

Interface ● It should start with the uppercase interface Printable{


letter. //code snippet
● It should be an adjective such as }
Runnable, Remote, ActionListener.
● Use appropriate words, instead of
acronyms.

Method ● It should start with lowercase letter. class Employee{


● It should be a verb such as main(), // method
print(), println(). void draw(){
● If the name contains multiple words, //code snippet
start it with a lowercase letter }
followed by an uppercase letter }
such as actionPerformed().

Variable ● It should start with a lowercase class Employee{


letter such as id, name. // variable
● It should not start with the special int id;
characters like & (ampersand), //code snippet
$ (dollar), _ (underscore). }
● If the name contains multiple words,
start it with the lowercase letter
followed by an uppercase letter
such as firstName, lastName.
● Avoid using one-character variables
such as x, y, z.

Package ● It should be a lowercase letter such //package


as java, lang. package com.mypack;
● If the name contains multiple words, class Employee{
it should be separated by dots (.) //code snippet
such as java.util, java.lang. }
Constant ● It should be in uppercase letters class Employee{
such as RED, YELLOW. //constant
● If the name contains multiple words, static final int MIN_AGE = 18;
it should be separated by an //code snippet
underscore(_) such as }
MAX_PRIORITY.
● It may contain digits but not as the
first letter.

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.

Examples are- int,float etc.

b. Non-Primitive Data Types: These data types are special types of data which are user
defined, i,e, the program contains their definition.

Examples are- classes, interfaces etc.

Primitive Data Types in Java

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

There are 8 types of Java primitive data types namely:

a. int
b. float
c. char
d. boolean
e. byte
f. short
g. long
h. double.
int data type

● int is used for storing integer values.


● Its size is 4 bytes and has a default value of 0.
● The maximum value of integer is 2^31 and the minimum value is -2^31.
● It can be used to store integer values unless there is a need for storing numbers larger or smaller
than the limits

Example

int a=56;

float data type

● float is used for storing decimal values.


● Its default value is 0.0f and has a size of 4 bytes.
● It has an infinite value range. However it's always advised to use float in place of double
if there is a memory constraint.
● Currency should also never be stored in float data type. However it has a single
precision bit.

Example

float a=98.7f;

char data type

● 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 data type

● 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;

byte data type

● It’s an 8 bit signed two’s complement .


● The range of values are -128 to 127.
● It is space efficient because it is smaller than integer data types.
● It can be a replacement for int data type usage but it doesn’t have the size range as the
integer datatype.

Example

byte a = 10;

short data type

● This data type is also similar to the integer datatype.


● However it’s 2 times smaller than the integer datatype.
● Its minimum range is -32,768 and maximum range is 32,767.
● It has a size of 2 bytes

Example

short a= 54;

long data type

● This datatype primarily stores huge sized numeric data.


● It is an 8 byte integer and ranges from -2^63 to +(2^63)-1.
● It has a size of 8 bytes and is useful when you need to store data which is longer than int
datatype.

Example

long a= 1273762;

double data type

● 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;

Non-primitive Data Types

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

int arr[] = new int[100];

This creates a storage space for 100 integers

Strings

String is a collection of characters but in Java String is a completely different class


altogether. It’s located in java.lang.String. However, strings end with a ‘\0’ character. Java has a
lot of methods for manipulating strings such as substring, length and many more.

Example:

String s=”DataFlair is a fun place to learn”;

String sub=s.substring(0,9);

System.out.println(sub); //output : DataFlair

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.

An example of assigning a literal to a variable is:

int age = 21;

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.

Types of Literals in Java

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.

Example: 1000, 1234, +78, -82, etc.

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.

Example: 012, 077,075, etc.

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.

Example: 0xff, 0x2a, 0xf1f2, etc.

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.

Example: 0b100101, 0b1010101, etc.

int binary_int=0b1010101;

Binary literals can be created only on Java SE 7 and above.

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.

Example of declaring a float literal

float val_float=1.7732f;

Example of declaring a double literal

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

String Company = “DataFlair”; //Valid String Literal

String Company = DataFlair; //Invalid as there is no double quote.

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:

1. Single quote character:

Example:

char ch = ‘A’;

2. Character Literal as an Integer Literal:

Example:

char number = 0065;

3. Unicode representation of character Literal:

Example:

char uni = ‘\u0065’;


4. Escape Sequence: It is a special kind of character literal which is preceded by a \. Each
and every escape sequence has a special feature. Some of the most used escape
sequences are:

Escape Sequence Functionality

\n Used to insert a new line.

\t Used to insert a horizontal tab.

\b Used to insert a blank space.

\v Used to insert a Vertical tab.

\a Used to add a small beep sound.

\’ Used to add a single quote inside a string.

\” Used to add double quotes inside a String.

\\ Used to add a backslash

\r Used for carriage return.

\? Used to add a Question mark

\0n Used to represent an octal number

\xHn Used to represent Hexadecimal number

\uHn Used to represent Unicode CharacterThrough its hex code.

\0 Null Character

\f Used to represent form feed

Scope and lifetime of variables

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.

Syntax for declaring variable is

<datatype><variable_name>=<Variable_value>

Example

int i=76;

String s=”DataFlair”;
Types of Variables and its Scope

There are three types of variables.

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

Scope: Throughout the class except in the static methods.

Lifetime: Until the object of the class stays in the memory.

Class Variables: A variable which is declared inside a class, outside all the blocks and is
declared as static is known as class variable.

Scope: Throughout the class.

Lifetime: Until the end of the program.

Local Variables: All variables which are not instance or class variables are known as local
variables.

Scope: Within the block it is declared.

Lifetime: Until control leaves the block in which it is declared.

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

Unary postfix expr++ expr-- Not associative

prefix ++expr --expr +expr -expr ~ ! Right to Left

Arithmetic multiplicative */% Left to Right

additive +- Left to Right

Shift shift << >> >>> Left to Right

Relational comparison < > <= >= instanceof Right to Left

equality == != Left to Right

Bitwise bitwise AND & Left to Right

bitwise exclusive OR ^ Left to Right

bitwise inclusive OR | Left to Right

Logical logical AND && Left to Right

logical OR || Left to Right

Ternary ternary ?: Right to Left

Assignment assignment = += -= *= /= %= &= ^= |= Right to Left


<<= >>= >>>=

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.

1. Decision Making statements


● if statements
● switch statement
2. Loop statements
● do while loop
● while loop
● for loop
● for-each loop
3. Jump statements
● break statement
● continue statement

Decision-Making statements

As the name suggests, decision-making statements decide which statement to execute


and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types of
decision-making statements in Java, i.e., If statement and switch statement.

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

public class IfElse {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}
else {
System.out.println("x + y is greater than 20");
}
}
}
Output

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

public class IfElseLadder {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output
Delhi

Nested if-statement: In nested if-statements, the if statement can contain a if or if-else


statement inside another if or else-if statement.

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

Points to be noted about switch statement:


● The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
● Cases cannot be duplicate
● Default statement is executed when any of the cases doesn't match the value of the
expression. It is optional.
● Break statement terminates the switch block when the condition is satisfied.
● It is optional, if not used, the next case is executed.
● While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Syntax
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example
public class Switch{
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output
2

While using switch statements, we must notice that the case expression will be of the same type
as the variable. However, it will also be a constant value. The switch permits only int, string, and
Enum type variables to be used.

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while


some condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.

● 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

for(initialization, condition, increment/decrement) {

//block of statements

Example

public class ForLoop {


public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output
The sum of first 10 natural numbers is 55

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

for(data_type var : array_name/collection_name){

//statements

Example

public class ForEach {


public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name : names) {
System.out.println(name);
}
}
}
Output
Printing the content of the array names:
Java
C
C++
Python
JavaScript

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.

public class WhileLoop {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output

Printing the list of first 10 even numbers

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

public class Calculation {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output
Printing the list of first 10 even numbers
0
2
4
6
8
10

Jump Statements

Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the other part of
the program. There are two types of jump statements in Java, i.e., break and continue.

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

public class Break {


public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6

Example for break statement with labeled for loop

public class BreakFor {


public static void main(String[] args) {
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}

}
}
}
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

public class ContinueExample {


public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output
0
1
2
3
5
1
2
3
5
2
3
5
Arrays

An array is a collection of similar types of elements which has contiguous memory


location. Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.

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

● Single Dimensional Array


● Multidimensional Array

Single Dimensional Array

Syntax

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

Instantiation of an Array in Java

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:

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

//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

For-each Loop for Array

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.

//Java Program to print the array elements using for-each loop


class Array{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Output
33
3
4
5

Passing Array to a Method: We can pass the java array to method so that we can reuse the
same logic on any array.

Example to get the minimum number of an array using a method.

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


class ArrayMin{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Output:
3

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.

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

public class AnonymousArray{


//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66}); //passing anonymous array to method
}
}
Output
10
22
44
66

Returning Array from the Method

//Java Program to return an array from 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

ArrayIndexOutOfBoundsException: The Java Virtual Machine (JVM) throws an


ArrayIndexOutOfBoundsException if length of the array is negative, equal to the array size or
greater than the array size while traversing the array.

//Java Program to demonstrate the case of ArrayIndexOutOfBoundsException in a Java Array.

public class ArrayException{


public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Multidimensional Array: In such cases, data is stored in row and column based index (also
known as matrix form).

Syntax to Declare Multidimensional Array

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array

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

Example to initialize Multidimensional Array in Java

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.

//Java Program to illustrate the use of multidimensional 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

Jagged Array:If we are creating an odd number of columns in a 2D array, it is known as a


jagged array. In other words, it is an array of arrays with different numbers of columns.

//Java Program to illustrate the jagged array

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++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output
012
3456
78

Let's see a simple example of adding two matrices.

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

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

//Java Program to multiply two matrices

public class MatrixMultiplication{


public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++){
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}
Output
666
12 12 12
18 18 18

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:

String str1 = new String("Welcome");


String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same string

Java String Methods


Here are the list of the methods available in the Java String class. These methods are explained
in the separate tutorials with the help of examples. Links to the tutorials are provided below:

● 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 defines 4 constructors.

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

Example: Creating a StringBuffer Object

In this example, we are creating a string buffer object using the StringBuffer class and also
testing its mutability.

public class Demo {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Sachin");
System.out.println(sb);
// modifying object
sb.append(" Tendulkar");
System.out.println(sb); // Output: Sachin Tendulkar
}
}
Output
Sachin
Sachin Tendulkar

Methods in StringBuffer class

StringBuffer append(String s) Appends the specified string to the original string

StringBuffer append(CharSequence csq, int start, int end) Appends the specified
portion of the character sequence to the original string

int capacity() Returns the current capacity of the StringBuffer

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

StringBuffer deleteCharAt(int index) Deletes the character at the specified 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

int length() Returns the number of characters of the string

StringBuffer replace(int start, int end, String str) Replaces the substring with the specified
string starting from the start index till the end index

StringBuffer reverse() Reverses the characters in the specified string

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

String toString() Returns the string representation of the StringBuffer object

void trimToResize() Trims the storage size of the CharacterSequence


References

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/

You might also like