0% found this document useful (0 votes)
50 views33 pages

R.P. Bhalodia BCA College: History of Java

Easy to use IDE for Java development. NetBeans is a popular integrated development environment for Java programming. It provides features like: - Code completion, debugging and refactoring tools to help write Java code quickly. - Project management functionality to organize Java files and dependencies. - Support for other languages like PHP, C/C++ and HTML5 beyond just Java. - Cross-platform support to develop Java applications on Windows, Linux and Mac operating systems. - Open source and free to download making it accessible for any Java developer.

Uploaded by

sr creation
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
50 views33 pages

R.P. Bhalodia BCA College: History of Java

Easy to use IDE for Java development. NetBeans is a popular integrated development environment for Java programming. It provides features like: - Code completion, debugging and refactoring tools to help write Java code quickly. - Project management functionality to organize Java files and dependencies. - Support for other languages like PHP, C/C++ and HTML5 beyond just Java. - Cross-platform support to develop Java applications on Windows, Linux and Mac operating systems. - Open source and free to download making it accessible for any Java developer.

Uploaded by

sr creation
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

R.P.

Bhalodia BCA College

CH 1
Histroy Introduction & Language
 History of Java
• Java is General purpose object oriented Programming Language.
Developed by Sun Microsystems of U.S.A

• Mr. James Gosling one Of the Developer of the Language “OAK‟.

• initially java was Develop for Making the software for consumer
Electronic Devices like TV, microwave(sensor technology)

• The Developer team has reviewed the existing Language like c and
c++ and combine the advantage of both language and remove
the limitation and then develop the simple ,reliable ,portable
and power tool language that is called Java as we can show in
below figure

1
 Explain java features
1. Compiler and interpreter
• Usually any programming language will be either compiler or
interpreter but java has combine both the approaches
• so become two stage system in it first stage java compiler
translate source code to machine independent byte code in the
second stage java interpreter will run this byte code in the
destination machine.
• Compiler: - C, C++, VB, FOXPRO….
• Interpreter: - Scripting language, HTML, PHP

2.Platform independent
• This is the most important and power full future of JAVA
program can run anyway any time changes on upgrade in
operation system or any other system recourses will not affect the
JAVA program to run.
• This is the reason why JAVA become most popular language on
the internet because on internet each and every pc will have
different configuration.

3. Object oriented
• Java is pure object oriented programming and that‟s while
everything in java is an object

4.Secure and robust


• When we have a language for internet base programming security
is the first and for most issues security in the sense of protection
from wireless or security of data
• Java does not support * pointer so direct access of memory will
not allow and that why ever program and data will become secure
and robust

2
5. Distributed
• JAVA programming language has the ability to run program on
distributed network so that it allow us that multiple location can
develop a single project

6.Simple, small & familiar


• JAVA is simple language because all the feature like if condition
,for loop ,while loop , switch case, and so on of the most popular
language like C,C++
• JAVA is small language because it consists of only six packages.
The package is same feature combination of C and C++ which we
can familiar this language.

7. Dynamic
• JAVA is dynamic language because one can add new feature all
new feature all new classes.
• To the java itself we can also call it as extension language which
can be extend whenever needed.

8.Multithreading
• Multithreading meaning handling of multiple task at a time.
• Java supports multithreaded programming this means that we
does not have to wait for a process to complete instead of that we
can start new process while the current process running.

9.High performance
• When you develop at require very much less memory as well as
high speed that‟s while its give us high performance.

3
 Milestone of Java [JAVA Edition]
• 1990
• Sun Micro System has desired to develop a software for
consumer electronic device
• 1991
• The team has given a name to the new language “OAK”
• 1992
• The team has been given a name called “green project team”
• 1993
• The internet and www has given authority to develop the
language for then also
• 1994
• The team has develop a new web browser called “HOT JAVA”
• 1995
• “OAK” was rename to java due to some legal problem in the same
year Microsoft announce support to JAVA
• 1996 : sun has release “JAVA Development kit (jdk 1.0)
• 1997 : sun has release JDK1.1
• 1998 : sun has release JDK1.2
• 1999 : sun has release J2EE
• 2000 : sun has release JDK1.3
• 2002 : sun has release JDK1.4
• 2004 : sun has release JDK5.0
• 2007 : sun has release JDK6.0
• 2012 : Latest version is JDK10.0 (64 bits)

4
 What is JDK?
