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

Java Unit1

The document provides an overview of object-oriented programming (OOP) and its significance in software development, highlighting concepts such as encapsulation, inheritance, and polymorphism. It contrasts procedural programming with OOP, emphasizing the benefits of modularity, reusability, and data security. Additionally, it covers the history of Java, its applications, and the roles of JVM, JRE, and JDK in the Java ecosystem.

Uploaded by

fastgamer651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views34 pages

Java Unit1

The document provides an overview of object-oriented programming (OOP) and its significance in software development, highlighting concepts such as encapsulation, inheritance, and polymorphism. It contrasts procedural programming with OOP, emphasizing the benefits of modularity, reusability, and data security. Additionally, it covers the history of Java, its applications, and the roles of JVM, JRE, and JDK in the Java ecosystem.

Uploaded by

fastgamer651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit I: Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping

with
complexity, abstraction mechanisms. A way of viewing world Agents, responsibility, messages, methods, History of
Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators, expressions, control
statements, type conversion and casting, simple java program, concepts of classes, objects, constructors, methods,
access control, this keyword, garbage collection, overloading methods and constructors, method binding, inheritance,
overriding and exceptions, parameter passing, recursion, nested and inner classes, exploring string class.

Need for oop paradigm

Object-oriented programming (OOP) has become a fundamental paradigm in software development, revolutionizing the way
we design, implement, and maintain complex systems. By organizing code into reusable objects with their own properties and
behaviors, the four pillars of OOP are code organization, modularity, and scalability. We will delve into the need for object-
oriented programming, exploring its key principles, benefits, and real-world applications. By understanding the fundamental
concepts and advantages of OOP, we can appreciate its significance in modern software development and gain insights into
how it shapes the way we build and maintain software systems.
There are several reasons why object-oriented programming (OOP) is essential in modern software development. Here are
some key points highlighting the need for OOP:
1. Code Organization and Reusability: OOP allows developers to organize code into reusable objects. Objects
encapsulate data and behaviors, making it easier to manage and maintain complex systems. With OOP, code can be
modularized, promoting reusability and reducing redundancy. This leads to more efficient development, as developers
can leverage existing code components instead of reinventing the wheel.
2. Modularity and Scalability: OOP promotes modularity, breaking down complex systems into smaller, manageable
components. Each object has its own defined responsibilities and interactions, making the overall system easier to
understand and maintain. This modular approach also enables scalability, as new objects can be added or modified
without affecting the entire system. This flexibility allows for seamless updates and expansions as the software evolves
with features of object-oriented programming.
3. Encapsulation and Data Security: OOP emphasizes encapsulation, which means that objects contain both data
(attributes) and methods (behaviors). Encapsulation protects data integrity by allowing controlled access to the internal
state of an object. This enhances data security and reduces the risk of unintentional data manipulation, as objects
control their own data and expose only necessary interfaces to other objects.
4. Inheritance and Code Reuse: OOP supports inheritance, where new classes can inherit properties and behaviors from
existing classes. Inheritance facilitates code reuse, as common functionalities can be defined in a base class and
inherited by derived classes. This reduces code duplication, improves code organization, and enhances maintainability.
Inheritance also allows for polymorphism, where objects of different types can be treated interchangeably, increasing
code flexibility and extensibility.
5. Collaboration and Teamwork: OOP enables effective collaboration among software development teams. By
providing a standardized way of organizing code and defining interactions between objects, OOP allows multiple
developers to work concurrently on different parts of a system without conflicts. This promotes teamwork, simplifies
code integration, and streamlines the development process.
6. Real-World Modeling: OOP closely aligns with real-world concepts, making it easier to model and represent real-
world entities and their relationships in code. OOP provides a natural and intuitive way to translate complex real-world
systems into software solutions. This makes OOP particularly well-suited for applications such as simulations, games,
graphical user interfaces (GUIs), and object-oriented databases.
In summary, the need for object-oriented programming stems from its ability to improve code organization, enhance
reusability, facilitate modularity and scalability, ensure data security, promote collaboration, and provide a natural way to
model real-world systems. By leveraging the principles and advantages of OOP, developers can build robust, maintainable,
and adaptable software systems that meet the demands of today's complex applications.
Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is divided into small In object-oriented programming, the program is divided into
parts called functions. small parts called objects.

Object-oriented programming follows a bottom-up


Procedural programming follows a top-down approach.
approach.

Object-oriented programming has access specifiers like


There is no access specifier in procedural programming.
private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any proper way of Object-oriented programming provides data hiding so it
hiding data so it is less secure. is more secure.

In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming.

In procedural programming, there is no concept of data hiding In object-oriented programming, the concept of data hiding
and inheritance. and inheritance is used.

In procedural programming, the function is more important In object-oriented programming, data is more important than
than the data. function.

Procedural programming is based on the unreal world. Object-oriented programming is based on the real world.

Procedural programming is used for designing medium-sized Object-oriented programming is used for designing large
programs. and complex programs.

Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.

