0% found this document useful (0 votes)
2 views

Unit 1 Introduction to JAVA

The document provides an overview of Java programming, detailing its history, features, and applications. It explains the evolution of Java from its inception by the Green Team to its current usage in various domains, including web and mobile applications. Additionally, it covers Java's characteristics such as platform independence, object-oriented design, and security features, along with a brief introduction to variables and data types in Java.

Uploaded by

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

Unit 1 Introduction to JAVA

The document provides an overview of Java programming, detailing its history, features, and applications. It explains the evolution of Java from its inception by the Green Team to its current usage in various domains, including web and mobile applications. Additionally, it covers Java's characteristics such as platform independence, object-oriented design, and security features, along with a brief introduction to variables and data types in Java.

Uploaded by

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

BCA 403 Java Programming

Unit - 1: Introduction to JAVA


History of Java
Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
 Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
 Initially it was designed for small, embedded systems in electronic appliances like set-top boxes
 Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project.

 Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
 Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his
office.
Why they chooses java name for java language?
 The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of
the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
 According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Notice that Java is just a name not an acronym.
 Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
 In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 JDK 1.0 released in (January 23, 1996).
What is Java?
 Java is a programming language and a platform.
 Platform -Any hardware or software environment in which a program runs, known as a platform.
Since Java has its own Runtime Environment (JRE) and API, it is called platform.
Where it is used?
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 type of applications that can be created using java:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to
install on every machine such as 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 dynamic page, is called web application.
Currently, servlet, jsp, struts, 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. It has the advantage of
high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating
mobile applications.
Features of Java
1. Features of Java
1. Simple
2. Object-Oriented
3. Platform Independent
4. secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10. Multi-threaded
Features of java:
1. Platform Independent:
Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or macOS
which means if we compile a program on Windows, then we can run it on Linux and vice versa.
Each operating system has a different JVM, but the output produced by all the OS is the same
after the execution of bytecode. That is why we call java a platform-independent language.
2. Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Java is
purely an object oriented language due to the absence of global scope, Everything in java is an object,
all the program codes and data resides within classes and objects. It comes with an extensive set of
classes, arranged in packages, object model in java in sample and easy to extend.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
3. Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used
to load Java classes into the Java Virtual Machine dynamically. It adds security by separating
the package for the classes of the local file system from those that are imported from network
sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing
to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a
lot of effort into checking errors as early as possible that is why the java compiler is able to detect
even those errors that are not easy to detect by another programming language. The main features
of java that make it robust are garbage collection, Exception Handling, and memory allocation.

5. Portable
The WORA (Write Once Run Anywhere) concept and platform independent feature make Java
portable. Now using the Java programming language, developers can yield the same result on any
machine, by writing code only once. The reason behind this is JVM and bytecode.
Suppose you wrote any code in Java, then that code is first converted to equivalent bytecode
which is only readable by JVM. We have different versions of JVM for different platforms.
Windows machines have their own version of JVM, linux has its own and macOS has its own
version of JVM. So if you distribute your bytecode to any machine, the JVM of that machine would
translate the bytecode into respective machine code.

6. Distributed:
In Java, we can split a program into many parts and store these parts on different computers.
A Java programmer sitting on a machine can access another program running on the other machine.
This feature in Java gives the advantage of distributed programming, which is very helpful when
we develop large projects. Java helps us to achieve this by providing the concept of RMI (Remote
Method Invocation) and EJB (Enterprise JavaBeans).
Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as
HTTP and FTP, which makes creating network connections much easier than in C/C++.

7. Multithreaded:
A thread is an independent path of execution within a program, executing concurrently. Multithreaded
means handling multiple tasks simultaneously or executing multiple portions (functions) of the same
program in parallel.
The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web applications, etc.
8. Simple:
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

9. Architecture-neutral:
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

10. High Performance:


The performance of Java is impressive for an interpreted language because of its intermediate
bytecode.
Java provides high performance with the use of “JIT – Just In Time compiler”, in which the
compiler compiles the code on-demand basis, that is, it compiles only that method which is being
called. This saves time and makes it more efficient.
Java architecture is also designed in such a way that it reduces overheads during runtime. The
inclusion of multithreading enhances the overall execution speed of Java programs.

11. Dynamic and Extensible