The Java Development Kit (JDK) is an implementation of either one of the Java
SE, Java EE or Java ME platforms released by Oracle Corporation in the form of a
binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows.
JDK Tool Meaning Use

Javac Java Compiler Compiles the source code (.java file) &
translates it into Bytecode.

Java Java Interpreter Interprets Bytecode & generates output.


Javadoc Java Used to create documentation for java source

Documentation code in HTML format.

Javah Java Header It produces header files for the program

files which uses native methods. This file is


included in your program which calls this
native method

Javap Java It converts Bytecode file (.class file) to

disassemble program description

Jdb Java debugger Used to debug your program

applerviewer Applet Viewer Used to execute java Applets.

5
 Bytecode & JVM Machine
• With most programming languages, you either compile or
interpret a program so that you can run it on your computer.

• The Java programming language is unusual in that a program is


both compiled and interpreted.

• With the compiler, first you translate a program into an


intermediate language called Java

• The platform-independent codes interpreted by the interpreter on


the Java platform.

• The interpreter parses and runs each Java instruction on the


computer.

• Compilation happens just once; interpretation occurs each time


the program is executed.
• The following figure illustrates how this works.

6
• You can think of Java bytecodes as the machine code instructions
for the Java Virtual Machine (JVM).
• Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the JVM.

• Java byte codes help make "write once, run anywhere" possible.

• You can compile your program into bytecodes on any platform


that has a Java compiler.

• The byte codes can then be run on any implementation of the


JVM.

• That means that as long as a computer has a JVM, the same


program written in the Java programming language can run on
Windows 2000, a Solaris workstation, or on an iMac.

7
 Java Runtime Environment (JRE)
 The Java Runtime Environment (JRE), also known as Java
Runtime,

 The Java Development Kit (JDK), a set of programming tools for


developing Java applications.

 The Java Runtime Environment provides the minimum


requirements for executing a Java application;

 it consists of the Java Virtual Machine (JVM), core classes, and


supporting files.

 Compiling & Executing basic java program


Step1:
Open the Windows Command prompt and type this command .Here we
are opening notepad with the filename Class1.java (Please remember
the .java extension)

Steps for compiling and running your first java program using the
Java Development kit from Sun Microsystems

Step2:
Notepad would ask if you want to create the file. Click on Yes. This
would create the file and you can type the code in it

Step3:
Type the following code. All this code does is print Hello World! on the
screen. Remember Java is case sensitive

class a1
{
public static void main(String[] args){
System.out.println("Hello RPBC");
}
}

8
Step4:
Compilation Now Save the file and get back to the command prompt
and type the following command as shown.

javac a1.java

This command would compile a1.java and produce a1.class which


contains Java byte code which is machine independent.

Step5:
Running the program If you have any errors, you would see them on
the screen.

java a1
Please go back to notepad and correct the errors and resave the file.
If you see a blank output after the javac command,
it means there were no errors and you are ready to run the program.
You could run the program using the command as shown in the
screen shot.

Hello RPBC

JAVA IDE
 NetBeans

 NetBeans is an integrated development environment (IDE) for


developing primarily with Java, but also with other languages, in
particular PHP, C/C++, and HTML5.
 It is also an application platform framework for Java desktop
applications and others.
 The NetBeans IDE is written in Java and can run on Windows, OS
X, Linux, Solaris and other platforms supporting a compatible JVM.
 NetBeans IDE 7.4 was released in October 15 2013.
9
 NetBeans IDE is a free, open-source, cross-platform IDE with built-
in-support for Java Programming Language.
Feauter of netbeans.

 Fast & Smart Coding


 Easy & Efficient Project Management.
 Rapid User Interface Development.
 Bug Free Code.
 User interface management (e.g. menus and toolbars)
 User settings management.
 Storage management (saving and loading any kind of data)
 Window management.
 Wizard framework (supports step-by-step dialogs)
 NetBeans Visual Library.
 Integrated development tools.

 Eclipse IDE

The Eclipse is another very powerful editor for so many languages


such as Java, PHP, C, C++ etc.

The Eclipse IDE for Java Developers contains everything that you will
need to build java application.

It provides greater java editing with validation, incremental


compilation, cross-referencing, code assistance, an XML Editor & so
many others following are some debugging support with hyperlink
stepping.

1. Great debugging support with hyperlink stepping.


