Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java Learning Recode - Biswajeet

Java is a programming language developed by Sun Microsystems in 1995. It is a platform-independent, secure, robust, and object-oriented language. Some key points: - Java code examples show a simple "Hello World" program. - Java is used widely in desktop applications, web applications, enterprise applications, mobile applications, and more. There are four main types of Java applications. - The Java platform includes Java SE, Java EE, Java ME, and JavaFX editions. - Variables in Java hold values and have data types like primitive types and non-primitive types. There are three types of variables: local, instance, and static.

Uploaded by

Nodal gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Learning Recode - Biswajeet

Java is a programming language developed by Sun Microsystems in 1995. It is a platform-independent, secure, robust, and object-oriented language. Some key points: - Java code examples show a simple "Hello World" program. - Java is used widely in desktop applications, web applications, enterprise applications, mobile applications, and more. There are four main types of Java applications. - The Java platform includes Java SE, Java EE, Java ME, and JavaFX editions. - Variables in Java hold values and have data types like primitive types and non-primitive types. There are three types of variables: local, instance, and static.

Uploaded by

Nodal gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Java Technology

 What is java ?
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language. Java was developed by Sun Microsystems (which
is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father
of Java. Before Java, its name was Oak. Since Oak was already a registered company, so
James Gosling and his team changed the name from Oak to Java.

SIMPLE JAVA CODE EXAMPLE ?


1. class Simple{  
2.     public static void main(String args[]){  
3.      System.out.println("Hello Java");  
4.     }  
5. } 

Application
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application

Standalone applications are also known as desktop applications or window-based


applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an


enterprise application. It has advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application.


Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang,


java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like
OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking,
AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise


applications. It is built on top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API.

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

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

There are two types of data types in Java: primitive and non-primitive.

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

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.
Example to understand the types of variables in java

1. public class A  
2. {  
3. static int m=100;//static variable  
4. void method()  
5. {    
6. int n=90;//local variable    
7. }  
8. public static void main(String args[])  
9. {  
10. int data=50;//instance variable    
11. }  
12. }//end of class   

Java Variable Example: Add Two Numbers

1. public class Simple{    
2. public static void main(String[] args){    

3. int a=10;    
4. int b=10;    

5. int c=a+b;    
6. System.out.println(c);    

7. }  
8. }    
Output = 20

Data Types in Java

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

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

Java Primitive Data Types

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

1. boolean data type


2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type

Boolean Data Type


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

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

1. Boolean one = false  

Byte Data Type


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

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

Example:

1. byte a = 10, byte b = -20  

Short Data Type


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

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

Example:

1. short s = 10000, short r = -5000  

Int Data Type


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

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

1. int a = 100000, int b = -200000  

Long Data Type


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

Example:

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

Float Data Type


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

Example:

1. float f1 = 234.5f  

Double Data Type


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

Example:

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

Example:

1. char letterA = 'A'  

Java Control Statements


Java compiler executes the code from top to bottom. The statements in the code 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. It is one of the fundamental features of Java, which provides a smooth
flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of
decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false. In Java, there are four types of if-
statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:
It 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.

1. if(condition) {    
2. statement 1; //executes when condition is true   
3. }    

Consider the following example in which we have used the if statement in the java code.

Student.java

1. public class Student {    
2. public static void main(String[] args) {    
3. int x = 10;    
4. int y = 12;    
5. if(x+y > 20) {    
6. System.out.println("x + y is greater than 20");    
7. }    
8. }      
9. }     

Output:
x + y is greater than 20

2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.

Syntax:

1. if(condition) {    
2. statement 1; //executes when condition is true   
3. }  
4. else{  
5. statement 2; //executes when condition is false   
6. }  

Consider the following example.

Student.java

1. public class Student {  
2. public static void main(String[] args) {  
3. int x = 10;  
4. int y = 12;  
5. if(x+y < 10) {  
6. System.out.println("x + y is less than      10");  
7. }   else {  
8. System.out.println("x + y is greater than 20");  
9. }  
10. }  
11. }  

Output:

x + y is greater than 20
3) if-else-if ladder:
The if-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 in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

