Java UNIT 1-1
Java UNIT 1-1
HISTORY OF JAVA:
Java is a General Purpose, class based, object oriented, Platform independent, portable,
Architecturally neutral, multithreaded, dynamic, distributed, Portable and robust interpreted
Programming Language developed by James Gosling along with two other person ‘Mike Sheridan‘
and ‘Patrick Naughton‘ at sun micro-systems in 1991. Initially it was named oak Programming
Language but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of
1992 and the public announcement of java in the spring of 1995, many more people contributed to
the design and evolution of the language. Bill Joy, Frank Yellinand Tim Lindholmwere key
contributors to the maturing of the original prototype.
Five Goals which were taken into consideration while developing Java:
1) In 1990, sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A team of sun mocrosystems programmers headed
by James Gosling was formed to undertake this task
2) In 1991, after exploring the possibility of using the most popular object oriented language C+
+, the team announced new language called “Oak”.
3) In 1992, the team known as Green Project Team ny sun, demonstrated the applications of
their new language to control a list of home appliances using a handheld device with a tiny
sensitive screen.
4) In 1993, the World Wide Web (WWW) appeared as internet and transformed the text based
internet into a graphical rich environment. The Green Project Team came up with the idea of
developing web applets using the new language that could run on all types of computers
connected to the internet.
5) 1n 1994, the team developed a web browser called “Hot Java” to locate and run applet
programs on internet.
6) In 1995, Oak was renamed “JAVA” due to some legal snags.
7) In 1996, Java established itself not only as a leader for internet programming but also as a
general purpose Object Oriented Programming language.
Java is related to C++, which is a direct descendant of C. Much of the character of Java is inherited
from these two languages. From C, Java derives its syntax. Many of Java’s object-oriented features
were influenced by C++. The most important striking feature is that it is platform-neutral language.
MATEIN UNIT 1 JAVA PROGRAMMING|2
Java
Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0
[J2SE]).
Java is a programming language and a platform. Java is a high level, robust, secured and object-
oriented programming language. Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has its own runtime environment (JRE) and API, it
is called platform.
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.
Platform independent: Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted
by virtual Machine (JVM) on whichever platform it is being run.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java
would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Architectural-neutral: Java compiler generates an architecture-neutral object file format
which makes the compiled code to be executable on many processors, with the presence of
Java runtime system.
Portable: Being architectural-neutral and having no implementation dependent aspects of the
specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is
an incremental and light weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high performance.
Distributed: Java is designed for the distributed environment of the internet.
MATEIN UNIT 1 JAVA PROGRAMMING|3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FEATURES OF JAVA:
They are also known as java buzzwords. The Java Features given below are simple and easy to
understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
MATEIN UNIT 1 JAVA PROGRAMMING|4
Simple
According to Sun, Java language is simple because syntax is based on C++ (so easier for programmers
to learn it after C++). Removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc. No need to remove unreferenced objects because there is Automatic
Garbage Collection in java.
Object-oriented
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
simplify software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
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 software-based platform.
The Java platform differs from most other platforms in the sense that it's 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)
MATEIN UNIT 1 JAVA PROGRAMMING|5
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris, and 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).
Robust
Robust simply means strong. Java uses strong memory management. There is lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points make java robust.
Architecture-neutral
There is no implementation dependent feature e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may 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 shares the same memory. Threads are important for multi-media, Web
applications etc.
Secure:
The Java platform is designed with security features built into the language and runtime system
such as static type-checking at compile time and runtime checking (security manager), which let
you creating applications that can’t be invaded from outside. You never hear about viruses
MATEIN UNIT 1 JAVA PROGRAMMING|6
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To compile and run this program, you need to open command prompt. To compile and
run the above program, go to your current directory first; my current directory is c:\new .
Write here:
JVM stands for Java Virtual Machine. It is the engine that drives the java code. It is a medium which
compiles java code to bytecode which can be interpreted on different machines and hence it makes it
platform independent. Bytecode is an intermediary language between java source and the host
system.Mostly in other programming languages, compiler produce code for a particular system but
java complier produce code for a virtual machine. JVM generates .class file that can be interpreted and
run in any OS, but it should have a JVM within it, because JVM is system dependent. Java is called
platform independent because of JVM. as different computers with different operating systems have
their own JVM, when we submit '.class' file to any operating system, JVM interprets the bytecode into
machine level language. JVM is the main component of java architecture and it is the part of the JRE
(Java Runtime Environment). JVM is responsible to allocate the necessary memory needed by the java
program and also to de-allocate a memory space. JIT is the part of the JVM that is used to speed up the
execution time.
Architecture:
The JVM specification defines the subsystems and their external behavior. The JVM has the following
major subsystems:
Class Loader: Responsible for reading Java source code and loading classes into the data areas.
Execution Engine: Responsible for executing instructions from the data areas.
The data areas occupy memory that is allocated by the JVM from the underlying OS.
MATEIN UNIT 1 JAVA PROGRAMMING|8
Class Loader
The JVM uses different class loaders organized into the following hierarchy:
The bootstrap class loader is the parent for other class loaders. It loads the core Java libraries
and is the only one written in native code.
The extension class loader is a child of the bootstrap class loader. It loads the extension
libraries.
The system class loader is a child of the extension class loader. It loads the application class
files that are found in the class path.
When a class loader receives a request to load a class, it checks the cache to see if the class has already
been loaded, then delegates the request to the parent. If the parent fails to load the class, then the
child attempts to load the class itself. A child class loader can check the cache of the parent class
loader, but the parent cannot see classes loaded by the child. The design is such because a child class
loader should not be allowed to load classes that are already loaded by its parent.
Execution Engine
The execution engine executes commands from the bytecode loaded into the data areas one by one.
To make the bytecode commands readable to the machine, the execution engine uses two methods.
Just-in-time (JIT) compilation. If a method is used frequently, the execution engine compiles
it to native code and stores it in the cache. After that, all commands associated with this
method are executed directly without interpretation.
Although JIT compilation takes more time than interpretation, it is done only once for a method that
might get called thousands of times. Running such method as native code saves a lot of execution
time compared to interpreting each command one by one every time it is encountered.
JIT compilation is not a requirement of the JVM specification, and it is not the only technique that is
used to improve JVM performance. The specification defines only which bytecode commands relate
to which native code; it is up to the implementation to define how the execution engine actually
performs this conversion.
MATEIN UNIT 1 JAVA PROGRAMMING|9
Memory Model
The Java memory model is built on the concept of automatic memory management. When an object
is no longer referenced by an application, a garbage collector discards it and this frees up memory.
This is different from many other programming languages, where you have to manually unload the
object from memory.
The JVM allocates memory from the underlying OS and separates it into the following areas.
Heap Space. This is a shared memory area used to hold the objects that a garbage collector
scans.
Method Area. This area was previously known as the permanent generationwhere loaded
classes were stored. It has recently been removed from the JVM, and classes are now loaded
as metadata to native memory of the underlying OS.
Native Area. This area holds references and variables of primitive types.
Breaking the heap up into generations ensures efficient memory management because the garbage
collector does not need to scan the whole heap. When a Java application creates an object, it is stored
in the eden pool of the heap. Once it is full, a minor garbage collection is triggered at the eden pool.
First, the garbage collector marks dead objects (those that are not referenced by the application any
more) and increments the age of live objects (the age is represented by the number of garbage
collections that the object has survived). Then the garbage collector discards dead objects and moves
live objects to the survivor pool, leaving the eden pool clear.
When a surviving object reaches a certain age, it is moved to the old generation of the heap:
the tenured pool. Eventually, the tenured pool fills up and a major garbage collection is triggered to
clean it up. There are different kinds of garbage collectors, some may be faster in certain situations
when performing a major garbage collection.
The heap size is dynamic. Memory is allocated to the heap only if it is required. When the heap fills
up, the JVM reallocates more memory, until the maximum is reached. Memory reallocation also
causes the application to stop briefly.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MATEIN UNIT 1 JAVA PROGRAMMING|10
C and Java are both power programming languages with many advantages. C is more of a procedure-
oriented programming language which means that there is a procedure to be written for certain tasks,
and programs are built by calling those procedures. Java is an object-oriented programming language
in which OOP is used to define classes. Programs written in C language compile to native machine
code which means that the programs written in C must be run on the platform they were compiled to
run on. Java compiles to Java byte code which runs on top of a Java virtual machine environment.
The byte code can be ported to different platforms and can be executed on different operating
systems.
Java is not like c but the major differences between Java and c is that Java is an Object Oriented
language and has mechanism to define classes and objects. To build a simple and safe language the
Java team did not include some of the c features in Java:
Java does not include the C unique statement keywords goto, sizeof and typedef.
Java is object oriented while C is procedure oriented (not object oriented).
Java is object oriented language while C++ is basically C with object oriented extension. Java
appears to be similar to C++ when we consider only the extension part of C++. Some major C++
features that were intentionally omitted from Java are:
Java uses a “Garbage Collector” which manages memory automatically so the programmer doesn’t
have to handle that. Variables in Java can be declared anywhere in a program. Java’s motto (so to
speak) is “write once run anywhere”. When you compile a Java program, an intermediate bytecode is
generated, which is interpreted by the Java Virtual Machine. This way you write a program once, and
the virtual machine translates the bytecode into instructions a specific processor can understand.
JAVA C++
Write once, run anywhere Write once, compile everywhere
Primitive data types always passed by value. Pointers, References, and pass by value are
Objects are passed by reference. supported.
MATEIN UNIT 1 JAVA PROGRAMMING|11
1. Pointers are supported by C++, where as Java does not support pointers.
2. Operator overloading and multiple inheritance are supported by c++where as Java does not.
3. Java is a platform independent language, where as C++ depends on different platforms and
machines.
4. Java utilizes both compiler and interpreter, where as C++ is only compiler.
within a machine" which understands Java bytecodes and translates them into machine language on
the target processor.
STEPS:
Follow the instructions to download java and run the .exe to install Java on your machine. Once you
installed Java on your machine, you would need to set environment variables to point to correct
installation directories:
ByteCode:
Bytecode is nothing but the intermediate representation of Java source code which is produced by the
Java compiler by compiling that source code. This byte code is an machine independent code. It is
notan completely a compiled code but it is an intermediate code somewhere in the middle which is
MATEIN UNIT 1 JAVA PROGRAMMING|13
later interpreted and executed by JVM. Bytecode is a machine code for JVM. But the machine code is
platform specific whereas bytecode is platform independent that is the main difference between
them. It is stored in .class file which is created after compiling the source code. Translating a Java
program into a bytecode makes it much easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each platform. The fact that a Java program is
executed by the JVM also helps to make it secure. Bytecode is a step between your source code and
actual machine code. The JVM is what takes the bytecode and translates it into machine code.When
you compile something in Java, the compiler generates bytecode. This is native code for the Java
Virtual Machine. The JVM then translates the bytecode to native code for your
processor/architecture; this is where the JIT happens. Without JIT, the JVM would translate the
program one instruction at a time, which is very slow. A Just in Time compiler (JIT) is used to
translate the byte code to machine code to speed up execution of class methods.
Lexical Tokens:
Computer languages, like human languages, have a lexical structure. A source code of a Java program
consists of tokens. Tokens are atomic code elements and also smallest individual units in a program
are known as Tokens. In Java we have white spaces, comments, identifiers, literals, separators, and
keywords.
White space
White space in Java is used to separate tokens in the source file. It is also used to improve readability
of the source code.
int i = 0;
White spaces are required in some places. For example, between the “int” keyword and the variable
name.
Identifiers
Identifiers are names for variables, methods, classes or parameters. Identifiers can have
alphanumerical characters, underscores and dollar signs ($). It is an error to begin a variable name
with a number. White space in names is not permitted.
MATEIN UNIT 1 JAVA PROGRAMMING|14
Identifiers are case sensitive. This means that Name, name or NAME refer to three different variables.
Identifiers also cannot match language keywords.
There are also conventions related to naming of identifiers. The names should be descriptive. We
should not use cryptic names for our identifiers. If the name consists of multiple words, each
subsequent word is capitalized.
String name23;
int _col;
shortcar_age;
Literals
Here we assign two literals to variables. Number 29 and string "Hungarian" are literals.
Separators
A separator is a sequence of one or more characters used to specify the boundary between separate,
independent regions in plain text or other data stream.
[] () {} , ; .
String language = "Java";
The double quotes are used to mark the beginning and the end of a string. The semicolon ;character is
used to end each Java statement. The various separators are as:
Keywords
A keyword is a reserved word in Java language. Keywords are used to perform a specific task in the
computer program. For example, to define variables, do repetitive tasks or perform logical operations.
packagecom.zetcode;
System.out.println(i);
Comments:
There are three types of comments defined by Java: Single line comment (//), Multiple line comment
(*/) and documentation comment. The third type of comment is used to produce an HTML file that
documents your program. The documentation comment begins with a /** and ends with a */.
MATEIN UNIT 1 JAVA PROGRAMMING|16
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
MATEIN UNIT 1 JAVA PROGRAMMING|17
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an int.
Example: byte a = 100 , byte b = -50
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a concern
about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, long b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
MATEIN UNIT 1 JAVA PROGRAMMING|18
This data type is generally used as the default data type for decimal values, generally the
default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char:
char data type is a single 16-bit Unicode character.
Minimum value is 0.
Maximum value is 65.
Char data type is used to store any character.
Example: char letterA ='A'
Variable:
Variable is name of reserved area allocated in memory. You must declare all variables before they
can be used. The basic form of a variable declaration is shown here:
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more
than one variable of the specified type, you can use a comma-separated list.
The Java compiler requires that variables should be initialized with some starting value before using
them in an operation. Following are valid examples of variable declaration and initialization in Java:
Local variables
Instance variables
Class/static variables
MATEIN UNIT 1 JAVA PROGRAMMING|19
Local Variable
A variable that is declared inside the method is called local variable. Local variables are declared in
methods, constructors, or blocks.Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method, constructor or block.Local
variables are visible only within the declared method, constructor or block.There is no default value
for local variables so local variables should be declared and an initial value should be assigned before
the first use.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable. It is not
declared as static. When a space is allocated for an object in the heap, a slot for each instance variable
value is created. Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed. Instance variables have default values. For numbers
the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned
during the declaration or within the constructor. Instance variables can be accessed directly by
calling the variable name inside the class. However within static methods and different class ( when
instance variables are given accessibility) should be called using the fully qualified
name . ObjectReference.VariableName.
Static variable
A variable that is declared as static is called static variable. It cannot be local. Class variables also
known as static variables are declared with the static keyword in a class, but outside a method,
constructor or a block. Static variables are stored in static memory. Static variables are created when
the program starts and destroyed when the program stops. Default values are same as instance
variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is
null. Values can be assigned during the declaration or within the constructor. Static variables can be
accessed by calling with the class name ClassName.VariableName.
NOTE: the area of the program where the variable is accessible is called its scope.
CONVERSION:
Java is strongly typed language. It also supports conversion between different reference types and
allows you to define how data types that you have created behave when converted to other types.
Consider the following code:
When this code is compiled, the following error message appears: “cannot implicitly convert int into
byte”. The problem here is that when we add two bytes together, the result will be returned as an int
because after adding two bytes together the compiler automatically converts them into ‘int’ type and
hence the result of addition is returned as int nor byte. If we want to store this result in byte variable,
we have to first convert it back to a byte.
Java supports 2c conversion mechanisms:
1) Implicit casting
2) Explicit casting
1. Implicit Conversion:
A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is
done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic
type conversion.
Examples:
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
In the above code 4 bytes integer value is assigned to 8 bytes double value.
2. Explicit conversion:
A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size.
This is not done implicitly by the JVM and requires explicit casting; a casting operation to be
performed by the programmer. The higher size is narrowed to lower size. Casting can be a dangerous
operation to perform. Even a simple cast from double to an int can cause problems.
In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises error. Let us
explicitly type cast it.
double x = 10.5;
int y = (int) x;
Explicit casting are potentially unsafe because it might cause loss of data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
OPERATORS IN JAVA:
Operator in java is a symbol that is used to perform operations. There are many types of operators in
java such as:
Arithmetic operators
Relational operators
Bitwise operators
Assignment operators
Conditional operators
Modules operators
Boolean operators
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
operator description
% remainder of division
Relational Operators:
Relational Operators are used for decision statements when we have to compare two quantities:
operator description
> Check if operand on the left is greater than operand on the right
Bitwise Operators:
Java defines several bitwise operators that can be applied to the integer types long, int, short, char and
byte. These operators are used for shifting the bits to right or left.
operator description
| Bitwise OR
MATEIN UNIT 1 JAVA PROGRAMMING|23
^ Bitwise exclusive OR
Assignment operator:
Assignment operators are used to assign the value of an expression to a variable. The various
assignment operators are:
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b
-= subtracts right operand from the left operand and assign the result to left a-=b is same as a=a-b
operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a
%b
Logical Operators:
Logical Operators are used to combine two or more relational expressions.
|| Logical OR (a || b) is true
Conditional operator ( ? : ):
Conditional operator is also known as the ternary operator and used to evaluate Boolean expression.
Modulus Operator:
The modulus operator % returns the remainder of a division operation. It can be applied to floating
point type as well as integer type.
For example:
Int x = 42;
System.out.println(“mod10 = “ + x% 10);
OPERATOR PRCEDENCE:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Unicode
Unicode is a computing industry standard designed to consistently and uniquely encodes characters
used in written languages throughout the world. The Unicode standard uses hexadecimal to express a
character. Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
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 0 index. Each element of an array
can be accessed with a combination of array name and the index number.
1) DECLARATION OF ARRAYS: Arrays are declared by fixing a set of square brackets to the
end of the varia\ble type followed by the array name i.e.
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
3) INITIALIZATION OF ARRAYS: Putting values into the array is known as initialization i.e.
MATEIN UNIT 1 JAVA PROGRAMMING|26
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only 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.
An array with a single index number is called linear array oe single dimensional array and the array
with two subscripts for single element is known as 2 dimensional array and so on.
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
1. arrayRefVar=new datatype[size];
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
In such case, data is stored in row and column based index (also known as matrix form).
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];//3 row and 3 column
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class Testarray3{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
MATEIN UNIT 1 JAVA PROGRAMMING|28
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Test it Now
Output:1 2 3
245
445
In java, array is an object. For array object, an proxy class is created whose name can be obtained by
getClass().getName() method on the object.
1. class Testarray4{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A program executes from top to bottom except when we use control statements, we can control the
order of execution of the program, based on logic and values.
In Java, control statements can be divided into the following three categories:
Selection Statements
MATEIN UNIT 1 JAVA PROGRAMMING|29
Iteration Statements
Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the basis of the outcome
of an expression or state of a variable known during runtime.
1. if: Statement(s) between the set of curly braces ‘{ }’ will be executed only if the condition(s),
between the set of brackets ‘( )’ after ‘if’ keyword, is/are true.
Syntax:
1 if(Condition) {
2 // statements;
3 }
2. if-else: If the condition(s) between the brackets ‘( )’ after the ‘if’ keyword is/are true then the
statement(s) between the immediately following set of curly braces ‘{ }’ will be executed else the
statement(s) under, the set of curly braces after the ‘else’ keyword will be executed.
Syntax:
1 if(condition) {
2 // statements;
3 } else{
4 // statements;
5 }
if(condition)
statements;
else if (condition)
statements;
else if(condition)
MATEIN UNIT 1 JAVA PROGRAMMING|30
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and the remaining
conditions will be bypassed. If none of the conditions are true then the else block will execute.
4. Switch: When there is a long list of cases & conditions, then if/if-else is not good choice as the code
would become complicated.
Syntax:
1 switch(expression)
2 {
3 casevalue1:
4 //statement;
5 break;
6 casevalue2:
7 //statement;
8 break;
9 default:
10 //statement;
11 }
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.
Example
1. public class WhileDemo
MATEIN UNIT 1 JAVA PROGRAMMING|31
2. {
3. public static void main( String[] args )
4. {
5. int i = 0;
6. while ( i < 5 )
7. {
8. System.out.println( "Value :: " + i );
9. i++;
10. }
11. }
12. }
The only difference between a while and a do-while loop is that do-while evaluates its expression at
the bottom of the loop instead of the top. The do-while loop executes at least one time then it will
check the expression prior to the next iteration.
Example
1. public class DoWhileDemo
2. {
3. public static void main( String[] args )
4. {
5. int i = 0;
6. do
7. {
8. System.out.println( "value :: " + i );
9. i++;
10. }
11. while ( i < 5);
12. }
13. }
A for loop executes a statement (that is usually a block) as long as the boolean condition evaluates to
true. A for loop is a combination of the three elements initialization statement, boolean expression
and increment or decrement statement.
Syntax:
for(<initialization>;<condition>;<increment or decrement statement>)
MATEIN UNIT 1 JAVA PROGRAMMING|32
{
<block of code>
}
The initialization block executes first before the loop starts. It is used to initialize the loop variable.
The condition statement evaluates every time prior to when the statement (that is usually be a block)
executes, if the condition is true then only the statement (that is usually a block) will execute.
The increment or decrement statement executes every time after the statement (that is usually a
block).
Example
1. public class WhileDemo
2. {
3. public static void main( String[] args )
4. {
5. int i = 0;
6. while ( i < 5 )
7. {
8. System.out.println( "Value :: " + i );
9. i++;
10. }
11. }
12. }
This was introduced in Java 5. This loop is basically used to traverse the array or collection elements.
Example
1. package com.deepak.main;
2.
3. public class ForEachDemo
4. {
5. public static void main( String[] args )
6. {
7. int[] i =
MATEIN UNIT 1 JAVA PROGRAMMING|33
8. { 1, 2, 3, 4, 5 };
9. for ( int j : i )
10. {
11. System.out.println( "value :: " + j );
12. }
13. }
14. }
Jump statements are used to unconditionally transfer the program control to another part of the
program.
Java provides the following jump statements:
break statement
continue statement
return statement
Break Statement
The break statement immediately quits the current iteration and goes to the first statement following
the loop. Another form of break is used in the switch statement.
Unlabeled Break Statement: This is used to jump program control out of the specific loop on the
specific condition.
Example
1. public class UnLabeledBreakDemo
2. {
3. public static void main( String[] args )
4. {
MATEIN UNIT 1 JAVA PROGRAMMING|34
5. for ( int var = 0; var < 5; var++ )
6. {
7. System.out.println( "Var is : " + var );
8. if ( var == 3 )
9. break;
10. }
11. }
12. }
Labeled Break Statement: This is used for when we want to jump the program control out of nested
loops or multiple loops.
Example
1. public class LabeledBreakDemo
2. {
3. public static void main( String[] args )
4. {
5. Outer: for ( int var1 = 0; var1 < 5; var1++ )
6. {
7. for ( int var2 = 1; var2 < 5; var2++ )
8. {
9. System.out.println( "var1:" + var1 + ", var2:" + var2 );
10. if ( var1 == 3 )
11. break Outer;
12. }
13. }
14. }
15. }
Continue Statement: The continue statement is used when you want to continue running the loop
with the next iteration and want to skip the rest of the statements of the body for the current
iteration.
This statement skips the current iteration of the innermost for, while and do-while loop.
Example
1. public class UnlabeledContinueDemo
2. {
3. public static void main( String[] args )
4. {
5. for ( int var1 = 0; var1 < 4; var1++ )
6. {
7. for ( int var2 = 0; var2 < 4; var2++ )
8. {
9. if ( var2 == 2 )
10. continue;
11. System.out.println( "var1:" + var1 + ", var2:" + var2 );
12. }
13. }
14. }
15. }
Labeled Continue Statement: This statement skips the current iteration of the loop with the specified
label.
Example
1. public class LabeledContinueDemo
2. {
3. public static void main( String[] args )
4. {
5. Outer: for ( int var1 = 0; var1 < 5; var1++ )
6. {
7. for ( int var2 = 0; var2 < 5; var2++ )
8. {
9. if ( var2 == 2 )
10. continue Outer;
11. System.out.println( "var1:" + var1 + ", var2:" + var2 );
12. }
13. }
14. }
15. }
Return Statement: The return statement is used to immediately quit the current method and return to
the calling method. It is mandatory to use a return statement for non-void methods to return a value.
Example
1. public class ReturnDemo
MATEIN UNIT 1 JAVA PROGRAMMING|36
2. {
3. public static void main( String[] args )
4. {
5. ReturnDemo returnDemo = new ReturnDemo();
6. System.out.println( "No : " + returnDemo.returnCall() );
7. }
8.
9. int returnCall()
10. {
11. return 5;
12. }
13. }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%