UNIT I java
UNIT I java
History of Java
• The initial name was Oak but it was renamed to Java in 1995 as OAK was
a registered trademark of another Tech company.
• Java is an island of Indonesia where first coffee was produced (called java
coffee).
• In 1995, Time magazine called Java one of the Ten Best Products of 1995.
• There are many java versions that has been released. Current stable release of Java is
Java SE 16.
Application of Java
Java is widely used in every corner of world and of human life. Java is not only
used in softwares but is also widely used in designing hardware controlling
software components. There are more than 930 million JRE downloads each
year and 3 billion mobile phones run java.
4. Embedded Systems
5. Robotics and games etc.
Features of Java
Following are some of the useful and advanced features of java:
1. Simple
Java is a very simple programming language, it is easy to learn, read and write
in Java. The syntax of Java is clean and easy to understand. Here’s why java
is simple programming language compared to other popular programming
language:
2. Platform Independent
Each operating system has different JVM, however the output they produce
after execution of bytecode is same across all operating systems. That is why
we call java as platform independent language.
3. Secure
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
5. Robust
1. Garbage collection,
2. Exception Handling
3. Memory allocation.
6. Distributed
In simple words: The java programs can be distributed on more than one
systems that are connected to each other using internet connection.
7. Multithreading
8. Portable
As discussed above, java code that is written on one machine can run on
another machine. The platform independent byte code can be carried to any
platform for execution that makes java code portable.
9. Architectural Neutral
Compiler converts the java file into byte-code and this byte code is machine
independent, java virtual machine can easily translate this byte code into
machine specific code. This makes java architectural neutral programming
language.
10. Dynamic
11. Performance
1. JDK stands for Java Development Kit. To install Java on your system,
you need to first install JDK on your system.
2. JDK contains the tools that you need, in order to write and execute java
programs.
3. JDK consists of Private JRE, JVM, compiler, Java application launcher,
etc. It also provides the Standard Edition (SE) of java API.
So from the above diagram, we can conclude that,
1. The JDK comes with a complete Java Runtime Environment (JRE), that
is different from the regular JRE thats the reason it is usually called a
private runtime so we can say that it includes all the features that JRE has.
2. It has all the java development tools such as compiler, JVM, JRE,
debugger etc.
3. You need jdk in order to write and run java program.
4. JDK supports multiple platforms and can be installed on Windows, Mac
and other operating systems.
Features of JRE
1. JRE contains set of libraries and other tools that JVM needs at runtime.
2. You can easily run any java program on JRE but you need jdk to write
and compile java programs.
3. JRE contains libraries that are required for integrations such as Java
Database Connectivity (JDBC), Java Naming and Directory Interface
(JNDI), Remote Method Invocation (RMI) etc.
Java Virtual Machine (JVM) is a virtual machine that resides in the real
machine (your computer) and the machine language for JVM is byte code.
This makes it easier for compiler as it has to generate byte code for JVM rather
than different machine code for each type of machine. JVM executes the byte
code generated by compiler and produce output. JVM is the one that makes
java platform independent.
Features of JVM
1. JVM makes it possible to run java code on any machine, it is the JVM
that makes java truly platform independent.
2. It also allows to run java applications on cloud platforms.
3. JDK and JRE both of these contain JVM.
4. JVM is an interpreter as it executes the java code line by line.
5. JVM converts the bytecode into machine code. JVM is platform
independent as JVM doesn’t depend on the hardware and operating
system of the machine.
Differences between C, C++, and Java
OOPs Concepts in JAVA
Objects
• Each object is identified by a unique name. Each object must be a member of a particular
class.
Classes
• The objects can be made user defined data types with the help of a class.
• A class is a collection of objects that have identical properties, common
behavior and shared relationship.
• For example: Planets, sun, moon are member of class solar system.
Abstraction
Abstraction is the concept of hiding the internal details and describing things in
simple terms. Data Abstraction refers to the process of representing essential
features without including background details or explanations.For example, a
method that adds two integers. The internal processing of the method is hidden
from the outer world. There are many ways to achieve abstraction in object-
oriented programmings, such as encapsulation and inheritance.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will
stop the car, but he does not know how on pressing the accelerator, the speed
is actually increasing. He does not know about the inner mechanism of the car
or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.
A Java program is also a great example of abstraction. Here java takes care of
converting simple statements to machine language and hides the inner
implementation details from the outer world. In Java, abstraction is achieved
by interfaces and abstract classes.
Data Encapsulation:
The wrapping of data and functions into a single unit (class) is called
data encapsulation. Data encapsulation enables data hiding and information
hiding.
Inheritance
Polymorphism
Message Passing
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).
The compiler ignores these comments during the time of execution and is
solely meant for improving the readability of the Java program.
Let’s take a look at an example to understand how we can use the above-
mentioned comments in a Java program.
Package Statement
There is a provision in Java that allows you to declare your classes in a
collection called package. There can be only one package statement in a Java
program and it has to be at the beginning of the code before a
ny class or interface declaration. This statement is optional, for example,
take a look at the statement below.
This statement declares that all the classes and interfaces defined in this source
file are a part of the student package. And only one package can be declared in
the source file.
Import Statement
Many predefined classes are stored in packages in Java, an import statement is
used to refer to the classes stored in other packages. An import statement is
always written after the package statement but it has to be before any class
declaration. We can import a specific class or classes in an import statement.
Take a look at the example to understand how import statement works in Java.
Interface Section
This section is used to specify an interface in Java. It is an optional section
which is mainly used to implement multiple inheritance in Java. An interface is
a lot similar to a class in Java but it contains only constants
and method declarations.
A Java program may contain several class definitions, classes are an essential
part of any Java program. It defines the information about the user-defined
classes in a program. A class is a collection of variables and methods that
operate on the fields. Every program in Java will have at least one class with
the main method.
Let’s analyze the above program line by line to understand how it works.
public class Example
This creates a class called Example. You should make sure that the class name
starts with a capital letter, and the public word means it is accessible from any
other classes.
Comments
Braces
The curly brackets are used to group all the commands together. To make sure
that the commands belong to a class or a method.
When the main method is declared public, it means that it can be used
outside of this class as well.
The word static means that we want to access a method without making
its objects. As we call the main method without creating any objects. The
word static means that we want to access a method without making
object of the class within which the method is declared. We call the main
method without creating any objects.
The word void indicates that it does not return any value. The main is
declared as void because it does not return any value.
Main is the method, which is an essential part of any Java program.
String[] args
It is an array where each element is a string, which is named as args. If you run
the Java code through a console, you can pass the input parameter. The main()
takes it as an input.
System.out.println();
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the system class. The method println prints
the text on the screen with a new line. All Java statements end with a
semicolon.
There are three main stages in the life cycle of a java program. They are:
First, you will start with typing the program in a text-editor (ex: notepad,
notepad++, wordpad, textedit etc). After completing editing of the program, we
have to save the file. While saving the file you should remember that the file
must be saved with .java extension. For example, let’s think that I had written a
Java program which contains a single class Sample (more on classes in future
posts). It is a good convention to save the file with the name of the class. So, as
per my example, the file will be saved as Sample.java.
Second step is compilation. The name of the Java compiler is javac. The input
to the compiler is Java source code which is available in Sample.java. The
output of the compiler is machine independent or platform independent code
which is known as bytecode. The file which is generated after compilation
is .class file. As per my example, the bytecode file will be Sample.class.
Comments
Comments in Java are the statements that are not executed by the compiler and interpreter. It
can be used to provide information or explanation about the variable, method, class or any
statement. It can also be used to hide program code for a specific time.
Types of Comments
Basically, there are three types of comments in Java. They are as follows:
Single-line comments
Multi-line comments
Documentation comments
1. Single-line Comments
Example
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World");
3. Documentation Comments
This type of comments is used generally when you are writing code for a project/ software
package. It helps you to generate a documentation page for reference, which can be used for
getting information about methods present, its parameters, etc. The documentation
comment statement is used to create documentation of APIs. To generate documentation of
API, you need to use the Javadoc tool.
Example
Java Data Types
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types – such as String,interfaces, Arrays ,enum and Classes.
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional
methods.There are eight primitive data types in Java:
Example
System.out.println(myNum);
System.out.println(myNum);
The float and double data types can store fractional numbers. Note that you should end the value
with an "f" for floats and "d" for doubles: The precision of a floating point value indicates how
many digits the value can have after the decimal point. The precision of float is only six or seven
decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.
Variables
Variables are containers for storing data values.
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false
Syntax
Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.
Example1
System.out.println(name);
Example 2
int myNum = 5;
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and read-only):
myNum = 20; // will generate an error: cannot assign a value to a final variable
Keywords
In Java, literals are the values that appear directly in the program. It can be assigned directly
to a variable. Java has various types of literals. The following figure represents a literal.
Types of Literals in Java:
Integer Literals:
Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal. The integer literal can be specified in four ways :
Decimal (Base-10): Digits from 0-9 are allowed in this form. Example: int x=101;
Octal (Base-8): Digits from 0 – 7 are allowed. It should always have a prefix 0. Example: int
x=0146;
Hexa-Decimal (Base-16): Digits 0-9 are allowed and also characters from a-f are allowed in this
form. Furthermore, both uppercase and lowercase characters can be used, Java provides an
exception here. A literal in this type should have a prefix 0x and 0X Example: int x =
0X123Face;
Binary: A literal in this type should have a prefix 0b and 0B, from 1.7 one can also specify in
binary literals, i.e. 0 and 1. Example: int x = 0b1111;
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. For Floating-
point data types, we can specify literals in only decimal form and we can’t specify in Octal and
Hexadecimal forms.
Decimal (Base-10): In this form, the allowed digits are 0-9.
Example: double d = 123.456;
Boolean Literal
Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The values of true and false do not convert into any numerical representation. The true
literal in Java does not equal 1, nor does the false literal equal 0.
Character Literal
A literal character is represented inside a pair of single quotes. There are four types of character
literal:
1. Single-Quote: Java Literal can be specified to a char data type as a single character
within a single quote.
Example: char ch = „a‟;
2. Char as Integral: A char literal in Java can specify an integral literal which also
represents the Unicode value of a character.
Example: char ch = 062;
3. Unicode Representation: Char literals can specify in Unicode representation ‘\uxxxx’.
Here XXXX represents 4 hexadecimal numbers.
Example: char ch = „\u0061‟; // Here 0061 represent a.
4. Escape Sequence: Escape sequences can also specify as char literal.
Example: char ch = „\n‟;
String Literals:
String Literals in Java are specified like they are in most other languages – by enclosing a
sequence of characters between a pair of double quotes.
Example: String s = “Hello”;
The scope of variables in Java is a location (or region) of the program where
the variable is visible to a program and can be accessible. Scope of a variable
refers to in which areas or sections of a program can the variable be accessed
and lifetime of a variable refers to how long the variable stays alive in
memory.
In other words, the variable scope is the location from which we can access its
value. The scope of variables determines its accessibility for other parts of the
program. Java allows declaring variables within any block. A block defines a
scope that starts with an opening curly brace and ends with a closing curly
brace.
1. When we define an instance variable inside a class, its scope is within the
class. It is visible inside all the methods, constructors, and from the beginning
of its program block to the end of program block in the class. General scope of
an instance variable is throughout the class except in static methods. Lifetime
of an instance variable is until the object stays in memory.
Therefore, all the methods, constructors, and blocks inside the class can access
instance variables. Normally, it is recommended to make these variables
private in the class.
However, the visibility of instance variables for the sub-classes can be given
with the use of access modifiers.
2. In the user-defined method, we can access the instance variables directly by
calling the variable name inside the class.
ClassName.VariableName;
Example:-
class A {
String name = "Steve"; //instance variable
static double salary = 25000.5; //static variable
public static void main(String[] args)
{
int age = 35; //local variable
}
}
class CSEStudent
static int id = 5;
int stud_id;
String stud_name;
class StudentDemo
s1.stud_name = "John";
S2.stud_id = 5002;
S2.stud_name = "Kevin";
+s1.stud_id);
+s2.stud_id);
}
Control Statements
Selection Statements/Conditional/Decision Making statements
if Statement
The Java if statement tests the condition. It executes the if block if condition is
true. The condition is any expression that returns a boolean value.
Example
if-else Statements
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
Nested if
The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
Nested if statements mean an if statement inside an if statement. Yes, java
allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.
Syntax:
if(condition)
{
statement;
if(condition)
statement;
}
else
statement;
Example
Output:
s is an even number and greater than 10!
Hello World!
Switch statement
The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement. The switch statement works with byte,
short, int, long, enum types, String and some wrapper types like Byte, Short,
Int, and Long. Since Java 7, you can use strings in the switch statement. In
other words, the switch statement tests the equality of a variable against
multiple values.
o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-time error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
o Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is
not found, it executes the next case.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
........................
default:
code to be executed if all cases are not matched;
}
Example:
public class Example {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
................
Else
{
//code to be executed if all the conditions are false
}
Example
Output:
NEGATIVE
Loops in Java
While Loop
Syntax :
loop statements...
Flowchart:
Example:
for loop:
for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for (initialization ; testing condition; increment/decrement)
statement(s);
Flowchart:
do while Loop:
do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example of Exit
Control Loop.
Syntax:
do
statements..
}
while (condition);
Flowchart:
Example:
int i = 1;
// Do-while loop
do{
System.out.println("Hello World");
i++;
}while (i < 6);
}
}
for-each Loop
The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.It works
on the basis of elements and not the index. It returns element one by one in the defined
variable.
Syntax:
Example:
public class Example {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;)
{
//code to be executed
}
Example:
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
break statement
continue statement
labelled break and continue statements
return statement
break statement
The break statement in java is used to terminate a switch or looping statement. That means
the break statement is used to come out of a switch statement and a looping statement like
while, do-while, for, and for-each.
The floowing picture depictes the execution flow of the break statement.
Example:
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the
beginning of the loop. The continue statement can be used with looping statements like
while, do-while, for, and for-each.
When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement flow of execution is as shown in the following figure.
Example 1:
Example 2:
Output
13579
The labelled break statement terminates the block with specified label. The labbeled
continue statement takes the execution control to the beginning of a loop with specified
label.
import java.util.Scanner;
verify: if (value % 2 == 0)
{
System.out.println("\nYou won!!!");
break reading;
}
else
{
System.out.println("\nSorry try again!!!");
continue reading;
}
}
}}
In java, the return statement used with both methods with and without return type. In the
case of a method with the return type, the return statement is mandatory, and it is optional
for a method without return type.
When a return statement used with a return type, it carries a value of return type. But, when
it is used without a return type, it does not carry any value. Instead, simply transfers the
execution control.
Syntax:
The syntax of a return statement is the return keyword is followed by the value to be
returned.
return returnvalue;
Example 1:
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
Example 2:
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a
rich set of operators.
Arithmetic Operators
Relational (or) Comparision Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like
addition, subtraction, multiplication, division, modulus, increment, decrement, etc.,
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
++ Increment a++
-- Decrement a--
< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE
> Returns TRUE if the first value is larger than second value 10 > 5 is
otherwise returns FALSE TRUE
<= Returns TRUE if the first value is smaller than or equal to 10 <= 5 is
second value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to 10 >= 5 is
second value otherwise returns FALSE TRUE
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
Operator Meaning Example
& Logical AND - Returns TRUE if all conditions are TRUE false & true =>
otherwise returns FALSE false
| Logical OR - Returns FALSE if all conditions are FALSE false | true =>
otherwise returns TRUE true
^ Logical XOR - Returns FALSE if all conditions are same true ^ true =>
otherwise returns TRUE false
! Logical NOT - Returns TRUE if condition is FLASE and returns !false => true
FALSE if it is TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a false & true =>
decision is finalized it does not evaluate remianing. false
|| short-circuit OR - Similar to Logical OR (|), but once a decision false | true =>
is finalized it does not evaluate remianing. true
Short-circuit OR
To answer the question you only needed to evaluate the first subexpression:
12 > 6 || 18 > 1
------
true
+= Add both left and right-hand side values and store the result into left- A += 10
hand side variable
-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable
Operator Meaning Example
/= Divide left-hand side variable value with right-hand side variable value A /= B
and store the result into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value A %= B
and store the remainder into the left-hand side variable
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on binary
values. The following table describes all the bitwise operators in the java programming
language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A & B
⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it A ^ B
is 1 ⇒ 13 (01101)
Operator Meaning Example
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100)
>> the Bitwise right shift operator shifts all the bits to the right by A >> 2
the specified number of positions ⇒ 6 (00110)
Conditional Operators
The conditional operator is also called a ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first, we verify a
condition, then we perform one operation out of the two operations based on the condition
result. If the condition is TRUE the first option is performed, if the condition is FALSE the
second option is performed. The conditional operator is used with the following syntax.
Syntax
c = (a>b)? a : b;
1. If byte, short, and int are used in a mathematical expression, Java always
converts the result into an int.
2. If a single long is used in the expression, the whole expression is
converted to long.
3. If a float operand is used in an expression, the whole expression is
converted to float.
4. If any operand is double, the result is promoted to double.
5. Boolean values cannot be converted to another type.
Example
public class Example
int myInt = 9;
System.out.println(myInt); // Outputs 9
}
Explicit Type casting (Narrowing conversion)
The conversion of a higher data type into a lower data type is called
narrowing conversion.
(type_name)expression;
Example
public class Main {
System.out.println(myInt); // Outputs 9
}
Java Arrays
An array is a collection of similar types of data.
One-Dimensional Arrays
In Java, here is how we can declare an array.
dataType[ ] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc.
or Java objects
arrayName - it is an identifier
In Java, we can declare and allocate the memory of an array in one single
statement. For example,
Initialize Arrays
In Java, we can initialize arrays during declaration. For example,
Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java, using
the index number.
We can access the element of an array using the index number. Here is
the syntax for accessing elements of an array,
array[index]
Multidimensional Arrays
2-dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java
starts with 0 and not 1.
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
import java.util.Scanner;
public class ArrayInputExample1
{
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
//reading the number of elements from the that we want to enter
n=sc.nextInt();
//creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
//reading array elements from the user
array[i]=sc.nextInt();
}
System.out.println("Array elements are: ");
// accessing array elements using the for loop
for (int i=0; i<n; i++)
{
System.out.println(array[i]);
}
}
}