Unit 1-Introduction and Overview of Java Language
Unit 1-Introduction and Overview of Java Language
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. There
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 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 chosen java name 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 of 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 coffee near his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
1
Programming in JAVA Unit 1
Introduction and Overview of Java Language
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(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 the new
features in Java.
Up to JDK 1.0.1, private and protected keywords could be used together to create yet another form of
protection which used to act as a restriction to methods or variables mainly to subclasses of a given
class. In JDK 1.0.2, this capability has been removed.
3
Programming in JAVA Unit 1
Introduction and Overview of Java Language
It includes some specific features: Modularization of the JDK under Project Jigsaw, Provided Money and
Currency API, Tight integration with JavaFX, Java implementation of reactive streams, More Concurrency
Updates, Provided Java Linker,Automatic scaling and sizing.
Features of Java
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.
Java Features
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because: Java syntax is based on C++ (so
easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
4
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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
incorporates both data and behavior. Object-oriented programming (OOPs) is a methodology
that simplifies software development and maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is 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 the top of other hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be run 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:
No explicit pointer
Java Programs run inside a virtual machine sandbox
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.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
5
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Security Manager: It determines what resources a class can access such as reading and writing
to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Robust simply means strong. Java is robust because: It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
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.
6
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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 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).
1 Origin The C language is based The C++ language is based The Java programming
on BCPL. on the C language. language is based on both C
and C++.
3 Approach It uses the top-down It uses the bottom-up It also uses the bottom-up
approach. approach. approach.
5 Code Execution The code is executed The code is executed The code is executed by the
directly. directly. JVM.
7
Programming in JAVA Unit 1
Introduction and Overview of Java Language
7 Translator It uses a compiler only to It also uses a compiler only Java uses both compiler and
translate the code into to translate the code into interpreter and it is also
machine language. machine language. known as an interpreted
language.
8 File Generation It generates the .exe, and It generates .exe file. It generates .class file.
.bak, files.
9 Number of There are 32 keywords in There are 60 keywords in There are 52 keywords in the
Keyword the C language. the C++ language. Java language.
10 Source File The source file has a .c The source file has a .cpp The source file has a .java
Extension extension. extension. extension.
11 Pointer Concept It supports pointer. It also supports pointer. Java does not support the
pointer concept because of
security.
12 Union and It supports union and It also supports union and It does not support union
Structure structure data types. structure data types. and structure data types.
Datatype
13 Pre-processor It uses pre-processor It uses pre-processor It does not use directives but
Directives directives such as directives such as #include, uses packages.
#include, #define, etc. #define, #header, etc.
16 Memory It uses the calloc(), It uses new and delete It uses a garbage collector to
Management malloc(), free(), and operator to manage the manage the memory.
realloc() methods to memory.
manage the memory.
17 Overloading It does not support the Method and operator Only method overloading
overloading concept. overloading can be can be achieved.
achieved.
8
Programming in JAVA Unit 1
Introduction and Overview of Java Language
18 goto Statement It supports the goto It also supports the goto It does not support the goto
statement. statement. statements.
19 Used for It is widely used to It is widely used for system It is used to develop web
develop drivers and programming. applications, mobile
operating systems. applications, and windows
applications.
20 Array Size An array should be An array should be declared An array can be declared
declared with size. For with size. without declaring the size.
example, int num[10]. For example, int num[].
Technical definition: The JVM is the specification for a software program that executes code and
provides the runtime environment for that code.
Everyday definition: The JVM is how we run our Java programs. We configure the JVM's settings and
then rely on it to manage program resources during execution.
9
Programming in JAVA Unit 1
Introduction and Overview of Java Language
JVM Architecture
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.
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.
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.
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.
10
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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.
7) Execution Engine
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
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.
JRE
Java Run-time Environment (JRE) is the part of the Java Development Kit (JDK). It is a freely available
software distribution which has Java Class Library, specific tools, and a stand-alone JVM. It is the most
common environment available on devices to run java programs. The source Java code gets compiled
and converted to Java bytecode. If you wish to run this bytecode on any platform, you require JRE. The
JRE loads classes, verify access to memory, and retrieves the system resources. JRE acts as a layer on the
top of the operating system.
11
Programming in JAVA Unit 1
Introduction and Overview of Java Language
12
Programming in JAVA Unit 1
Introduction and Overview of Java Language
13
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming language that
makes it popular. Using the Java programming language, we can develop a wide variety of applications.
So, before diving in depth, it is necessary to understand the basic structure of Java program in detail. In
this section, we have discussed the basic structure of a Java program. At the end of this section, you will
able to develop the Hello world Java program, easily.
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the programmer because they help
Section them understand the code. These are optional, but we suggest you use them because they are useful to
understand the operation of the program, so you must write comments within the program.
Package statement You can create a package with any name. A package is a group of classes that are defined by a name. That
is, if you want to declare many classes within one element, then you can declare it within a package. It is an
optional part of the program, i.e., if you do not want to declare any package, then there will be no problem
with it, and you will not get any errors. Here, the package is a keyword that tells the compiler that package
14
Programming in JAVA Unit 1
Introduction and Overview of Java Language
has been created.
It is declared as:
package package_name;
Import statements This line indicates that if you want to use a class of another package, then you can do this by importing it
directly into your program.
Example:
import calc.add;
Interface Interfaces are like a class that includes a group of method declarations. It's an optional section and can be
statement used when programmers want to implement multiple inheritances within a program.
Class Definition A Java program may contain several class definitions. Classes are the main and essential elements of any
Java program.
Main Method Class Every Java stand-alone program requires the main method as the starting point of the program. This is an
essential part of a Java program. There may be many classes in a Java program, and only one class defines
the main method. Methods contain data type declaration and executable statements.
EXAMPLE:
15
Programming in JAVA Unit 1
Introduction and Overview of Java Language
main is a method; this is a starting point of a Java program.
You will notice that the main method code has been moved to some spaces left. It is
called indentation which used to make a program easier to read and understand.
String[] args It is an array where each element of it is a string, which has been named as "args". If your Java
program is run through the console, you can pass the input parameter, and main() method takes it as
input.
System.out.println(); This statement is used to print text on the screen as output, where the system is a predefined class,
and out is an object of the PrintWriter class defined in the system. The method println prints the
text on the screen with a new line. You can also use print() method instead of println() method. All
Java statement ends with a semicolon.
Java Tokens
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the smallest
element of the Java program. The Java compiler identified these words as tokens. These tokens are
separated by the delimiters. It is useful for compilers to detect errors.
16
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Keywords: These are the pre-defined reserved words of any programming language. Each keyword has
a special meaning. It is always written in lower case. Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
21. import 22. instanceof 23. int 24. interface 25. long
31. public 32. return 33. short 34. static 35. super
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also known as
17
Programming in JAVA Unit 1
Introduction and Overview of Java Language
a special kind of identifier that is used in the goto statement. Remember that the identifier name must
be different from the reserved keywords. There are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals are as
follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
18
Programming in JAVA Unit 1
Introduction and Overview of Java Language
"javatpoint" String
Operators: In programming, operators are the special symbol that tells the compiler to perform a
special operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Separators: The separators in Java is also known as punctuators. There are nine separators in Java, are
as follows ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets represents the
single-dimensional array, two pairs of square brackets represent the two-dimensional array.
19
Programming in JAVA Unit 1
Introduction and Overview of Java Language
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The Java
compiler treats comments as whitespaces. Java provides the following two types of comments:
int is used for storing integer values. Its size is 4 bytes and has a default value of 0. The maximum values
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;
20
Programming in JAVA Unit 1
Introduction and Overview of Java Language
import java.io.IOException;
class TypeVariable
<class names should be meaningful and never start with lowercase letter, refer the naming
convention of a class>
21
Programming in JAVA Unit 1
Introduction and Overview of Java Language
{
public static void main(String[] args) throws IOException {
int a = 10;
short s = 2;
byte b = 6;
long l = 125362133223l;
float f = 65.20298f;
double d = 876.765d;
System.out.println("The integer variable is " + a);
System.out.println("The short variable is " + s);
System.out.println("The byte variable is " + b);
System.out.println("The long variable is " + l);
System.out.println("The float variable is " + f);
System.out.println("The double variable is " + d);
}
}
Output
The integer variable is 10
The short variable is 2
The byte variable is 6
The long variable is 125362133223
The float variable is 65.20298
The double variable is 876.765
These are the datatypes which have instances like objects. Hence they are called reference variables.
They are primarily classes, arrays, strings or interfaces.
a. Classes in Java
These are the special user defined data type. It has member variables and class methods. They are
blueprinted by objects.
b. Interfaces in Java
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.
c. Strings in Java
You may be knowing string as 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
d. Arrays in Java
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.
24
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Control Flow/Structure in Java
Java compiler executes the java code from top to bottom. The statements 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 flow statements.
Java provides three types of control flow statements.
Decision-Making statements:
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the condition result. 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 condition result that is a Boolean value, either true or false. In
java, there are four types of if-statements given below.
if statement
if-else statement
else-if statement
Nested if-statement
Let's understand the if-statements one by one.
1. if statement:
This 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 of if statement is given below.
if(<condition>) {
//block of code
}
Consider the following example in which we have used the if statement in the java code.
3. lse-if statement
The 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 any block of code. We can also define an else statement at the end of the chain.
Consider the following example.
4. Nested if-statement
In nested if-statements, the if statement contains multiple if-else statements as a separate block of
code. Consider the following example.
26
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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 enables us to check
the variable for the range of values defined for multiple case statements. The switch statement is easier
to use instead of if-else-if statements. It also enhances the readability of the program. The syntax to use
the switch statement is given below.
switch <variable> {
Case <option 1>:
//block of statements
..
..
..
Case <option n>:
//block of statements
Default:
//block of statements
}
Consider the following example to understand the flow of the switch statement.
public class Student implements Cloneable {
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");
27
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java 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. The syntax to use the for loop is given below.
for(<initialization>, <condition>, <increment/decrement>)
{
//block of statements
}
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
28
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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
Java
C
C++
Python
JavaScript
29
Programming in JAVA Unit 1
Introduction and Overview of Java Language
The flow chart for the while loop is given in the following image.
0
2
4
6
8
10
30
Programming in JAVA Unit 1
Introduction and Overview of Java Language
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in java.
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
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.
Java 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 the current flow. It is used to break the loop and
switch statement. However, it breaks only the inner loop in the case of the nested loop.
31
Programming in JAVA Unit 1
Introduction and Overview of Java Language
The break statement cannot be used independently in the java program, i.e., it can only be written
inside the loop or switch statement.
}
}
}
32
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Output:
0
1
2
3
4
5
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
33
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Java Arrays
Normally, an array is a collection of similar type 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.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator.
In Java, 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 dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
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 in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
34
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
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
33
3
4
5
35
Programming in JAVA Unit 1
Introduction and Overview of Java Language
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java 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.
for(data_type variable:array)
{
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
3
4
5
In such case, data is stored in row and column based index (also known as matrix form).
36
Programming in JAVA Unit 1
Introduction and Overview of Java Language
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.
Output:
123
245
445
37
Programming in JAVA Unit 1
Introduction and Overview of Java Language
Important Questions:
1. Discuss Java History.
2. Explain Java Features
3. Discuss how Java Differs from C and C++
4. Explain JVM.
5. Explain Java Environment
6. Discuss Java Programming Structure with suitable example.
7. Discuss Java Tokens with example.
8. Explain various Data types in Java.
9. Explain Conditional Statements in java with example.
10. Explain Looping Statements in java with example.
11. Explain various Jumping Statements in java with example.
12. What is Array? How do you define and access array elements in Java.
38