Java is dynamic and extensible means with the help of OOPs, we can add classes and add new
methods to classes, creating new classes through subclasses. This makes it easier for us to expand our
own classes and even modify them.
12. Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.
Multithreading saves time as you can perform multiple operations together.
The threads are independent, so it does not block the user to perform multiple operations at the
same time and also, if an exception occurs in a single thread, it does not affect other threads.

JVM
 Actually, JVM is an interpreter for Byte code.
 The details of the JVM will differ from platform to platform, but all interpret the same Java
Byte code according to machine/platform.
 The Byte code which are generated by the compiler will be tested by the JVM on the
execution of the program or we can say every Java Program is under the control of the JVM
which checks the code on the runtime many times for viruses and any malicious.
 The Byte code generated by the compiler are also supported on any machine which has the
JVM which makes Java a platform independent language.

The JVM performs following operation:


 Loads code
 Verifies code

 Executes code
 Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment.
It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
Variable and Data type in Java
There are three types of variables: local, instance and static.
There are two types of data types in java, primitive and non-primitive.
Variable
Variables in Java are fundamental elements that act as containers to store data values. They serve as
named storage locations in your program, where each variable is associated with a specific data
type and a value. The variable's name is a unique identifier used to refer to and manipulate its stored
value within the code.
int data=50; //Here data is variable
Types of Variable
There are three types of variables in java
• Local variable
• Instance variable
• Static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable. It is not
declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Example to understand the types of variables
class A{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
}//end of class
Data Types in Java
In java, there are two types of data types
 primitive data types
 non-primitive data types

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
Byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four
times smaller than an int.
 Example: byte a = 100 , byte b = -50
short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times smaller than
an int.
 Default value is 0.
 Example: short s = 10000, short r = -20000
int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is a concern about
memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000
long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, int b = -200000L
float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f
double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values, generally the default
choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example: double d1 = 123.4
boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true
char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letter A ='A'
Rules of variables:
 The name of a variable can start with a letter, an underscore "_", or the dollar sign $. The name
cannot start with a digit. If the name starts with an underscore, the second character must be an
alphabetical letter
 After the first character, the name of the variable can include letters, digits (0, 1, 2, 3, 4, 5, 6, 7, 8,
or 9), or underscores in any combination
 The name of a variable cannot be one of the words that the Java languages has reserved for its
own use. A reserved word is also called a keyword. This means that you cannot use one of the
following keywords to name your variable:

abstract assert boolean break byte

case catch char class const


continue default do double else

enum extends final finally float

for goto if implements import

instanceof int interface long native

new package private protected public

return short static strictfp super

switch synchronized this throw throws

transient try void volatile while

Non-Primitive Data Types


 Non-primitive data types are called reference types because they refer to objects.
 The main difference between primitive and non-primitive data types are:
 Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase
letter.
 Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will learn more
about these in a later chapter.
Operators:
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Conditional Operator ( ? : )
7. Unary Operator
1. The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand A - B will give -10
operand
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand and B % A will give 0
returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
2. The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then (A == B) is not true.
condition becomes true.
!= Checks if the values of two operands are equal or not, if values (A != B) is true.
are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not true.
value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

3. The Bitwise Operators:


Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in
binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists (A & B) will give 12 which is
in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is
operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) will give -61 which is
effect of 'flipping' bits. 1100 0011 in 2's complement
form due to a signed binary
number.
<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which is
moved left by the number of bits specified by the right 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is
moved right by the number of bits specified by the right 1111
operand.
>>> Shift right zero fill operator. The left operands value is A >>>2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand and shifted values are filled up with zeros.
4. The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, (A && B) is false.
then the condition becomes true.
|| Called Logical OR Operator. If any of the two operands are non- (A || B) is true.
zero, then the condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is true.
its operand. If a condition is true then Logical NOT operator will
make false.

5. The Assignment Operators:


There are following assignment operators supported by Java language:
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C
left operand and assign the result to left operand =C+A
-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C
from the left operand and assign the result to left operand =C-A
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C
operand with the left operand and assign the result to left =C*A
operand
/= Divide AND assignment operator, It divides left operand with C /= A is equivalent to C
the right operand and assign the result to left operand =C/A
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to
two operands and assign the result to left operand C=C%A
<<= Left shift AND assignment operator C <<= 2 is same as C = C
<< 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C
>> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C
&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C
^2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C |
2

6. Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should
be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:


This would produce the following result:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println (“Value of b is : " + b );
b = (a == 10) ? 20 : 30;
System.out.println ("Value of b is : " + b );
}
}

Value of b is : 30
Value of b is : 20
7. Unary Operator
Increment operator is used to increment a value by 1. There are two varieties of increment
operator:
 Post-Increment: Value is first used for computing the result and then incremented.
 Pre-Increment: Value is incremented first and then the result is computed.
Decrement operator is used for decrementing the value by 1. There are two varieties of
decrement operators.
 Post-decrement: Value is first used for computing the result and then decremented.
 Pre-decrement: Value is decremented first and then the result is computed.
First, let’s look at a code snippet using the pre-increment unary operator:
int operand = 1;
++operand; // operand = 2
int number = ++operand; // operand = 3, number = 3
Next, let’s have a look at the code snippet using the pre-decrement one:
int operand = 2;
--operand; // operand = 1
int number = --operand; // operand = 0, number = 0
Let’s look at a sample code snippet using the post-increment operator:
int operand = 1;
operand++; // operand = 2
int number = operand++; // operand = 3, number = 2
Also, let’s have a look at the post-decrement one:
int operand = 2;
operand--; //operand = 1
int number = operand--; // operand = 0, number 1

Control Structures and Loops


Control structures are programming blocks that can change the path we take through those
instructions.
There are three kinds of control structures:

 Conditional Branches, which we use for choosing between two or more paths. There are three
types in Java: if/else/else if, ternary operator and switch.
 Loops that are used to iterate through multiple values/objects and repeatedly run specific
code blocks. The basic loop types in Java are for, while and do while.
 Branching Statements, which are used to alter the flow of control in loops. There are two
types in Java: break and continue.

Creating hello java example


import java.io.*; // Importing classes from packages
public class Hello { // Main class
public static void main(String[] args) // Main driver method
{
System.out.println ("Welcome to Java Hello"); // Print statement
}
}
Save this file as Simple.java
To compile: javac Hello.java
To execute: java Hello

/* Comments */ The compiler ignores comment block. Comment can be used anywhere in
the program to add info about the program or code block, which will be
helpful for developers to understand the existing code in the future easily.
import java.io.* This means all the classes of io package can be imported. Java io package
provides a set of input and output streams for reading and writing data to
files or other input or output sources.
public class  This creates a class called Hello.
Hello  All class names must start with a capital letter.
 The public word means that it is accessible from any other classes.
Braces Two curly brackets {...} are used to group all the commands, so it is known
that the commands belong to that class or method.
public static  When the main method is declared public, it means that it can also
void main be used by code outside of its class, due to which the main method
is declared public.
 The word static used when we want to access a method without
creating its object, as we call the main method, before creating any
class objects.
 The word void indicates that a method does not return a
value. main() is declared as void because it does not return a value.
 main is a method; this is a starting point of a Java program.
String[] args It is an array where each element of it is a string, which has been named as
"args". If your Java program is run through the console, you can pass the
input parameter, and main() method takes it as input.
System.out.prin This statement is used to print text on the screen as output, where the
tln(); system is a predefined class, and out is an object of the PrintWriter class
defined in the system. The method println prints the text on the screen
with a new line. You can also use print() method instead of println()
method. All Java statement ends with a semicolon.

Program 2:

public class SumOfNumbers1


{
public static void main(String args[])
{
int n1 = 225, n2 = 115, sum;
sum = n1 + n2;
System.out.println("The sum of numbers is: "+sum);
}
}

Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.
So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample hello
Output: Your first argument is: hello

Ways to read input from console in Java


1. Using Buffered Reader Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));

// Reading data using readLine


String name = reader.readLine ();

// Printing the read line


System.out.println (name);
}
}
Input:
Hello Java
Output:
Hello Java
2. Using Scanner Class
The main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however, it is also can be used to read input from the user in the command line.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}

Input:
Hello Java
12
3.4
Output:

You entered string Hello Java


You entered integer 12
You entered float 3.4

Java Arrays
An array is a collection of similar types of data.

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 dimensional or
multidimensional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

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
// declare an array
double[] data; // allocate memory
data = new double[10];
OR
double[] data = new double[10];
Here, the array can store 10 elements. We can also say that the size or length of
the array is 10.

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};

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

You might also like