1. if(condition 1) {    
2. statement 1; //executes when condition 1 is true   
3. }  
4. else if(condition 2) {  
5. statement 2; //executes when condition 2 is true   
6. }  
7. else {  
8. statement 2; //executes when all the conditions are false   
9. }  

Consider the following example.

Student.java

1. public class Student {  
2. public static void main(String[] args) {  
3. String city = "Delhi";  
4. if(city == "Meerut") {  
5. System.out.println("city is meerut");  
6. }else if (city == "Noida") {  
7. System.out.println("city is noida");  
8. }else if(city == "Agra") {  
9. System.out.println("city is agra");  
10. }else {  
11. System.out.println(city);  
12.}  
13.}  
14. }  

Output:

Delhi

4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.
Syntax of Nested if-statement is given below.
1. if(condition 1) {    
2. statement 1; //executes when condition 1 is true   
3. if(condition 2) {  
4. statement 2; //executes when condition 2 is true   
5. }  
6. else{  
7. statement 2; //executes when condition 2 is false   
8. }  
9. }  
Consider the following example.
Student.java
1. public class Student {    
2. public static void main(String[] args) {    
3. String address = "Delhi, India";    

4. if(address.endsWith("India")) {    
5. if(address.contains("Meerut")) {    
6. System.out.println("Your city is Meerut");    
7. }else if(address.contains("Noida")) {    
8. System.out.println("Your city is Noida");    
9. }else {    
10. System.out.println(address.split(",")[0]);    
11. }    
12.}else {    
13.System.out.println("You are not living in India");    
14. }    
15.}    
16.}    

Output:

Delhi

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else
-if statements. It also enhances the readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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 syntax to use the switch statement is given below.

1. switch (expression){  
2. case value1:  
3. statement1;  
4. break;  
5. .  
6. .  
7. .  
8. case valueN:  
9. statementN;  
10. break;  
11. default:  
12.default statement;  
13.}  

Consider the following example to understand the flow of the switch statement.

Student.java

1. public class Student implements Cloneable {  
2. public static void main(String[] args) {  
3. int num = 2;  
4. switch (num){  
5. case 0:  
6. System.out.println("number is 0");  
7. break;  
8. case 1:  
9. System.out.println("number is 1");  
10. break;  
11. default:  
12.System.out.println(num);  
13.}  
14. }  
15.}  

Output:

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.
We use the for loop only when we exactly know the number of times, we
want to execute the block of code.

1. for(initialization, condition, increment/decrement) {    
2. //block of statements    
3. }    

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.

Calculation.java
1. public class Calculattion {  
2. public static void main(String[] args) {  
3. // TODO Auto-generated method stub  
4. int sum = 0;  
5. for(int j = 1; j<=10; j++) {  
6. sum = sum + j;  
7. }  
8. System.out.println("The sum of first 10 natural numbers is " + sum);  
9. }  
10. }  
Output:
The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection.
In the for-each loop, we don't need to update the loop variable. The syntax to use the
for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){    
2. //statements    
3. }    

Consider the following example to understand the functioning of the for-each loop in
Java.

Calculation.java

1. public class Calculation {    
2. public static void main(String[] args) {    
3. // TODO Auto-generated method stub    
4. String[] names = {"Java","C","C++","Python","JavaScript"};    
5. System.out.println("Printing the content of the array names:\n");    
6. for(String name:names) {    
7. System.out.println(name);    
8. }    
9. }    
10. }    
Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at


the start of the loop. If the condition is true, then the loop body will be
executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

1. while(condition){    
2. //looping statements    
3. }    

The flow chart for the while loop is given in the following image.
Consider the following example.