2. A new Quick Access feature to enhance IDE navigation.
3. Quick Fix/Assist support.
4. Task-focused development.

Eclipse 3.0 (released on 21 June 2004) selected the OSGi Service


Platform specifications as the runtime architecture.

The Association for Computing Machinery recognized Eclipse with the


2011 ACM Software Systems Award on 26 April 2012.
10
Data Type in Java
Data Type Range Size
(Byte)
Byte -128 to 127 1
Short -32768 to 32767 2
Int -2147483648 to 4
2147483647
Long -9223372036854775808 to 8
9223372036854775807
Float 3.4*10-38 to 3.438 4
Double 1.7*10-308 to 1.7*10+308 8
Char Single character 2
Boolean Either true or false 1

 Explain the Structure of java OR

Question : Explain the following line in JAVA

public static void main(String args[])

Answer :
First of follow we can see bellow example

Example:-
class xyz
{
public static void main (String args [])
{
System.out.println (“hello”);
}

11
}

In above example we can see xyz is a class name and the description of
public static void main (String args []) as we can see bellow.

public:-
The public keyword is access specified which means that the
contain of the following block accessible from all other classes.

static:-
The keyword static allow main to be called without having
instance of class (duplication copy of object).

void:-
The keyword void tell to the compiler that main () does not return
value.

main ()

main () is method called when Java application begin Java is


case sensitive main is different from MAIN Java compiler will compile
classes that doesn‟t contain a main method but Java has no may to
run is classes.

String args []
Declare a parameter name which is an array of instance
of the class string args receive and command line argument precision
when the program is executed.

System.out.println()
System is predefining classes that provide access to the system.
Out is the output stream that is connecting to the console.
Output is a complies by the build in println method.

 Explain Basic Structure of Java program.


Basic structure of a Java program is as under.
1. Documentation section
2. Package statement
3. Import statement
4. Class definition
5. Main method

1. Documentation section