Code reusability absent in procedural programming, Code reusability present in object-oriented programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

summary of oop concepts


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

An Object can be defined as an instance of a class.

An object contains an address and takes up some space in memory.

Objects can communicate without knowing the details of each other's data or code.

The only necessary thing is the type of message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.

Class

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

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to
draw something, for example, shape, triangle, rectangle, etc.

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

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction

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

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

Encapsulation

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

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

A way of viewing world Agents, responsibility, messages, methods

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

Messages and Methods


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

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

Classes and Instances


In object-oriented programming, all objects are instances of a class. The method invoked by an object in response to a
message is decided by the class. All the objects of a class use the same method in response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request (message), the class creates an
instance of it and uses a suitable method to solve the problem.

Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes (objects) of a community. This
graphical representation shows classes listed in a hierarchical tree-like structure. In this more abstract class listed near the top
of the tree, and more specific classes in the middle of the tree, and the individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical inheritance structure. A child class
inherits properties from the parent class that higher in the tree.

Method Binding, Overriding, and Exception


In the class hierarchy, both parent and child classes may have the same method which implemented individually. Here, the
implementation of the parent is overridden by the child. Or a class may provide multiple definitions to a single method to
work with different arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the class of this receiver. If no suitable
method is found, the search is performed in the parent class of it. The search continues up the parent class chain until either a
suitable method is found or the parent class chain is exhausted. If a suitable method is found, the method is executed.
Otherwise, an error message is issued.
History of Java

The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team
members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early
'90s.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given
significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team
of sun engineers called Green Team.

2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

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

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

Why Java was named as "Oak"?


5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?

7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The suggested words
were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team
members preferred Java than other names.

8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java
name was chosen by James Gosling while having a cup of coffee nearby his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released
in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added
to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

Applications using Java: There are mainly 4 type of applications that can be created using java

a. Standalone Application:

It is also known as desktop application or window-based application. An application that we

need to install on every machine such as media player, antivirus etc. AWT and Swing are used

in java for creating standalone applications.

b. Web Application:

An application that runs on the server side and creates dynamic page, is called web application.

Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in

java.

c. Enterprise Application:

An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating

enterprise applications.

d. Mobile Application:

An application that is created for mobile devices. Currently Android and Java ME are used for

creating mobile applications.

JDK, JRE, JVM

JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a
specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the
configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JRE

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

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

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

JVM (Java Virtual Machine) Architecture


1. Java Virtual Machine
2. Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java
bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to
choose the algorithm. Its implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of
JVM is created.

What it does

The JVM performs following operation:


o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by
the classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads
the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package
classes, java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It
loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from
classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in
another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS
libraries.

Java buzzwords

The primary objective of Java programming language creation was to make it portable, simple and secure programming
language. Apart from this, there are also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
ADVERTISEMENT

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that incorporate both data and behavior.Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes
into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the local disk.

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is
fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the
internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also
supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

Data types in java

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types
available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need
to declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that
track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example: Boolean one = false


Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because
a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example:

byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an
integer.

Example:

short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Example:

int a = 100000, int b = -200000

Long Data Type

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

ADVERTISEMENT

Example:

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


Float Data Type

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

Example:

float f1 = 234.5f

Double Data Type

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

Example:

double d1 = 12.3

Char Data Type

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

Example:

char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system.

Variables in Java

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

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

Variable

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

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method
and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

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

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

3) Static variable

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

Example to understand the types of variables in java

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

Java Variable Example: Widening

public class Simple{


public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)

public class Simple{


public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}

Output:

10.5
10

Java Variable Example: Overflow

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

Output:

130
-126

Scope and lifetime of a variables


Local Variables:
Local variables are those that are declared inside of a method, constructor, or code block. Only the precise block in
which they are defined is accessible. The local variable exits the block's scope after it has been used, and its memory is
freed. Temporary data is stored in local variables, which are frequently initialized in the block where they are declared.
The Java compiler throws an error if a local variable is not initialized before being used. The range of local variables is
the smallest of all the different variable types.

Example:

public SumExample
{
public void calculateSum() {
int a = 5; // local variable
int b = 10; // local variable
int sum = a + b;
System.out.println("The sum is: " + sum);
} // a, b, and sum go out of scope here
}

Output:

The sum is: 15

Instance Variables:
Within a class, but outside of any methods, constructors, or blocks, instance variables are declared. They are accessible
to all methods and blocks in the class and are a part of an instance of the class. If an instance variable is not explicitly
initialized, its default values are false for Boolean types, null for object references, and 0 for numeric kinds. Until the
class instance is destroyed, these variables' values are retained.

Example:

public class Circle {


double radius; // instance variable
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Class Variables (Static Variables):
In a class but outside of any method, constructor, or block, the static keyword is used to declare class variables, also
referred to as static variables. They relate to the class as a whole, not to any particular instance of the class. Class
variables can be accessed by using the class name and are shared by all instances of the class. Like instance variables,
they have default values, and they keep those values until the program ends.

Example:

public class Bank {


static double interestRate; // class variable
// ...
}

Method Parameters:
Variables that are supplied to a method when it is invoked are known as method parameters. They serve as inputs for
method execution and are used to receive values from the caller. The scope of method parameters is restricted to the
method in which they are defined, making them local to that method. The values of the arguments given are allocated
to the respective parameters when a method is called.

Example:

public void printName(String name) { // name is a method parameter


System.out.println("Hello, " + name + "!");
}
Arrays
Definition of Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

Java array is an object that contains elements of similar data type.


It is a data structure where we store similar elements.
We can store only fixed set of elements in a java array.
Array in java is index based; first element of the array is stored at index 0.
An array is an indexed collection of fixed number of homogeneous data elements.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array.
Single Dimensional Array:

Single dimensional array declaration:

Syntax: Datatype arrayname[ ]; Or

Datatype[ ] arrayname;

Example:

int a[ ];

Example:

int[ ] a;//valid
int[5] a;//invalid

Creation of Array construction:

Every array in java is an object hence we can create by using new operator.
Syntax for Creating:

arrayname=new datatype[size];

Example :

a= new int[3];

we can also combine declaration and creation into one step

Syntax Datatype[ ] arrayname= new datatype[size];

Example:

int[] a=new int[3];


 At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.

Example :

int[] a=new int[3];

int[] a=new int[];//C.E:array dimension missing


Array initialization:

Syntax for initialization of Single Dimensional Array:

arrayname[subscript]=value;

Example:

int[] a=new int[4];

a[0]=10;

a[1]=20;

a[2]=30;

a[3]=40;

a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4

a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4

Diagram:

Note:if we are trying to access array element with out of range index we will
get RuntimeException saying ArrayIndexOutOfBoundsException

Declaration construction and initialization of an array in a single line:

 We can perform declaration construction and initialization of an array in a single line.

Example:

int [] a={10,20,30};//valid

String[] s={"abc","def","jog","lmn”};(valid)

Array Length:

length Vs length():

length:

 It is the final variable applicable only for arrays.


 It represents the size of the array.

length() method:

 It is a final method applicable for String objects.


 It returns the no of characters present in the String.
Example on Single Dimensional Array:

class Testarray1

{
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

2. Multidimensional Array

Two dimensional array

 In java multidimensional arrays are implemented as array of arrays approach but not matrix
form.
 The main advantage of this approach is to improve memory utilization.

Two dimensional array declaration:

Datatype arrayname[ ]
[ ]; Or Datatype[ ][ ]
arrayname;

Alternate two dimensional array Declaration Syntax

int [ ][ ]a;

int [ ][ ]a;
int a[ ] [ ]; All are valid statements

int [ ] [ ]a;

int [ ] a[ ];

int [ ]a[ ];

Example :

Creation of Two- Dimensional array:

syntax:

arrayname=new datatype[size]

Example:

int a[ ] [ ];

a=new int[3][2];

we can also combine declaration and creation into one step

Syntax

Datatype[ ][ ] arrayname= new datatype[size] [size];

Variable Size Array:


int[][] a=new int[3][];
a[0]=new int[2];

a[1]=new int[4];
a[2]=new int[3];

Two- Dimensional array Array initialization :

Syntax for initialization of Two- Dimensional Array:

datatype [subscript][subscript] arrayname ={list of value};

Example:

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

Diagram:

If we want to use this short cut compulsory we should perform declaration, construction and
initialization in a single line. If we are trying to divide into multiple lines then we will get compile
time error.

Two Dimensional array length

Length variable applicable only for arrays where as length()method is applicable for String objects.

Example :
int[][] a=new int[6][3];
System.out.println(a.length);//6
System.out.println(a[0].length);//3
Examples on Two Dimensional array

Example 1: program to declare,create,initialize and access the elements of


2-D 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:1 2 3
245
445

Example 2 : program for Addition of two matrix

class twodarrayaddition

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 : 2 6 8

6 8 10
Anonymous Arrays:
Sometimes we can create an array without name such type of nameless arrays are called
anonymous arrays.

The main objective of anonymous arrays is “just for instant use”.


We can create anonymous array as follows.

new int[]{10,20,30,40}; (valid)


new int[][]{{10,20},{30,40}}; (valid)

At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.

Example :

new int[3]{10,20,30,40};//C.E:';' expected(invalid)

Advantage of Java Array

o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of
the code will be improved

Disadvantage of Java Array

o Fixed in size that is once we created an array there is no chance of increasing or decreasing
the size based on our requirement that is to use arrays concept compulsory we should know
the size in advance which may not possible always.
o We can resolve this problem by using collections.

Jagged Array in Java


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

//Java Program to illustrate the jagged array


class TestJaggedArray{
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
}
}
}
Test it Now

Output:

012

3456
78

You might also like