Java Unit1
Java Unit1
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.
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:
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.
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, 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.
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
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.
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.
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 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.
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 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.
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.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
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.
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:
need to install on every machine such as media player, antivirus etc. AWT and Swing are used
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
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.
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:
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) 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
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
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.
PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
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.
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
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 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.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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.
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:
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:
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:
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:
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
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
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:
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
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.
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.
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
Output:
10
10.0
Output:
10.5
10
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
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:
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:
Example:
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:
Normally, array is a collection of similar type of elements that have contiguous memory location.
Datatype[ ] arrayname;
Example:
int a[ ];
Example:
int[ ] a;//valid
int[5] a;//invalid
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];
Example:
Example :
arrayname[subscript]=value;
Example:
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
Example:
int [] a={10,20,30};//valid
String[] s={"abc","def","jog","lmn”};(valid)
Array Length:
length Vs length():
length:
length() method:
class Testarray1
{
public static void main(String args[]){
Output :
33
2. Multidimensional 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.
Datatype arrayname[ ]
[ ]; Or Datatype[ ][ ]
arrayname;
int [ ][ ]a;
int [ ][ ]a;
int a[ ] [ ]; All are valid statements
int [ ] [ ]a;
int [ ] a[ ];
int [ ]a[ ];
Example :
syntax:
arrayname=new datatype[size]
Example:
int a[ ] [ ];
a=new int[3][2];
Syntax
a[1]=new int[4];
a[2]=new int[3];
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.
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
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
class twodarrayaddition
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.
At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.
Example :
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
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.
Output:
012
3456
78