12
In this section you can write the documentation for your program
like, program definition, author information, the logic of your
program etc. this is optional section.
It is written in comment lines (//) or (/* …………..*/)

2. Package statement
If you want to save your program in a package(directory) then the
package statement is included. This is also an optional section.

3. Import statement
If you want to import any library or user-defined package, the
import statement is used. Now from this imported package, you
can use its classes & methods. This is also an optional section.

Ex : import java.util.Date;

4. Class Definition
You can define classes in this section. Use class keyword to
declare a class. There can be member variable & methods in this
class. This is required & its compulsory section.

5. Main method
In your program, you can more than one class, but there should
be one class that contains the main method.
This class is run to generate output because the main method is
the entry point for program execution. This is compulsory
section.

13
Java Tokens
 Comments
There are three types of comment in java.
1. Single line comments : Double slashes are used to indicate single line
comment.
Ex. //This is a single line comment.
2. Multi-line comments :
The text written between /* and */ are considered comments.
Ex : /*
This is documentation comment
Rpbc
*/

 Identifiers
An identifier is a name given to a variable, a method or a class. To
declare an identifier we must follow some rules :

1. Identifier may consist of letters (uppercase or lowercase), digits,


underscore or dollar sign.
2. It must not start with a number.
3. No white space is allowed.
4. No keyword can be used as identifier.
Some valid examples of identifiers :
Var1, sub1, marks1, first_value, $price
Some invalid examples of identifiers :
In valid, 1marks, first-value

 Literals
In java, any constant value is known as literal. The literal can be any
one of the following.

Integer literal :
Ex : int x=300;
Here x is variable & 300 is value which is integer literal.

Floating-point literal :
Ex. double d=39.86;
Here 39.86 is floating-point literal.

Character literal :
Ex char c=‟A‟;
Here „A‟ is a character literal.

14
Some other are shown in below.
Escape Meaning
sequence
\n To give new line
\b Backspace
\t To give space as much as a tab
\‟ To print single quote
\” To print double quotes
\\ To print back slash

String literal :
Ex : String str=”java”;
Here “java” is a String literal
To print “I like “java”
System.out.println(“ I like \” java \” “);

Boolean literal :
Boolean literal can be true or false.
Ex. boolean flag=true;
Here true is boolean literal.

White-spaces
The white space can be a space, a tab or new line. The extra white
spaces are ignored by java compiler. Therefore if you write program in
a single line it makes no difference.

Separators
The separator are used to separate the statements from each other.
For ex. , the semicon (;) is used to terminate a statement. The list of
various separator is shown below :

Separator Name Use


; Semicolon Used to terminate a statement
. Dot or period Used to access variable or method of a
class through object. Also used to
separate package from sub package.
: Colon Used to specify a label.
() Parenthesis Used in method declaration & method
call. Also used in if conditions & loops.
{} Braces Used to enclose statements of methods,
class or any block of code. Also used to
initialize an array
[] Brackets Used to declare array & access array
elements

15
Keywords :
There are 49 keywords in java are reserved & each one has its unique
meaning. They can not be used as identifier.
They are listed below:

Abstract Continue goto* package synchronized

assert*** Default If private this


Boolean Do implements protected throw
Break Double Import public throws
Byte Else instanceof return transient
Case Extends int short try
Catch Final interface static void
Char Finally Long strictfp** volatile
Class Float Native super while
const* For New switch

Some are default initial value for data types


Data Type Default Initial value
Byte 0
Short 0
Int 0
Long 0L
Float 0.0f
Double 0.0d
Char „\0‟
Boolean False

16
Operator in Java
Operators
In java language there are same operators which we was used in the C and C++.
There are
Arithmetic Operators
Arithmetic operators are used in mathematical expression in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Operator Result
+ Addition
- Subtraction(also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition Assignment
-= Subtraction Assignment
/= Division Assignment
%= Modulus Assignment
*/ Multiplication Assignment
-- Decrement

The Modulus Operators


The modulus operation, % returns the remainder of a division operation. It can
be applied to floating-point types as well as integer types. The following
example program demonstrates the %:

In Arithmetic Assignment Operators


Java provides special operators that can be used to combine an arithmetic
operation with an assignment. As you probably know, statements like the
following are quite common in programming.
a = a + 4;

In java, you can rewrite this statement as shown here;


a+=4;

This version uses the += compound assignment operator. Both statements


perform the same operation: they increase the value of a by 4. Another example:
a = a / 4; a /= 4;
a = a % 4; a %= 4;
a = a - 4; a -= 4;
17
The compound assignment operator provides two benefits. First, they save you a
bit of typing, because they are “shorthand” for their equivalent long forms.
Second, they are implemented more efficiently by the java run-time system than
are their equivalent long forms. For these reasons, you will often see the
compound assignment operators used in professionally written java programs.

Increment and Decrement Operators


The ++ and -- are Java’s increment and decrement operators.
The ++ (Increment Operators) increase its operand by one.
The -- (decrement Operators) decrease its operand by one. For example, this
statement.
x = x + 1; x = x – 1;
can be rewritten like this by use of the
x++; ++x; x--; --x;

These operators are unique in that they can appear in prefix (++x) and postfix
(x++) form. For example:-

The Bitwise Operators


Bitwise and bit shift operators are used on integral types (byte, short, int and
long) to perform bit-level operations.
Java Bitwise and Bit Shift Operators
Operator Description
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift

Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits
is 1, it gives 1. If not, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

18
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)

Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1,
it gives 1. If either of the bits is not 1, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is
denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Why are we getting output -36 instead of 220?

It's because the compiler is showing 2's complement of that number; negative
notation of the binary number.

Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding
bits are different, it gives 1. If corresponding bits are same, it gives 0. For
example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)

19
Bitwise XOR Operation of 12 and 25
00001100
| 00011001
________
00010101 = 21 (In decimal)

The Left Shift


The left shift operator << shifts a bit pattern to the left by certain number of
specified bits, and zero bits are shifted into the low-order positions.
212 (In binary: 11010100)

212 << 1 evaluates to 424 (In binary: 110101000)


212 << 0 evaluates to 212 (In binary: 11010100)
212 << 4 evaluates to 3392 (In binary: 110101000000)

The Right Shift


The right shift operator >> shifts a bit pattern to the right by certain number of
specified bits.
212 (In binary: 11010100)

212 >> 1 evaluates to 106 (In binary: 01101010)


212 >> 0 evaluates to 212 (In binary: 11010100)
212 >> 8 evaluates to 0 (In binary: 00000000)

Program
class RightShift {
public static void main(String[] args) {

int number = 212, result;

System.out.println(number >> 1);


System.out.println(number >> 0);
System.out.println(number >> 8);
}
}

The Unsigned Right Shift