Calculation .java
1. public class Calculation {    
2. public static void main(String[] args) {    
3. // TODO Auto-generated method stub    
4. int i = 0;    
5. System.out.println("Printing the list of first 10 even numbers \n");    
6. while(i<=10) {    
7. System.out.println(i);    
8. i = i + 2;    
9. }    
10. }    
11. }    

Output:
Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop
at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance.
The syntax of the do-while loop is given below.

1. do     
2. {    
3. //statements    
4. } while (condition);    

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.

Calculation.java

1. public class Calculation {    
2. public static void main(String[] args) {    
3. // TODO Auto-generated method stub    
4. int i = 0;    
5. System.out.println("Printing the list of first 10 even numbers \n");    
6. do {    
7. System.out.println(i);    
8. i = i + 2;    
9. }while(i<=10);    
10. }    
11. }    
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 a loop
or switch statement. However, it breaks only the inner loop in the case of the
nested loop.

The break statement cannot be used independently in the Java program, i.e.,
it can only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement
with the for loop.

BreakExample.java

1. public class BreakExample {  

2. public static void main(String[] args) {  
3. // TODO Auto-generated method stub  
4. for(int i = 0; i<= 10; i++) {  
5. System.out.println(i);  
6. if(i==6) {  
7. break;  
8. }  
9. }  
10. }  
11. }  

Output:
0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

1. public class Calculation {    

2. public static void main(String[] args) {    
3. // TODO Auto-generated method stub    
4. a:    
5. for(int i = 0; i<= 10; i++) {    
6. b:    
7. for(int j = 0; j<=15;j++) {    
8. c:    
9. for (int k = 0; k<=20; k++) {    
10. System.out.println(k);    
11. if(k==5) {    
12.break a;    
13.}    
14. }    
15.}    

16.}    
17. }    

18.}    
Output:
0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement
in Java.
1. public class ContinueExample {  

2. public static void main(String[] args) {  
3. // TODO Auto-generated method stub  

4. for(int i = 0; i<= 2; i++) {  

5. for (int j = i; j<=5; j++) {  

6. if(j == 4) {  
7. continue;  
8. }  
9. System.out.println(j);  
10. }  
11. }  
12. }  

13. }  

Output:

0
1
2
3
5
1
2
3
5
2
3
5

Java OOPs Concepts


Object-Oriented Programming

Advantage of OOPs over Procedure-oriented programming language

Difference between Object-oriented and Object-based programming language.

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that
provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where
everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example, object,
classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition

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

An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.

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

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

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

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

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

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

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't
know the internal processing.

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

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

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

Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when classes
are aware of each other. If a class has the details information of another class, there is strong
coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field. You can use interfaces for the weaker coupling because there is no concrete
implementation.

Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task into
separate parts. The java.io package is a highly cohesive package because it has I/O related classes and
interface. However, the java.util package is a weakly cohesive package because it has unrelated classes
and interfaces.

Association
Association represents the relationship between the objects. Here, one object can be associated with one
object or many objects. There can be four types of association between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can
have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one object
contains other objects as a part of its state. It represents the weak relationship between objects. It is
also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another
way to reuse objects.

Composition
The composition is also a way to achieve Association. The composition represents the relationship where
one object contains other objects as a part of its state. There is a strong relationship between the
containing object and the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be deleted
automatically.

Advantage of OOPs over Procedure-oriented programming


language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming
language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be
accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming


Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming 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
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o 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

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)  

dataType []arr; (or)  

dataType arr[];  

Instantiation of an Array in Java

arrayRefVar=new datatype[size];  

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.

1. //Java Program to illustrate how to declare, instantiate, initialize  
2. //and traverse the Java array.  
3. class Testarray{  
4. public static void main(String args[]){  
5. int a[]=new int[5];//declaration and instantiation  
6. a[0]=10;//initialization  
7. a[1]=20;  
8. a[2]=70;  
9. a[3]=40;  
10. a[4]=50;  
11. //traversing array  
12. for(int i=0;i<a.length;i++)//length is the property of array  
13. System.out.println(a[i]);  
14. }}  

