Unit - I Introduction To JAVA
Unit - I Introduction To JAVA
P
• Introduction to the IDE
PP
• Data types and wrapper classes, operators
• Control structures
• String handling
• Basic Input-output
History of Java
• Java is a high-level object-oriented programming language developed by
James Gosling and his colleagues at Sun Microsystems in 1991.
P
• It was developed keeping in mind the consumer electronics and communication
PP
equipments. Thus need of a platform independent language.
• The company promoted this software product with a slogan named “Write Once
Run Anywhere” that means it can develop and run on any device equipped with
Java Virtual Machine (JVM)
• This language is supported in all kinds of OS including Linux, Windows, Solaris etc.
P
PP
Java Evoution
P
PP
• A Java LTS (long-term support) release is
a version of Java that will remain the industry standard for
several years.
• E.g. Java 8 was released in 2014, it will continue to receive
updates until 2020, and extended support will end by 2025
Features of Java
• Simple
• Object-oriented
– Data and methods resides in a class.
• Robust :
– Reliable on various systems, Memory Management, Exception Handling
P
• Multithreaded
– Network programming
PP
• Architecture-neutral
• Interpreted
• Performance
• Distributed
• Dynamic
• Secure
• Portable 5
• Simple:
Features of Java
– Easy to learn & use effectively. Extends C & C++ so easy
for programmers
• Object Oriented:
– Everything in java is object oriented. All program code ,
P
methods and data resides in a class.
• Robust : PP
– A program must execute reliably in a various system.
– Main reason for program failure are
• Memory management problem &
• Mishandled exception condition.
– Java supports Garbage Collection and use inbuilt
Exception Handler to make it robust.
• Multithreading :
Features of Java
– Creating an interactive network program.
– A program may do many things simultaneously.
• Architectural-Neutral:
– Java designer main goal is that a code is long life and portable.
– If processor, OS upgrade java program is run successful.
– “Write once, run anywhere, any time, forever.”
P
• Interpreted and High Performance:
– Java enable the creation of cross-platform programs by byte code.
–
–
–
PP
Byte code interpreted by JVM (Java Virtual Machine).
Byte code converted into native code by JIT (Just In time compilation).
Java perform very well in low power CPU.
• Distributed:
– Java handles TCP/IP protocols.
– Allow two objects on different computers execute remotely with RMI
(Remote Method Invocation).
• Dynamic:
– Java allocates memory at runtime for classes, methods and objects. This
feature allows programmer to allocate memory when required.
Introduction To The Java
Programming Environment
Java is a concurrent, class-based, object-oriented programming and
runtime environment, consisting of:
– A programming language - Java
– Java APIs
– JVM
P
PP
8
Introduction To The Java
Programming Environment
A programming language Java:
•Java is a powerful and has been exceptionally successful in business
and enterprise computing.
•Java is an object-oriented programming language that runs on almost
all electronic devices.
P
•The current steward of Java is Oracle Corporation (who acquired
PP
Sun Microsystems, the originator of Java).
•Other corporations, such as Red Hat, IBM, Hewlett-Packard, SAP, Apple,
and Fujitsu are also heavily involved in producing implementations of
standardized Java technologies.
•There is also an open source version of Java, called OpenJDK, which
many of these companies collaborate on.
•Java actually comprises several different, but related environments and
specifications—Java Mobile Edition (Java ME), Java Standard Edition 9
(Java SE), and Java Enterprise Edition (Java EE).
Introduction To The Java
Programming Environment
Java APIs
•Java APIs are integrated pieces of software that come with JDKs. APIs in
Java provides the interface between two different applications and
establish communication.
• APIs in Java include classes, interfaces, and user Interfaces.
P
•They enable developers to integrate various applications and websites
PP
and offer real-time information.
10
Introduction To The Java Programming
Environment
Compiler & Interpreter
•A Compiler searches all the errors of a program and lists
P
them.
•If the program is error free then it converts the code of
PP
program into machine code and executed.
P
•Source Code -- Java Compiler -- Byte Code
PP
•Byte Code -- JVM -- Machine readable file
Introduction To The Java Programming
Environment
Java’s Magic : The Bytecode & JVM
•The output after compilation of java source code is not an executable code
but it is a Bytecode.
P
the Java run-time system, which is called the Java Virtual Machine (JVM)
PP
•JVM is an interpreter for bytecode.
•Security: Execution of every Java program is under the control of the JVM,
the JVM can contain the program and prevent it from generating side effects
outside of the system
Introduction To The Java Programming
Environment
JIT (Just-In-Time)
•JVM also has JIT compiler.
P
•JIT is a part of JVM.
PP
•JIT execute selected portion of Bytecode.
P
2. java – interpreter used to execute Java Bytecodes.
Syntax : java filename
PP
3. appletviewer - Used to view and test applets.
Syntax : appletviewer url
P
•JRE is only used by them who only wants to run the Java Programs i.e.
end users of your system.
PP
•The Java Runtime Environment, or JRE, is a software layer that runs on
top of a computer’s operating system software and provides
the class libraries and other resources that a specific Java program
needs to run.
16
Program is created in
Phase 1 Editor Disk the editor and stored
on disk.
Compiler creates
Compiler Disk byte codes and stores
Phase 2 them on disk.
Primary
Class Loader Memory
Phase 3
Class loader puts
Disk bytecodes in memory.
..
P
..
..
Primary
Phase 4 PP
Bytecode Verifier Memory Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
restrictions.
..
..
Primary
.. Interpreter reads
Interpreter
Phase 5 Memory bytecodes and
translates them into a
language that the
computer can
Introduction To The Java understand, possibly
storing data values as
..
Programming Environment ..
the program executes.
Introduction to the IDE
(Integrated Development Environment)
• It is a programming environment that provides comprehensive
facilities to computer programmers for software development.
• It combines all the basic tools that developers need to write or test
software.
P
• This type of environment allows an application developer to write
PP
code while compiling, debugging and executing it at the same place.
• It can be a standalone application or a part of one or more
compatible applications.
• Popular IDEs
– NetBeans
– jEdit
– Eclips
– JBuilder
18
– JCreator
PP
P
Data types
• There are two types of data types in Java:
P
• The primitive data types are boolean, char, byte, short, int, long, float and
double.
PP
– Non-primitive data types:
• These are created by the programmer and is not defined by Java (except for
String ).
• It can be used to call methods to perform certain operations
• The non-primitive data types are Classes, Interfaces, and Arrays.
20
PP
P
Data types
– Primitive data types:
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
P
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
float
double
PP
9,223,372,036,854,775,807
22
PP
P
Document Section
• Two types of comments
P
– Single line comment
• // insert comments here.
PP
– Block comment
• /*
insert comments here.
*/
• Package Statement
– package Package-Name
– E.g. package student
• Import Statement
– Import package-name.class-name
– E.g. import java.io.*
P
• Interface Statement
– It is similar to class but includes a group of method
PP
declaration. Used for multiple inheritance.
• Class definition
– A Java program can contain multiple class definitions
• Main Method Class
– Every java stand-alone application requires a ‘main’ method.
– The main method creates objects of various classes and
establishes a connection between them.
Softwares To Run Java Programs
• The NetBeans IDE runs on the Java platform, which means that you
can use it with any operating system for which there is a JDK
available. These operating systems include Microsoft Windows,
Solaris OS, Linux, and Mac OS X.
• Softwares:
P
• The Java SE Development Kit (JDK Latest version : 15.0.2)
PP
– For Microsoft Windows, Solaris OS, and Linux:
https://www.oracle.com/java/technologies/javase-jdk15-
downloads.html
• The NetBeans IDE (Latest version 12.2)
– For all platforms:
https://netbeans.apache.org/download/index.html
26
Program
/*
First Java Program
*/
public class First
P
{
public static void main ( String args[] )
{
PP
// Print a message.
System.out.println (“Welcome to GDCST”);
}
}
First Java Program In NetBeans
Creating Your First Application
Your first application, FirstApp, will simply display the message “This is
my first java program" To create this program, you will:
P
you can use the NetBeans IDE item
in the Start menu.
PP
28
In the NetBeans IDE, choose File | New Project....
P
PP
In the New Project wizard, expand the Java category as shown in the
following figure:
P
PP
Select Java Application as shown in the following figure:
P
PP
In the Name and Location page of the wizard, do the following (as
shown in the figure below):
In the Project Name field, type FirstApp.
In the Project Location: C:\JavaApps
In the Create Main Class field, type firstapp.FirstApp.
Click the Finish Button.
P
PP
The project is created and opened in the IDE. You should see the
following components:
P
The Source Editor window with a file called FirstApp.java open.
PP
The Navigator window, which you can use to quickly navigate between
elements within the selected class.
PP
P
Add JDK 8 to the Platform List (if necessary)
It may be necessary to add JDK 8 to the IDE's list of available platforms.
To do this, choose Tools | Java Platforms as shown in the following
figure:
P
PP
PP
P
Add Code to the Generated Source File
When you created this project, you left the Create Main Class checkbox
selected in the New Project wizard.
The IDE has therefore created a skeleton class for you. You can add the
“This is my first program in java" message to the skeleton code.
P
PP
System.out.println(“This is my first program in java");
PP
P
Save your changes by choosing File | Save.
P
PP
Compile the Source File into a .class File
To compile your source file, choose Run | Build Project (Hello World
App) from the IDE's main menu. (Short cut key F11)
P
PP
If output window does not shown than click on Windows -> Output as
shown below.
P
PP
If the build output concludes with the statement BUILD SUCCESSFUL,
congratulations! You have successfully compiled your program!
If the build output concludes with the statement BUILD FAILED, you
probably have a syntax error in your code.
P
double-click such a hyperlink to navigate to the source of an error.
PP
You can then fix the error and once again choose Run | Build Project.
PP
P
When you build the project, the bytecode file FirstApp.class is generated.
You can see where the new file is generated by opening the Files window
and expanding the FirstApp/build/classes/firstapp node as shown in the
following figure.
P
PP
Run the Program
From the IDE's menu bar, choose Run | Run Main Project. (Short cut key F6)
The next figure shows what you should now see.
P
PP
PP
P
Code Explanation
• Every line of code that runs in Java must be inside a class.
In our example, we named the class FirstAPP.
A class should always start with an uppercase first letter.
•Note: Java is case-sensitive:
"MyClass" and "myclass" has different meaning.
P
• The name of the java file must match the class name.
PP
In our example the file name is FirstApp.java and within this
the class is FirstApp
file
• Every program must contain the main() method. Any code inside the
main() method will be executed.
• Inside the main() method, we can use the println() method to display
message on the screen
What is System.out.println?
• System – is a final class
• out – is a static member field of System class and
is of type PrintStream.
• println – is a method of PrintStream class.
P
• System. out is the output stream connected to the console.
PP
What is class & object?
• Everything in Java is associated with classes and objects.
• Class
it describes an data fields (called variables) and defines the
operations (called methods).
P
• Object
PP
An object is created from a class.
Identifier
•An identifier may be any sequence of uppercase and
lowercase letters, numbers or the underscore and dollar-
P
sign characters.
PP
•Identifiers must not begin with a number.
P
int basic=10000, hra, da ;
E.g.
int myNum = 15;
PP
System.out.println(myNum);
E.g.
int myNum;
myNum = 15;
System.out.println(myNum);
Basic Input Output
java.util.Scanner class
P
PP
Basic Input Output
Accept student_no, name & marks and display it.
import java.util.Scanner;
public class Student {
public static void main (String args[])
{ int rollno;
String name;
double marks;
Scanner sc = new Scanner (System.in);
P
System.out.print("Enter Student Rollno \t");
rollno=sc.nextInt();
PP
System.out.print("Enter Student name \t");
name = sc.next();
System.out.print("Enter Student Marks \t");
marks =sc.nextDouble();
System.out.println("Student Rollno:\t"+rollno);
System.out.println("Student Name:\t"+name);
System.out.println("Student Rollno:\t"+marks);
sc.close();
}
}
Naming Convention
Identifier Rules for Naming Examples
Type
java.lang
All-lowercase letters
Packages java.io
Mixed case with the first letter of each Integer, System,
Classes
internal word capitalized. Math
P
Integer.valueOf( s),
Methods The first letter lowercase, with the first letter BufferedReader.read
PP
of each internal word capitalized.
Line()
int employeeId
The first letter lowercase, with the first letter double itemPrice
Variables
of each internal word capitalized.
int numberOfUsers
All uppercase with words separated by static int
Constants
underscores ("_"). MIN_WIDTH = 4;
Interfaces Interface names should be capitalized like
class names.
Operators
• Java operators are mainly categorized into the
following four groups:
P
– Arithmetic operators,
PP
– Bitwise Operators,
– Relational operators,
– Logical operators
Arithmetic Operators
P
PP
Order of Precedence
P
∗, /, or % evaluated second, left-to-right
PP
+, − evaluated last, left-to-right
Example: Sum of two integer
public class Sum {
// main method
public static void main( String args[] ){
P
int a, b, sum;
a = 20;
PPb = 10;
sum = a + b;
System.out.println(a + ” + ” + b + “ = “ + sum);
} // end main
P
Addition/assignment +=
PP
Subtraction/assignment
Multiplication/assignment
−=
∗=
Division/assignment /=
Remainder/assignment %=
• The syntax is It is either a literal | a
leftSide Op= rightSide ; variable identifier | an
expression.
Allways it is a
variable identifier. It is an arithmetic
operator.
P
leftSide = leftSide Op rightSide ;
If X = 10 then
• X+=5; ⇔ x = x + 5;
PP o/p x = 15
• X*=5; ⇔ x = x * 5; o/p x = 50
• x%=5; ⇔ x = x % 5; o/p x = 0
• X *= y+w*z; ⇔ x = x * (y+w*z);
Increment/Decrement Operators
Only use ++ or − − when a variable is being incremented/decremented
as a statement by itself.
P
++x; is equivalent to x = x+1;
--x; is equivalent to x = x-1;
PP
The position of the ++ or -- is important here. It is postfix or prefix.
x++ means to return the value of x first then increment (++) it after
++x means to increment (++) first then return the value of x
a++;
P
System.out.println( “Value of a is ::” +
a);
a);
PP ++a;
System.out.println( “Value of a is ::” +
a = 10;
b = a++;
System.out.println( “Value of a is ::” +
a);
System.out.println( “Value of b is ::” +
b);
a 10;
Relational Operators
• Relational operators compare two values
• They Produce a boolean value (true or false) depending on
the relationship
P
Operation Is true when
a ==b a is equal to b
P
&&
PP T F || T F
T T F T T T
F F F F T F
Operators Precedence
Parentheses (), inside-out
P
Additive +, -, from left to right
Relational
Equality
PP <, >, <=, >=, from left to right
Logical OR ||
• AND &
• OR |
P
• XOR ^
• NOT ~
PP
Logical Operators (Bit Level)
& | ^ ~
int a = 10; // 00001010 = 10
int b = 12; // 00001100 = 12
a 00000000000000000000000000001010 10
& b 00000000000000000000000000001100 12
P
AND a & b 00000000000000000000000000001000 8
|
OR
a
b
PP
00000000000000000000000000001010
00000000000000000000000000001100
a | b 00000000000000000000000000001110
10
12
14
a 00000000000000000000000000001010 10
^ b 00000000000000000000000000001100 12
XOR a ^ b 00000000000000000000000000000110 6
~ a
~a
00000000000000000000000000001010
11111111111111111111111111110101
10
-11
NOT
Shift Operators (Bit Level)
P
• Shift Right >>
<<
Left
a
a << 2
PP
00000000000000000000000000000011
00000000000000000000000000001100
3
12
a 00000000000000000000000000000011 3
>> a >> 2 00000000000000000000000000000000 0
Right
Control Statements
In Java, control statements can be divided into the
following three categories:
P
•Selection / Conditional Statements
•Iterative / Looping Statements
PP
•Jump / Breaking Statements
Types of Selection Statements
• Simple if
P
•if … elsePP
•Nested if
•Switch
Simple IF Statement
•Syntax:
if ( Condition )
{
P
Statements ;
} PP
E.g. if ( num > 0 ) {
pcount = pcount + 1;
}
if (expression )
{
P
statements;
}
{
else
statements;
PP
}
P
It makes the code much more easy, readable, and shorter.
Syntax : variable x = (expression) ? value if true : value if false
{
PP
public static void main( String args[] )
int a, b , ans;
a = 10; b = 20;
ans = ( a > b ) ? a : b ;
System.out.println( “Value of ans ::” + ans);
}
If …. else if Statements
Syntax:
If(condition-1)
{ Statements; }
else if (condition-2)
P
{ Statements; }
.
.
PP
else if (condition-n)
{ Statements; }
else
{ Statements; }
If …. else if Statements
import java.util.Scanner;
public static void main( String args[] )
{ int percentage;
Scanner sc = new Scanner (System.in);
System.out.print("Enter value of day :: \t");
P
percentage=sc.nextInt();
if percentage > 70
PP
System.out.println( “ Grade is Distinction”);
else if percentage > 60
System.out.println( “ Grade is First Class”);
else if percentage > 35
System.out.println( “ Grade is Second Class”);
else
System.out.println( “ Grade is Fail”);
}
Nested If Statements
If(condition)
{
if (condition)
{ Statements; }
else
P
{ Statements; }
}
else
{
PP
if (condition)
{ Statements; }
else
{ Statements; }
}
if ( a > b )
{ If ( a > c )
{
System.out.println(“ A is the biggest number”);
}
else
{
System.out.println(“ C is biggest number”);
P
}
}
else
{
PP
If ( b > c )
{
System.out.println(“ B is the biggest number”);
}
else
{
System.out.println(“ C is biggest number”);
}
Switch Statement
switch (expression) {
case value_1 :
statement(s);
break;
case value_2 :
P
statement(s);
break;
... PP
case value_n :
statement(s);
break;
default:
statement(s);
}
Switch Statement
import java.util.Scanner;
public static void main( String args[] )
{ int day;
Scanner sc = new Scanner (System.in);
System.out.print("Enter value of day :: \t");
day=sc.nextInt();
P
switch (day) {
PP
case 1 : System.out.println( “Sunday”); break;
case 2 : System.out.println( “Monday”); break;
case 3 : System.out.println( “Tuesday”); break;
case 4 : System.out.println( “Wednesday”); break;
case 5 : System.out.println( “Thursday”); break;
case 6 : System.out.println( “Friday”); break;
case 7 : System.out.println( “Saturday”); break;
}
Types of Looping Structure
Loops are used to execute a set of
instructions/functions repeatedly when
some conditions become true.
P
There are three types of loops in Java
PP
• while loop
• do … while loop
• for loop
Comparison of Looping Structures
Comparison for loop while loop do while loop
When to If the number of If the number of If the number of
use iteration is fixed, it is iteration is not fixed, it iteration is not fixed
recommended to use is recommended to and you must have to
for loop. use while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.
P
Syntax for(initialize; condition; while(condition) Do
increment/decrement) { {
{
// code
}
PP }
//code //code
}
while(condition);
Example for(int=1; int i=1; int i=1;
i<=10; while(i<=10){ do{
i++) { System.out.println(i); System.out.println(i);
System.out.println(i); i++; i++;
} } }
while(i<=10);
Syntax for for(;;) while(true) Do
infinitive { //code } { //code } { //code }
loop while(true);
EXAMPLES
To find sum of first N numbers.
for ( sum = 0, cnt = 1; cnt <= n ; cnt ++)
{
sum = sum + cnt;
}
P
To find the reverse No. To find the reverse No.
================== ==================
PP
int n = 123, ans = 0;
while ( n > 0 )
int n = 123, ans = 0;
do {
{ n = n % 10 ; n = n % 10 ;
ans = (ans * 10 ) + n ; ans = (ans * 10 ) + n ;
n = n / 10 ; } n = n / 10 ; }while ( n > 0 )
Break Statement
• When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
• It is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only
inner loop.
P
Syntax : break ;
public class Sample {
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
} System.out.println(i); } } }
Continue Statement
• The continue statement is used in loop control structure when
you need to jump to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
• It continues the current flow of the program and skips the
remaining code at the specified condition.
• In case of an inner loop, it continues the inner loop only.
• Syntax : continue;
P
• Example:
public class Sample {
for(int i=1;i<=10;i++){
if(i==5){
//continue the loop . it will skip the rest statement
continue;
}
System.out.println(i);
} } }
String Handling
Java Strings are Immutable
Once we create a string, we cannot change that string.
•// create a string
String example = "Hello! ";
P
example = example.concat(" World");
PP
•concat() method to add another string World to the previous string.
•How it works?
• JVM takes the first string "Hello! "
• Creates a new string by adding "World" to the first string
• Assign the new string "Hello! World" to the example variable
• The first string "Hello! " remains unchanged
String Handling
Escape character in Java Strings
•The escape character is used to escape some of the characters present
inside a string.
P
String example = "This is the "String" class";
PP
•Since strings are represented by double quotes, the compiler will treat
"This is the " as the string. Hence, the above code will cause an error.
•To solve this issue, we use the escape character \ in Java. For example,
•// use the escape character
String example = "This is the \"String\" class.";
•Now escape characters tell the compiler to escape double quotes and
read the whole text.
String Handling
String Operations:
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Programming";
// get the length of greet
int length = first.length();
P
System.out.println("Length: " + length);
// Combine two strings
PP
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
// compare first and second strings
first = "Java";
second = "Java";
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " +
result1); }
String Handling : Methods of String
int length(): It returns the length of a String.
P
char charAt(int index):
It returns the character at the specified index.
PP
Specified index value should be between 0 to length() -1 both inclusive.
It throws IndexOutOfBoundsException if index < 0 or >= length of String.
String concat(String str): Concatenates the specified string “str” at the end
of the string.
P
int indexOf(int ch): Returns the index of first occurrence of the specified
character ch in the string.
PP
int indexOf(String str): This method returns the index of first occurrence
of specified substring str.
String substring():
Extracts a substring from the string and returns it.
String trim(): Returns the substring after omitting leading and trailing white
spaces from the original string.
String Handling
Creating strings using the new keyword
•Since strings in Java are objects, we can create strings using the
new keyword as well.
E.g.
public static void main(String[] args) {
P
// create a string using new
PP
String name = new String("Java String");
•In Java, the JVM maintains a string pool to store all of its strings
inside the memory. The string pool helps in reusing the strings.
P
•While creating strings using string literals, the value of the string
PP
is directly provided. Hence, the compiler first checks the string
pool to see if the string already exists. If the string already exists,
the new string is not created. Instead, the new reference points to
the existing string. If the string doesn't exist, the new string is
created.
•However, while creating strings using the new keyword, the value
of the string is not directly provided. Hence the new string is
created all the time.
String Handling
String Comparison
•To compare string objects, Java provides methods and operators
both. So we can compare string in following three ways.
P
Using equals() method
PP
•equals() method compares two strings for equality. Its general
syntax : boolean equals (Object str)
•It compares the content of the strings. It will return true if string
matches, else returns false.
Using == operator
•The double equal (==) operator compares two object references
to check whether they refer to same instance. This also, will
return true on successful match else returns false.
String Handling
compareTo() method
•String compareTo() method compares values and returns an
integer value which tells if the string compared is less than, equal
to or greater than the other string.
•It compares the String based on natural ordering i.e
alphabetically. Its general syntax is.
•Syntax: int compareTo(String str)
P
PP
String Handling
compareTo() method
P
int a = s1.compareTo(s2); //return less than 0 for s1 < s2
System.out.println(a);
PP
a = s1.compareTo(s3);
System.out.println(a);
//return 0 for s1 == s3
P
System.out.println(b);
}
b= PP
(s1 == s3); //false
System.out.println(b);
String Handling
Substr method
String s1="Javatpoint";
String substr = s1.substring(0); // Starts with 0 and goes to end
System.out.println(substr);
P
String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
PP
System.out.println(substr2);
P
Advantages
PP
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.
Array
• Declare a one-dimensional array
• data type arrary-name [ ]; OR
• data type [ ]arrary-name; OR
• data type[ ] arrary-name;
• Declaration and instantiation array
P
• data type array-name = new data type [ size ];
E.g. int a[]=new int[5];
PP
• Declaration, instantiation and initialization of an array
• data type array-name [ ] = { list of values };
E.g. int a[] = {1,2,3,4,5};
• Length of an array
•array-name.length
Array
•Length of an array
• array-name.length
P
int a[]={1,2,3,4,5};
PP
//printing array
for(int i=0; i< a.length; i++)
System.out.println(a[i]);
}
Array
Loop through an Array with For … Each
It is used exclusively to loop through elements in arrays:
Syntax:
for (type variable : arrayname) {
...
P
}
E.g.
PP
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i); }
for each String element (called i - as in index) in cars, print
out the value of i.
It does not require a the length property of an Array.
Array
• Declare a two-dimensional array
• data type arrary-name [ ] [ ]; OR
• data type [ ] [ ] arrary-name; OR
• data type[ ] [ ] arrary-name; OR
• data type [ ] arrary-name [ ];
P
• Allocate space for a two-dimensional array
• data type array-name = new data type [ size ] [ size ] ;
PP
• E.g. int[ ][ ] arr=new int[3][3]; //3 rows and 3 columns
• Initialization of an array
• data type array-name [ ] [ ] = { list of values };
• E.g. int arr[ ][ ] = { {1,2,3}, {2,4,5} , {4,4,5} };
• Length of an array
•array-name.length // Indicate the no. of rows.
•array-name [ index ] .length // Indicate the no. of columns.
//Java Program to demonstrate the addition of two matrices in Java
class AddMatrices{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
P
int c[][]=new int[2][3];
PP
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}}}
//Java Program to multiply two matrices
public class MatrixMultiplication {
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
P
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++)
{
{
PP
for(int j=0;j<3;j++)
c[i][j]=0;
for(int k=0;k<3;k++)
{ c[i][j]+=a[i][k]*b[k][j];
} //end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
} //end of j loop
System.out.println(); //new line
} }}