The unsigned right shift operator >>> shifts zero into the leftmost position.
Negative input value show the max range of the datatype.
Bitwise Operator Assignments
I just going through code someone has written and I saw |= usage, looking up on
Java operators, it suggests bitwise or and assign operation.

20
number1 |= number2; same as number1 = number1 | number2. Result is also
same.
Relational Operators

The relational Operators determine the relationship that one operand has to
another. Specifically, they determine equality and ordering. The relational
operators are shown here.
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to

The relational operators have always BOOLEAN value either true or false.
These operators are use in control statement line IF condition and loop. It is
same as C and C++.

 Symbolic constant in java


• In C and C++ we where declaring symbolic constant by using #
define symbolic constant are use full for getting a constant value.
Though out the program.
• Here in java we does not have the keyword like #define so instead of
that they have given special keyword called final ,which is use full for
defining symbolic constant as we can show below
• Syntax
final_datatype_variable name =value
• Example

final float pi=3.14;

21
 Type Casting in Java

Java supports two types of castings – primitive data type casting


and reference type casting.

Reference type casting is nothing but assigning one Java object to


another object.

It comes with very strict rules and is explained clearly in Object


Casting.

Java data type casting comes with 2 flavors.

1. Implicit casting
2. Explicit casting

1. Implicit casting (widening conversion)

A data type of lower size (occupying less memory) is assigned to a


data type of higher size.

This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.

Examples:

int x = 10; // occupies 4 bytes


double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0

In the above code 4 bytes integer value is assigned to 8 bytes double


value.

byte –> short –> int –> long –> float –> double

2. Explicit casting (narrowing conversion)

A data type of higher size (occupying more memory) cannot be


assigned to a data type of lower size.

This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.

The higher size is narrowed to lower size.


22
double x = 10.5; // 8 bytes

int y = x; // 4 bytes ; raises compilation error

In the above code, 8 bytes double value is narrowed to 4 bytes int


value. It raises error. Let us explicitly type cast it.

double x = 10.5;
int y = (int) x;

The double x is explicitly converted to int y. The thumb rule is, on


both sides, the same data type should exist.

In the above statement, left to right can be assigned implicitly and


right to left requires explicit casting.

That is, byte can be assigned to short implicitly but short to byte
requires explicit casting.

Following char operations are possible.

public class Demo

public static void main(String args[]) {

char ch1 = 'A';

double d1 = ch1;

System.out.println(d1); // prints 65.0

System.out.println(ch1 * ch1); // prints 4225 , 65 * 65

double d2 = 66.0;

char ch2 = (char) d2;

System.out.println(ch2); // prints B }

23
 Decision Statements

The decision statements also known as selection statements in java. There are
two decision statements are if and switch.
if statements:-
If statements in Java are used to control the program flow based on some
condition, it’s used to execute some statement code block if expression is
evaluated to true, otherwise it will get skipped. This is a simplest way to modify
the control flow of the program.

Syntex:-
if(condition)
{
Statement;
}

Nested ifs:-
A nested if is a statement that is the target of another if or else. Nested if are very
commonly in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else not already associated with an else. Example:-
if(i == 100)
{
if(j < 20) a=b;
if(k > 100) c=d;
else a =c;
}
else
a = d;

The if-else-if Ladder:-


A common programming construct that I based upon a sequence of nested ifs is
the if-else-if ladder. It look like this:

if(condition)
statements;

else if(condition)
statements;

else if(condition)
statements;
.
.
24
.
else
statement;

Switch..case
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional

case value :
// Statements
break; // optional

// You can have any number of case statements.


default : // Optional
// Statements
}
The following rules apply to a switch statement −
 The variable used in a switch statement can only be integers, convertable
integers (byte, short, char), strings.
 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the
switch and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.

25
 Looping Statement

There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of
the programming languages
Java programming language provides the following types of loop to handle
looping requirements. Click the following links to check their detail.
Sr.No. Loop & Description

while loop
1 Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

for loop
2 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

do...while loop
3 Like a while statement, except that it tests the condition at the end of the loop
body.

While loop:-
A while loop statement in Java programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop is −

while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non zero value.

When executing, if the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the expression result is
true.
When the condition becomes false, program control passes to the line
immediately following the loop.

26
for loop;-
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {
// Statements
}
Here is the flow of control in a for loop −
 The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables and this step ends
with a semi colon (;).
 Next, the Boolean expression is evaluated. If it is true, the body of the loop