Output:

10

20

70

40

50

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation   
2. //and initialization of Java array in a single line  
3. class Testarray1{  
4. public static void main(String args[]){  
5. int a[]={33,3,4,5};//declaration, instantiation and initialization  
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. }}  

Output:

33

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.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){  
2. //body of the loop  
3. }  

Let us see the example of print the elements of Java array using the for-each loop.

1. //Java Program to print the array elements using for-each loop  
2. class Testarray1{  
3. public static void main(String args[]){  
4. int arr[]={33,3,4,5};  
5. //printing array using for-each loop  
6. for(int i:arr)  
7. System.out.println(i);  
8. }}  

Output:

33

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array  
2. //to method.  
3. class Testarray2{  
4. //creating a method which receives an array as a parameter  
5. static void min(int arr[]){  
6. int min=arr[0];  
7. for(int i=1;i<arr.length;i++)  
8. if(min>arr[i])  
9. min=arr[i];  

10. System.out.println(min);  
11. }  

12.public static void main(String args[]){  
13.int a[]={33,3,4,5};//declaring and initializing an array  
14. min(a);//passing array to method  
15.}}  
Output:

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to declare the array while passing
an array to the method.

1. //Java Program to demonstrate the way of passing an anonymous array  
2. //to method.  
3. public class TestAnonymousArray{  
4. //creating a method which receives an array as a parameter  
5. static void printArray(int arr[]){  
6. for(int i=0;i<arr.length;i++)  
7. System.out.println(arr[i]);  
8. }  

9. public static void main(String args[]){  
10. printArray(new int[]{10,22,44,66});//passing anonymous array to method  
11. }}  

Output:

10

22

44

66

Returning Array from the Method


We can also return an array from the method in Java.
1. //Java Program to return an array from the method  
2. class TestReturnArray{  
3. //creating method which returns an array  
4. static int[] get(){  
5. return new int[]{10,30,50,90,60};  
6. }  

7. public static void main(String args[]){  
8. //calling method which returns an array  
9. int arr[]=get();  
10. //printing the values of an array  
11. for(int i=0;i<arr.length;i++)  
12. System.out.println(arr[i]);  
13. }}  

Output:

10

30

50

90

60

ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.

1. //Java Program to demonstrate the case of   
2. //ArrayIndexOutOfBoundsException in a Java Array.  
3. public class TestArrayException{  
4. public static void main(String args[]){  
5. int arr[]={50,60,70,80};  
6. for(int i=0;i<=arr.length;i++){  
7. System.out.println(arr[i]);  
8. }  
9. }}  

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)  
2. dataType [][]arrayRefVar; (or)  
3. dataType arrayRefVar[][]; (or)  
4. dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;  
2. arr[0][1]=2;  
3. arr[0][2]=3;  
4. arr[1][0]=4;  
5. arr[1][1]=5;  
6. arr[1][2]=6;  
7. arr[2][0]=7;  
8. arr[2][1]=8;  
9. arr[2][2]=9;  

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array  
2. class Testarray3{  
3. public static void main(String args[]){  
4. //declaring and initializing 2D array  
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
6. //printing 2D array  
7. for(int i=0;i<3;i++){  
8. for(int j=0;j<3;j++){  
9. System.out.print(arr[i][j]+" ");  
10. }  
11. System.out.println();  
12. }  
13. }}  
Output:

1 2 3

2 4 5

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