is executed. If it is false, the body of the loop will not be executed and
control jumps to the next statement past the for loop.
 After the body of the for loop gets executed, the control jumps back up to
the update statement. This statement allows you to update any loop control
variables. This statement can be left blank with a semicolon at the end.
 The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then
Boolean expression). After the Boolean expression is false, the for loop
terminates.

For-each loop (Advanced or Enhanced For loop):


As of Java 5, the enhanced for loop was introduced. This is mainly used to
traverse collection of elements including arrays. The advantage of for-each loop
is that it eliminates the possibility of bugs and makes the code more readable.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
 Declaration − The newly declared block variable, is of a type compatible
with the elements of the array you are accessing. The variable will be
available within the for block and its value would be the same as the
current array element.
 Expression − This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.

27
class For1
{
public static void main(String a[])
{
int numbers[]={10,20,30,40,50};
for(int x : numbers)
{
if(x==30)
break;
System.out.println(x);

}
}
}

do…while Loop;-
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the control jumps back up to do statement, and
the statements in the loop execute again. This process repeats until the Boolean
expression is false.

 Jumping Statement

Break:-
The break statement in Java programming language has the following two
usages −
 When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement (covered in the
next chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
28
continue:-
The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes control to immediately jump to
the update statement.
 In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue;

Array
An array stores a group of data items all of the same type.

Declare an array variable by specifying the type of data to be stored,


followed by square brackets [].

dataType[] variableName;

Instantiating Arrays
Instantiate an array object using new, the data type, and an array size
in square brackets

int[] nums;
nums = new int[10];

The second line constructs a new array object with 10 integer


elements, all initialized to 0, and stores the reference into nums.

int[] moreNums;
int size = 7;
moreNums = new int[size];

You can declare and instantiate all at once:

String[] names = new String[3];

The elements of the array, String references, are initialized to null.

29
As objects, arrays also have a useful property: length:

 In the above example, names.length would be 3.


 The property is fixed (i.e., it is read-only).

You can reassign a new array to an existing variable:

int[] nums;
nums = new int[10];
nums = new int[20];

The original ten-element array is no longer referenced by nums, since


it now points to the new, larger array.

Initializing Arrays
An array can be initialized when it is created

The notation looks like this:

String[] names = { "hello", "rpbc", "student" };

or

String[] names = new String[]{ "hello", "rpbc", "student" };

This automatically creates an array of length 3, because there were 3


items supplied.

int[] nums = new int[] { 2, 4, 6, 8, 10, 12 };

This array will have a length of 6.

If a new array is being assigned to an existing variable,

30
Two Dimensional Array [Rectangular Array]

Java doenot truely support multidimensional arrays.


In java ,a two dimensional array is simply an array of arrays,

We can see in bellow example

int x = 5;
int y = 5;

String[][] arr1 = new String [x][y];

arr1[0][x] = "hello";
arr1[0][y] = "rpbc";

Jagged Array
A jagged array is an array whose elements are arrays. The elements of
a jagged array can be of different dimensions and sizes. A jagged array
is sometimes called an array-of-arrays.

As we can shown in below example.

class test
{
public static void main( String args[] )
{
int [][]arr = new int[5][];
arr[0] = new int[5];
arr[1]= new int[6];
System.out.println(arr[0].length + " " + arr[1].length );
}

31
Command –line arguments

You can pass argument to the main() method. This can be done at
runtime.

As we know that the main() method takes array of string as argument,


the arguments given to the main() method will be assigned to this
array.

Thus giving commands-line argument is quite easy in java.

Following program shows how to give & receive command-line


arguments in a program.

class test1

public static void main(String args[]) {

for(int i=0;i<arrg.length;i++)

System.out.println(“argument are :”+i+ “ :”+args[i]);

How to run program

 javac test1.java
 java test1 hi hello bye

output

Argument 0: hi

Argument 1: hello

Argument 2: bye

32
Command Line Argument Array
 Sometimes you will want to pass information into a program when you run
it.
 This is accomplished by passing COMMAND-LINE ARGUMENTS TO
MAIN().
 A commang0line argument is the information that directly follows the
program’s name on the command line when it is executed.
 To access the command-line argument inside a java program is quite easy
they are stored as strings in a String array passed to the args parameter of
main().
 The first command-line argument is stored at args[0], the second at
args[1], and so on.

33

You might also like