1. //Java Program to illustrate the jagged array  
2. class TestJaggedArray{  
3. public static void main(String[] args){  
4. //declaring a 2D array with odd columns  
5. int arr[][] = new int[3][];  
6. arr[0] = new int[3];  
7. arr[1] = new int[4];  
8. arr[2] = new int[2];  
9. //initializing a jagged array  
10. int count = 0;  
11. for (int i=0; i<arr.length; i++)  
12. for(int j=0; j<arr[i].length; j++)  
a. arr[i][j] = count++;  

13. //printing the data of a jagged array   
14. for (int i=0; i<arr.length; i++){  
15. for (int j=0; j<arr[i].length; j++){  
a. System.out.print(arr[i][j]+" ");  
16. }  
17. System.out.println();//new line  
18. }  
19. }  
20.}  
Output:

0 1 2

3 4 5 6

7 8

What is the class name of Java array?


In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by
getClass().getName() method on the object.

1. //Java Program to get the class name of array in Java  
2. class Testarray4{  
3. public static void main(String args[]){  
4. //declaration and initialization of array  
5. int arr[]={4,4,5};  
6. //getting the class name of Java array  
7. Class c=arr.getClass();  
8. String name=c.getName();  
9. //printing the class name of Java array   
10. System.out.println(name);  

11. }}  
Output:

Copying a Java Array


We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method


1. public static void arraycopy(  
2. Object src, int srcPos,Object dest, int destPos, int length  
3. )  

Example of Copying an Array in Java


1. //Java Program to copy a source array into a destination array in Java  
2. class TestArrayCopyDemo {  
3. public static void main(String[] args) {  
4. //declaring a source array  
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',  
a. 'i', 'n', 'a', 't', 'e', 'd' };  
6. //declaring a destination array  
7. char[] copyTo = new char[7];  
8. //copying array using System.arraycopy() method  
9. System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
10. //printing the destination array  
11. System.out.println(String.valueOf(copyTo));  
12. }  
13. }  

Output:

caffein

Cloning an Array in Java


Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we
create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it
will copy the actual value. But, if we create the clone of a multidimensional array, it creates the
shallow copy of the Java array which means it copies the references.

1. //Java Program to clone the array  
2. class Testarray1{  
3. public static void main(String args[]){  
4. int arr[]={33,3,4,5};  
5. System.out.println("Printing original array:");  
6. for(int i:arr)  
7. System.out.println(i);  

8. System.out.println("Printing clone of the array:");  
9. int carr[]=arr.clone();  
10. for(int i:carr)  
11. System.out.println(i);  

12. System.out.println("Are both equal?");  
13. System.out.println(arr==carr);  

14. }}  

Output:

Printing original array:


33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false

Addition of 2 Matrices in Java


Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java  
2. class Testarray5{  
3. public static void main(String args[]){  
4. //creating two matrices  
5. int a[][]={{1,3,4},{3,4,5}};  
6. int b[][]={{1,3,4},{3,4,5}};  

7. //creating another matrix to store the sum of two matrices  
8. int c[][]=new int[2][3];  

9. //adding and printing addition of 2 matrices  
10. for(int i=0;i<2;i++){  
11. for(int j=0;j<3;j++){  
12. c[i][j]=a[i][j]+b[i][j];  
13. System.out.print(c[i][j]+" ");  
14. }  
15. System.out.println();//new line  
16. }  

17. }}  

Output:

2 6 8
6 8 10

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the
columns of the second matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

1. //Java Program to multiply two matrices  
2. public class MatrixMultiplicationExample{  
3. public static void main(String args[]){  
4. //creating two matrices    
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};    

7. //creating another matrix to store the multiplication of two matrices    
8. int c[][]=new int[3][3];  //3 rows and 3 columns  

9. //multiplying and printing multiplication of 2 matrices    
10. for(int i=0;i<3;i++){    
11. for(int j=0;j<3;j++){    
12.c[i][j]=0;      
13.for(int k=0;k<3;k++)      
14. {      
15.c[i][j]+=a[i][k]*b[k][j];      
16.}//end of k loop  
17. System.out.print(c[i][j]+" ");  //printing matrix element  
18.}//end of j loop  
19.System.out.println();//new line    
20. }    
21.}}  
Output:

6 6 6
12 12 12
18 18 18
Thank you

You might also like