Java Online Tutorial

X




Resources > Java Quick Notes > {{currentSubTopic}}

Introduction to Java


Introduction :

Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics, user interfaces; can be used to create applications, applets. Because of its rich set of APIs, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Java also has standard libraries for doing mathematical operations.


Features of Java :


Simple :

Java has a concise, cohesive set of features that makes it easy to learn and use. Java is made as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ like pointer arithmetic (or even pointer syntax), structures, unions, operator overloading, virtual base classes, and so on.


Object Oriented :

Simply stated, object-oriented design is a technique for programming that focuses on the data (objects) and on the interfaces (methods) to that object. The object-oriented facilities of Java are essentially those of C++.


Interpreted :

The Java Interpreter can execute Java byte codes directly on any machine to which the interpreter has been ported. Since linking is more incremental and lightweight process, the development process can be much rapid and exploratory.


Distributed :

Java was designed with the distributed environment of the Internet in mind. Java has an extensive library of routines for coping with TCP/IP protocols like HTTP and FTP. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file system.


Secure :

Java is intended to be used in networked / distributed environments. To that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems.


Robust :

Java encourages error-free programming by being strictly typed and performing run-time checks. One of the differences between Java and C/C++ is that Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data.


Dynamic :

In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment. Libraries can freely add new methods and instance variables without any effect on their clients.


Automatic memory management :

Automatic memory management, also known as automatic garbage collection, is the practice of allowing the language implementation to keep track of used and unused memory, freeing the programmer from this burden.

For example, in the C++ programming language, dynamically allocated memory will be de-allocated if the ‘delete’ operator is called.


Architecture Neutral :

The compiler generates an architecture-neutral object file format—the compiled code is executable on many processors, given the presence of the Java run time system. The Java compiler does this by generating byte code instructions which have nothing to do with particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code.


Portable :

Java programs can execute in any environment for which there is a Java run-time system.


High Performance :

While the performance of interpreted byte codes is usually more than adequate, there are situations where higher performance is required. The byte codes can be translated on the fly (at run time) into machine code or the particular CPU the application is running on.


Multithreading :

Java is also a multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multithreading works in a similar way to multiple processes running on one computer.


Java and the Internet :

Java is strongly associated with the Internet because of the fact that the first application program written in Java was Hot Java, a Web browser to run applets on Internet. Internet users can use a Java enabled browser to download an applet located on a computer anywhere in the Internet and run it on his/her local computer. With the support of Java, the Web has become more interactive and dynamic. On the other hand, with the support of Web, we can run a Java program on someone else’s computer across the Internet.


Java Virtual Machine :

All language compilers translate source code into machine code for a specific platform. Java compiler produces an intermediate code known as byte code. Translating a Java program into byte code helps make it much easier to run a program in a wide variety of platforms. That is, only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU. This helps achieve platform independence.

JIT :

When a program is interpreted, it generally runs substantially slower than the one compiled to executable code. However, with Java, the difference between the two is not so great. Sun Microsystems supplies its own Just in Time (JIT) compiler for byte code. When the JIT is part of the JVM, it compiles byte code into executable code in real time, on a piece-by-piece, demand basis. It is not possible to compile an entire Java program into executable code all at once, because Java performs various run-time checks that can be done only at run time. Instead the JIT compiles code as it is needed, during execution.


JDK :

The Java Development Kit (JDK) is a Sun Microsystems product for the Java developers. On 17 November 2006, Sun released it under the GNU General Public License (GPL), thus making it free software. JDK has the following primary components as its contents:
java – The loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler.
javac – The compiler, which converts source code into Java byte code.
jar – The archive, which package related class libraries into a single JAR files. This tool also helps manage JAR files.
javadoc – The documentation generator, which automatically generates documentation from source code comments.
javap – The class file disassembler.
applet viewer – This tool can be used to run and debug Java applets without a web browser.
javah — The C header and stub generator, used to write native methods.
javaws — The Java web Start launcher for JNLP applications.
extcheck — This utility can detect JAR-file conflicts.

The JDK also comes with a complete Java Runtime Environment, usually called a private runtime. It consists of a Java Virtual Machine and all of the class libraries present in the production environment, as well as additional libraries only useful to developers, such as the internationalization libraries and the IDL libraries.
Note that the JDK forms an extended subset of a software development kit (SDK). Along with JDK the SDK is composed of extra software, such as Application Servers, Debuggers, and Documentation.


JRE — Java Run Time Environment :

The Java Runtime Environment is an emulator that creates a Java Virtual Machine environment that can execute Java programs. Java compiler produces byte code, the Java Runtime Environment then runs the byte code in the JVM. To run a java program the system must have JRE.

JRE = JVM + Java Package Classes + Runtime Libraries
Java Package classes:

Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.

Runtime Libraries:

The Java Class Library is almost entirely written in Java itself, except the parts that need to have direct access to the hardware and operating system (as for I/O, or Graphic Rasterisation). The Java classes that give access to these functions commonly use JNI wrappers to access the native API of the operating system.


Simple structure of a Java program :


// This is my first program
public class HelloJava {
	public static void main (String [] args) {
		System.out.println(”Hello World”);
	}
}
public :

The keyword public denotes that a method can be called from code in other classes, or that a class maybe used by classes outside the class hierarchy. The class hierarchy is related to the name of the directory in which the java file is.

static :

The keyword static in front of a method indicates a static method, which is associated only with the class and not with any specific instance of that class. Only static methods can be invoked without a reference to an object. Static methods cannot access any instance variables of the class.

String [] args :

The main method must accept an array of String objects. By convention, it is referenced as args although any other legal identifier name can be used. It is used to take in the command line arguments.

System.out.println(); :

Printing is part of a Java standard library. The System class defines a public static field called ‘out’. The out object is an instance of the Print Stream class and provides many methods for printing data to standard output, including println (String) which along with printing the string, also appends a new line to it.


Compiling Java Source Code :

Before the Java Virtual Machine (JVM) can run a Java program, the program’s Java source code must be compiled into byte code using the ‘javac’ compiler. To compile a Java source code file HelloJava.java, you would do the following:
Directory containing the file to compile>javac HelIoJava.java
For example, the results of a successful compilation of HelloJava.Java will produce a byte code version of the class in a file named HelloJava.class.


Running a Java application :

Once you have successfully compiled your Java source code, you can invoke the JVM to run your application’s byte-code:
Directory containing the class’ file to run > java HelloJava



Comments :

A comment is a text that provides explanations to your code. Comments are completely ignored by the compiler, so you can place any text you wish in a comment. Using plenty of comments in your programs is a good idea to explain what your program does and how it works. Java has three basic types of comments: end-of-line comments, traditional comments, and JavaDoc comments.


total = discount Percent; // This is End-of-line comments
/* This is traditional comment
HelloApp sample program.
This program demonstrates the basic structure that all Java programs must follow. */

Difference between C++ and Java


1) Java does not support an explicit pointer type.
2) Java has labeled break and continue statements.
3) Java does not contain ‘struct’ and ‘union’ data types.
4) Java adds new operators such as ‘instance of’ and ‘>>>’.
5) Java does not include the C unique statement keywords size of’, ‘goto’ and ‘typedef’. Java does not define the type modifiers keywords ‘auto’, ‘extern’, ‘register’, signed’ and ‘unsigned’.
6) Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements.
7) Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.
8) There are no header files in Java.
9) Java does not support global variables.
10) Java does not support user defined operator overloading.
11) Java does not have template classes as in C++.
12) Java does not support multiple inheritance of classes. However, this is accomplished using a new feature called ‘interface’.


Advantages of Java


1) The Java designers eliminated manual memory allocation and deallocation.
2) Memory in Java is automatically garbage collected. You do not have to worry about memory corruption.
3) They introduced true arrays and eliminated pointer arithmetic.
4) They eliminated the possibility of confusing an assignment with a test for equality in a conditional statement.
5) You cannot even compile: if (ntries = 3)… (this is a common source of confusion in C/C ++ code.)
6)They eliminated multiple inheritance; replacing it with a new notion of interface’.
7) Interfaces give you most of what you want from multiple inheritance, without the complexity that comes with managing multiple inheritance hierarchies.


Types of Java Programs


Applets:

Programs created specially to work with the Internet.


Command line applications:

Java programs that run from a command prompt and don’t display any GUI screen.


GUI Applications:

Java programs that run stand-alone and accept user input through a GUI based screen.


Servlets:

Suitable for web based n-tier application development. Client sends request which is processed by the server. The server side APIs extends capabilities of standard APIs and are known as Servlets also called server side applets.
Example: HTML form processing, process databases and perform server side transactions.


Packages:

Class libraries in Java, A programmer can create his/her own packages or use the built-in packages. java.awt, java.io and java.applet are some examples.


Database application:

Uses JDBC API for database connectivity.


Note:

Programs can, be either applets or application.


Difference between Applets and Applications


1) Applications do not need a browser to execute.
2) Applications run within JVM.
3) Starling point of an application is the main () method.
4) Starting point of an applet is the init () method.
5) Applications have no restrictions about reading or writing from/to the local file system.
6) Applets flow of execution is partly managed by the browser context
7) Applets cannot read/write from/to the local file system.



Variables, Data Types and Operators


Unicode character Set :

A Unicode character set is a standard that supports all the international characters of various languages. These characters denote any alphabet, digit or special symbols used to represent information. It supports classical and historical texts of many written languages.


Keywords :

Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 50 words as keywords. These keywords, combined with operators and separators according to syntax, from definition of the java language.



Here’s list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.


Identifiers :

Identifiers are names we give to our variables, constants, classes, and methods. Identifiers must comply with these rules:
The first character of an identifier must be a letter, an underscore (_), or a dollar sign ($).
The rest of the characters in the identifier can be a letter, underscore, dollar sign, or digit. Note that spaces are NOT allowed in identifiers.
Identifiers are case-sensitive. This means that age and Age are different identifiers.
identifiers cannot match any of Java’s reserved words.
Example:

My class
$ amount
total Grades;

Data Types :


A data type in programming languages is a set of values and the operations on those values. Data types specify the size and type of values that can be stored. The variety of data types available allows the programmer to select the type appropriate to the needs of the application. Data types can be broadly classified into two groups:



Primitive Data Types :

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name. The primitive data types include boolean, byte, short, int, long, float, double and char.



Non-primitive Data Types :

Non-primitive data types in Java are reference variables (object references), arrays and enums. All non-primitive data types are references to heap memory where the objects live.


Variables


Variable is a memory location to store a data, referred by a symbolic name. The data may or may not vary during the program execution. The data must be assigned to the variable at some point in the program. The assignment of value to the variable is called as initialization or assignment. After the assignment, the data can be accessed or manipulated at some point of the program by simply referring the variable name.


Declaring variables :

type variab1e1, variable2,...,variableN;
int x;
String name;
double radius;
int y, z;

Initializing variable :

A variable must be given a value at the time of declaration or using in any expression. The variable can be initialized in two ways:
1. By using an assignment statement
2. By using read statement

Example: By using an assignment statement:

type variableName = value;

OR

type variableName;
variableName = value;
int a = 10; /* declares and initializes an integer variable. */

OR

int a;	// declares an integer variable.
a = 10; // initializes an integer variable.
char c = ‘x’; // declares and initializes a character
double b = 2.33; // declares and initializes a double

Example: By read statements:

import java.io.*;

class Read{
	public static void main (String arg []) {
		DataInputStream ds = new DataInputStream (System.in);
		int number;
		System.out.println (“Enter a number”);
		number = Interger.parseInt (ds.readLine());
		System.out.println(“Number =” + number);
	}
}

Declaring class variable :

A class variable is declared inside the class but not in the method. It can be used by any method in that class including static methods. To do so you must include the keyword ‘static’ in front of class variable.

Example:

class MyApp {

	static int a = 10;

	public static void main (String [] arg) { 
		System.out.println (a); 
	}
}

Declaring instance variable :

An instance variable is declared inside the class but not in the method without any static keyword. In order to access instance variable of class by a static method we need to create an instance of a class. An instance method of a class (without the keyword static) can directly access instance variable of that class.

Example:

class MyApp {

	int a=10;

	public static void main(String [] arg) {
		MyApp m=new MyApp();
		System.out.println(a);
	}
}

Local variable :

A local variable is a variable declared inside the body of a method, or formal parameters to a method, or within a block of code contained within the body of a method. These variables are accessible only within the method only or the block of code within the method; and other methods cannot access them.

Example:

Class MyApp	{

	public static void main (String [ ] arg) {
		int a = 10;
		MyApp m = new MyApp();
		System.out.println (a);
	}
}

Variable scope :

Variables scope refers to the accessibility of a variable. These variables are accessible within the statement block only; such as a variable declared inside ‘for’ or ‘while loop is accessible in that block only.


class stat {
	public static void main (String [] args) {
		for (int j = 0; j < 4; j ++) {

			System.out.println(j);
		}
		System.out.println (“outside “ + j);
	}
}

The above program will give compile time error as in the above program the scope of the variable j is only within for the loop.


Initialization blocks in Java :

Initialization blocks can be:
Static
Instance

Static Initialization Blocks :

A static initialization block is a normal block of code enclosed in braces, { }, and proceeded by the static keyword. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. They are executed automatically, when the class is loaded in memory. There is an alternative to static blocks - you can write a private static method. The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.


Initializing Instance Variables

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initialize blocks and final methods. Initialize blocks for instance variables look just like static initialize blocks, but without the static keyword. The Java compiler copies initialize blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. A final method cannot be overridden in a subclass. Here is an example of using a final method for initializing an instance variable. This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.


Some rules:

Rule 1: Initialization blocks execute in the order they appear.
Rule 2: Static initialization blocks run once, when the class is first loaded.
Rule 3: Instance initialization blocks run after the constructor's call to super ( ).
Rule 4: Instance initialization blocks run every time a class instance is created.
Rule 5: Instance blocks run after static blocks.


Operators


Operators are special symbols, which represent a particular operation that can be performed on some data. The data is called as ‘operand’. For example, 8+5–7; here 8,5,7 are called operands and +, - are called operators. Depending upon the number of operands and its functions, the operators can be classified into four groups:
1) Unary Operator
2) Ternary Operator
3) Binary Operator
4) Assignment Operator


Unary Operator


Unary in literal terms means ‘single’. These operators need one operand to perform an operation.



Binary Operator


An operator which has two operands is called as Binary operator. The following are binary operators.


Arithmetic Operator

Arithmetic operators are used to perform mathematical operations.



Relational Operator

Relational operators are used to compare two operands to check whether the first one is greater/less/equal/unequal than the second. The result of a Boolean expression is either true or false.



Logical Operators

Logical operators are those operators that are applied to the logical expression. The output of the expression will be either true or false.



Bitwise Operator

An operator that permits the programmer to access and manipulate individual bit of a data is called bitwise operator. Among the bitwise operators, ones complement is unary.



Assignment Operator


The assignment operator has single equal sign = All the arithmetic operators can be combined with assignment operator & can be made compound operator.



Note that the difference between simple and compound assignment operator is that, compound operators do not make temporary variables during operations.
All the binary operators except relational operators can be combined with assignment operators.


Ternary Operator (Conditional Operator)


?: it takes three operands, therefore it is called as ternary operator. The ternary operator has the following operator formation:
condition? expressionl:expression2

First, the condition is evaluated. If the condition is true then expression1 will be carried out and the result is returned, else expression2 will be carried out. The expression can be simple or compound or it can be another ternary operator. This is also called as conditional operator.

Parenthesis is not necessary for the condition because precedence is very low for the conditional operator.
Example:

int a=5,b=7;

z=a<b? a:b;

System.out.println (z);

Output:
5


Separators in Java:



Java Operator Precedence Table



Literals

Literal means any number, text, or other information that represents a value. This means what you type is what you get.


Integer Literals

An integer literal is a sequence of digits. To represent the type as long integer we use L as a suffix. We can specify the integers either in decimal (leftmost digit non-zero), hexadecimal(prefix the literal with 0x) or octal (prefix the literal with 0) format.



Character Literals

We can specify a character literal as a single printable character in a pair of single quote characters such as ‘a’, ‘#’, and ‘3’. The ASCII character set includes 128 characters including letters, numerals, punctuations etc. The table below shows the codes that can represent these special characters.



If we want to specify a single quote, a backslash, or a nonprintable character as a character literal use an escape sequence. An escape sequence uses a special syntax to represent a character. The syntax begins with a single backslash character.

In the table below the character literals use Unicode escape sequence to represent printable and non printable characters both.



Boolean Literals

The values true and false are also treated as literals in Java. When we assign a value to a boolean variable, we can only use these two values. Unlike C, we can’t presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. Example:
boolean chosen = true;

Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if it is in quotation marks.


Floating-point literals

Floating-point numbers are like real numbers in mathematics, for example, 4.13l79, – 0.000001 Java has two kinds of floating-point numbers float and double. The default type when you write a floating-point literal is double.



A floating - point literal can be denoted as a decimal point, a fraction part, an exponent (represented by E or e) and as an integer. We also add a suffix to the floating point literal as D, d, F or f. The type of a floating-point literal is by default double-precision floating-point. The following floating-point literals represent double-precision floating-point & floating-point values.



String literals

The string of characters is represented as String literals in Java. In Java a string is not a basic data type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods provided in Java to combine strings, modify strings and to know whether two strings have the same value. We represent string literals as:
String myString = ‘How are you?”;


null literal

The final literal that we can use in Java programming is a null literal. We specify the Null literal in the source code as ‘null’. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables.

For instance;
s =null;
In this example, suppose an object is referenced by s. We reduce the number of references to an object by assigning null to s.


Type Conversion

The type conversion in Java is of two types:
1. Automatic type conversion
2. Explicit Conversion or Casting


Automatic type conversion

When one type of data is assigned to another type of variable an automatic type conversion will take place, if the following conditions are satisfied:
The two types are compatible
The destination type is larger than the source type in terms of number of bytes
Example:

int x=10;
byte y=2:
x=y; // byte to int automatic conversion.

Casting

It is used to perform conversion between incompatible data types, in terms of size and type.
Syntax:
(Target_type) value;
Target type specifies the desired type to convert the specified value.

int i=257;
byte b;
b=(byte)I; //now value of b is 1.



Control Statements


Statements that enable the user to control the flow of the program are called control statements or control structure. Control statements are broadly classified as:
1) Sequential
2) Selection
3) Iteration
4) Jump


Sequential

In a program, if all the statements are executed sequentially, then that control structure is called as sequential control structure. By default a program has sequential control structure.


Selection

In a program if a statement or a group of statements are executed depending on the evaluation of a condition then they are called as selection statements or conditional statements. If the condition is true then certain set of statements are executed, else either other set of statements are executed or no statement is executed. In Java, the following selection statements are used.

if
if ..... else
if …… else if …… else
switch-case

If

The if statement is one of the selection statements used to make decisions.
The structure of an if statement is as follows:
if (condition)
Statement;

The condition involves a single relational expression or many relational expressions combined into one condition with the logical operator. It returns either true or false.

If the condition is true, a single statement which immediately follows the parentheses will be executed.

If there are multiple statements to be executed, then they should be placed within the curly braces ({}). This is called as a block.
Example:

if (condition) {
statement 1;
.
.
.
statement n;
}

if…else

The if….else statement is also a selection statement used to make decisions. If the condition is true, then statement after if is executed , if false statement after else is executed.
The structure of if….else statement is as follows:

if	(condition) {
statement 1;
}
else {
statement 2;
}

It is important to know that after the else, no condition can be given.
If there are a number of statements to be executed after the condition or after the else, then it should be placed inside the block.

if	(condition) {
statement 1;
.
.
.
Statement n;
}
else {
Statement 1;
Statement n;
}

Switch

The switch statement is a selection statement. It is an extension of if…else statement. In if.....else, we can have only two branches either true or false, but switch statement permits any number or branches. The branches are called as cases.

switch (variable or expression) {
case value:
statement 1;
break;
case value 2:
statement 2;
break;
.
.
.
case value n:
statement;
break;
default :
statement;
}

Followed by the keyword switch, a variable or an expression is placed in the parenthesis. The evaluation of the expression or variable should be char, byte, short, int (enums according to J2SEI .5).

The body of the switch statement is enclosed in braces. It consists of Case Labels, which take the keyword case followed by a constant value. The value should be of the same type as the switch variable. The case labels are followed by a colon. The case labels need not be consecutive. If expected value of the switch variable is an int (eg. 89), then the case label should be like below:

When a switch variable or expression is evaluated, the control is transferred to the case label whose constant is equal to the yielded value of the expression and then all the statements followed by the case label are executed. In between the case label and the break statement, n number of statements, of any type can be placed. The break statements are used to terminate the execution. If break statements are omitted, then the execution proceeds till the end of the closing brace, because switch….case functions like a waterfall. Since it is not desired to execute all the cases, we insert break to terminate the switch. A special label default can be used. If the expression does not match any of the case labels, the control is transferred to the default label if it is present. If it is not present, then the switch statement is skipped.


Iteration

In a program, if a statement or groups of statements are executed repeatedly depending on the evaluation of a condition then it is called as Iterative structure or loops. The difference between selection and iteration is the selection executes the statements only once, whereas Iterative statements execute repeatedly.

In Java, following iterative statements are used.
for
while
do...while


for loop

The most widely used looping is probably for loop. It is used for iterative execution. The general syntax of the for loop is:

for (initialization; condition; updation) { 
	statements;
}

The three parameters initialization, condition and updation determine the number of times the loop will be executed. These three expressions me separated by semicolon.


Initialization

It is used to initialize the variable, which is going to be used in the loop. In general, the initialization is done with the assignment operator.
for (i =0; condition; updation)

There can be many initializations, but each one should be separated by comma.
for (j=0, k=4; condition; updation) {}

The initialization can be done before the loop anywhere in the program, but the semicolon (;) has to be placed at the place of initialization.
For (;condition; updation) {}

Note that in C++ the loop variables are visible outside the loop, whereas in Java, the loop variables are visible only inside the loop.
for (int i =0; i <5; i++)
The variable i will be in existence only till the end of the for loop.


Condition

It is a relational expression that determines the termination of the loop. The body of the loop will be executed till the condition fails.

There must be only one condition. Multiple conditions can be combined with the logical operators and made as one condition,
for (j=0 ; j<4&&j>7; updation)

Absence or illogical test conditions lead to infinite loops.


Updation

It increases or decreases the value each time the loop segment is executed.
More than one increment/decrement operator can be placed in the loop. Each one should be separated by comma operator.

Increment/decrement may or may not appear in the parentheses. If it does not appear in the parenthesis it may appear along with the statements inside the block { }.


Statements

They can be of any type and in any number. Declaration, initialization, conditional or iterative statement can be inside the loop. If a for loop or while loop is placed inside a statement, then that is called as nested loops. A nested loop allows large number of possibilities. There is no limit on how deeply nested loops can be placed.


Execution

In a for loop:
1. First the initialization is done.
2. Then the condition is checked. If the condition is true, the body of the loop {} will be executed. If false, the loop terminates.
3. Then the increment/decrement is done.
4. The 2nd & 3rd process continues till the condition becomes false.


Enhanced for loop

The enhanced for loop allows you to iterate through Collection & Array very easily without any iterator or condition. Instead of having three components enhanced for loop has two components.

The syntax of enhances for loop is:
for (declaration : expression)

The two components are:

Declaration: This is the newly created type variable which is compatible with the element of Array or Collection. This variable is going to exist in this for loop block only. And the value of this variable will be the same as current array element.

Expression: This component must be evaluated to the array you want to loop through. This could be an array variable, Collection or a method call that returns array. The array can be of ally type: primitive, object, even array of array.


Example of having legal & illegal declaration:

int y;
long y2
long [ ] la = {7L, 8L, 9L}
String [ ] sName = {“one”, “two”, “three”};
Animal [ ] animal = {new Dog ( ), new Cat ()};

//legal declarations
for (long a : la); 			// loop thru an array of long
for (String s: sName) ;   	// loop thru an array of String
for (Animal an: animal); 	// set an Animal reference to each element

//illegal declaration
For (y2: la);				// y
y2 is already declared
For (int s : la); 			// can’t fit a long into an int
for (Cat c : animal); 		// you might get a Dog

while loop

The while loop is an iterative control statement. It executes a segment of code repeatedly. It is also called as pre-test while loop. The general form of the loop is:

while (condition) {
	Statements;
}

First the condition is evaluated. If the condition is true, it executes the body of the loop. After the execution, again it evaluates the condition, if true, it executes again. So long as the condition remains true all the statements within the body of the loop is getting executed repeatedly. Since the condition is evaluated before the execution of the loop, it is called pre-tested loop. Here the condition can be of any relational expression or a group of relational expressions combined with the logical operator. Similar to for loops, any kind of statement (or statements) can be placed inside the block and nested loops can be created.

The do while loop is an iterative control statement. It executes a segment of code repeatedly until the condition fails. It is also called as post-test while loop. The general form of the loop is:

do {
	Statements;
} while (condition);

The difference between while and do… while loop is that, in while loop the body of the loop is executed first time only when the condition is true but in do… while the body of the loop is executed first time, before it checks the condition. Therefore even if the evaluation of the condition is false, the loop will be executed at least once.

int x=1;
while (x) {}	//won’t compile x is not a Boolean

while (x=1){}	//won’t compile could not resolve to Boolean

While (x==1){}	//Legal, equality test

While (true){}	//Legal

Jump statements

Statements which transfer the control to a specific place by bypassing certain instructions and continue executing the remaining set of statements are called as jump statements. It is generally used in the selection or iteration structure. The following jump statements are used in Java.
1. break
2. continue
3. return


break

The break statement terminates the execution of the loop by transferring the control outside the loop without executing all the statements followed by it. The execution continues from the statement just after the loop.

for	(int i =0; i <5;i++) {
	System.out.println (“hi”);
	System.out.println ("welcome");
	break;
}

Output:
hi
welcome

Continue

The continue statement almost works opposite to the break statement. It transfers the control to the beginning of the loop by skipping all the statements followed by it. In the ‘for’ loop, the continue statement, transfers the control to the increment part of the loop and then the condition is evaluated. Whereas in the while or do-while, it transfers the control to the condition part of the loop, which is evaluated. In while & do...while loop the improper use of continue statement causes infinite loops.

Example I:
for (int i =0; i <2; i++)
	System.out.println (“hi”);
	continue;
	System.out.println (“welcome”);
}
System.out.println (“bye”);

Output:
Example.java:10: unreachable statement
System.out.println (“welcome’);
^
Example 2:
for (int i = 0; i < 2; i++) {
	System.out.println (“hi”);
	System.out.println (“welcome”);
	continue;
}
System.out.println (“bye”);

Output
hi
welcome
hi
welcome
bye

Return statement

The return statement is used explicitly to return from a method. That is, it causes program control to transfer back to the caller of the method. For such property it is categorized as jump statement. Although a full discussion of return can be shown in methods call.
Example

class Example {
	public static void main (String [ ] arg) { 
		System.out.println(“Hello java”); if (true)
		return;
		System.out.println(“end”);
	}
}
Output:
Hello java

Unlabeled statement

Both continue & break statement can be used as labeled or unlabeled. As it is very common to use unlabeled statement, till now all the examples which we have covered are unlabeled statement examples.


Labeled statement

This statement can be used for block of statement. A label can be any identifier in java or variable. This can be used by placing label before loop with the colon at the end. It is frequently used in for, while, do while. Here, if you want to jump outside the nested loop or to continue a loop that is outside the current loop, then we can use labeled break or continue statement.
Example of labeled break

boolean is=true;
int i =0;
labell:
do {
	System.out.println(“before”);
	while (is) {
		System.out.println(“hi”);
		break labell;
	}
	System.out.println(“bye”);
} while (i<3);
System.out.println(“end”);

Output:
before
hi
end

If you solve this program with the help of unlabeled statement it will go in infinite loop. But because of labeled loop the output terminates before because the label1 labels the outer loop and therefore the statement break label1 causes the execution to break out of both the loops.
Example of labeled continue:

boolean is=true;
labell:
for (int i =0; i <3; i++) {
	System.out.println(“before”); 
	while (is) {
		System.out.println(“hi”);
		continue labell;
	}
	System.out.println(“bye”);
}
System.out.println(“end“);

Output:
before
hi
before
hi
before
hi
end

This program too will go in infinite loop if we use unlabeled statement. But because of labeled statement it doesn’t print bye and goes to the labeled part which is before for loop and then increments the value of i in for loop.


Arrays, String and Vector


Arrays

An array is a data-structure, which holds a fixed-size sequential collection of elements of similar data type, sharing a common name.
The individual value in an array is known as element.The position of the element is indicated by the subscript or index number.
Once an array is created, it cannot grow or shrink.


Constructing an array

The three steps to construct an array are as follows:

1. Declare a reference to an array
Syntax:
data Type [ ] arrayRerfVar;
data Type arrayRefVar [ ];

2. Create memory— this is done using new keyword.
Syntax:
arrayRerfVar = new dataType [size];

3. Initialize the array — assign initial values to array elements (optional)
Syntax:
arrayRerfVar [subscript] = value;

double [ ] myList;			// Step 1
myList = new double [10];		// Step 2
myList [0] = 5.6;			// Step 3


Multi-dimensional array

Method 1:

1. Declare a reference to an array: To declare multi- dimensional arrays, you need to specify multiple square brackets after the array name. Each pair of square brackets represents one dimension.
Syntax:
datatype [ ] [ ] arrayRefVar: preferred
datatype arrayRefVar [ ] [ ]

2. Create memory:
Syntax:
arrayRefVar = new datatype [row] [column];

3. Initializing the array:
Two subscripts are used in a two dimensional array, one for the row and the other for the column.
Syntax:
arrayRefVar = [row _ index] [co1 _ index]; = value;
Example:

int [] [] x; // declare an array
x = new int [3] [4]; // create memory
x [2] [1] = 7; // assign value 7 to a specific element at row 2 and column


Method 2:

You could declare and construct an array in one statement as follows:
dataType [ ] [ ] arrayRefVar = new dataType [row] [co1];
Example: int [ ] [ ] x = new int [3] [4];


Method 3:

You can initialize the 2 dimensional arrays as below:
int x [ ][ ] = { {1,2}, {3,4} };


Constructing and initializing an anonymous array

The second shortcut is called “anonymous array” & can be used to construct & initialize an array, and then assign the array to the previously declared array reference variable. The construction is as follows:
int anon _ arr [ ];
anon_ arr = new int [ ] {3, 1, 8};


Jagged/ Ragged arrays

Each row in a two-dimensional array is itself an array. Thus, each row can have different length (i.e. different number of columns).
An array of this kind is known as n ragged array.
Syntax:
dataType [ ] [ ] arrayed = new data Type [row] [ ];
Example:

int [] [] T = new int [3] [];
T [0]	= new int [2];
T [1]	= new int [4];
T [2]	= new int [3];


Processing single dimensional arrays

When processing array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known.
Example:

public class Test Array {
	public static void main (String [ ] args) { 
		double [ ] myList 1.9, 2.9, 3.4, 3.5}; // Print all the array elements
		for (int i = 0; i < myList. length; i++) { 
			System.out.println (myList [i] + “ ”); 
		}

		//summing all elements 
		double total = 0;
		for (int i = 0; i < myList.length; i++) {
			total += myList [i]
		}
		System.out.println (“Total Is”+ total);
		
		//Finding the largest element 
		Double max = myList [0];
		for (int i = 1; i < myList. length; i++) { 
			if (myList [i] > max) 
				max = myList [i];
		}
		System.out.println (“Max 15” * max);
	}
}

Processing two dimensional arrays

Initializing arrays with random values:

The following loop initializes the array with random values between 0 and 99:

for (int row  = 0; row < row++) {
	for (int column = 0; column < matrix [row]. length; column++) { 
		matrix [row] [column] = (int) (math. random ( )* 100); 
	}
}

Printing arrays with random values:

To print a two dimensional array, you have to print each element in the array using a loop like the following:

for (int row  = 0; row < row++) {
	for (int column = 0; column <; column++) {
		System.out.Print (matrix [row] [column] + “ ”);
	}
	System.out.println ( );
}

Copying array elements


Method 1: Using for loop
int [] sourceArray = {2, 3, 1, 5, 10} ;
int [] targetArray = new it [souranceArray.lenght];
for (int i = 0; i < sourceArray.lenght; i ++) { 
	targetArtay [i] = sourceAray [i]; 
}

Using library method System.arraycopy ()

The library method System.arraycopy () is useful for coping a number of elements from one array to another. The method can be used on any time array and is declared as follows:
public static void arraycopy (object sourceArray, intsrc_pos, object targetArray, int tar_pos, int length)

The parameters src_pos and tar_pos indicate the starting positions in sourceArray and targetArray, respectively. The number of elements copied from sourceArray to targetArray is indicated by length. The destination array must already be allocated.
Example:

int [] sourceArray = {2, 3, 1, 5, 10};
int [] targetArray = new int [source Array.length];
System.arraycopy (sourceArray, 0, targetArray, 0, sourceArray.length);

String


String represents sequence of characters. Java implements String as objects of type String. There are two types of String Objects:


Immutable:

These are objects which once created cannot be modified. The String class is immutable when you create a String object, you are creating a string that cannot be changed. You can still perform all types of string operations. The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged.


Mutable:

These are objects whose contents can be modified. At any point in time this type of string contains some particular sequence of characters, but the length and content of the sequence can be changed. StringBuffer and String Builder class supports mutable String objects.


Creating Strings

We can declare a String variable and directly store a String literal using assignment operator.

String str = “Hello”; / / “Hello” is string literal — in this case compiler creates a String object with its value (i.e. “Hello”)

We can create String object using new operator with some data.
String S1 = new String (“Java”);

We can create a String by passing character array to the constructor:
char arr [ ] = {‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’};
String s2 = new String (arr);

We can create a String by passing array name and specifying which characters we need:
String s3 = new String (str, 2, 3); //Here starting from 2nd character a total of 3 characters are copied into String s3.



String literals (objects) are stored in a special memory area known as string Constant pool – which is part of heap.

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn’t exist in the pool, a new string instance is created and placed in the pool.

Case 1:
String s1= “abc”;
String s2= “abc”; //will not create new instance

In the above example only one object will be created. Firstly JVM will not find any string object with the value “abc” in string constant pool, so it will create a new object. After that it will find the string with the value ‘abc’ in the pool, it will not create new object but will return the reference to the same instance.


Case 2:
String S1 = new String (“abc”);
String S2 = new String (“abc”);

In such case, JVM will create 2 new string object in normal (non pool) heap memory.


Case 3:
String s = “abc”;
String s1 = s.concat(“def”);  
System.out.println(s1); 	//will print “abcdef”

Here, abc is not changed but a new object is created with abcdef. concat ( ) method appends the string at the end.


String Methods

The String Class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.

To know more about class String and String methods, visit Java Docs


StringBuffer


StringBuffer objects are mutable sequence of characters.
They are synchronized (thread-safe); it does not allow two threads to simultaneously access the same method. Each method can be accessed by one thread at a time.
The methods that directly manipulate data of the object are available in StringBuffer class.
StringBuffer is faster than String when performing simple concatenations and also when you want dynamic String concatenation. Common use of this class is in file I/O.
Example:

StrinBuffer str = new StringBuffer (“Ok”);
str.append (“Bye”);
System.out.println (Str);

Output:
OkBye




To know more about class StringBuffer and StringBuffer methods, visit Java Docs


Vector


Vectors (java.util.Vector class) are commonly used instead of arrays, because they can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
Java Vector is a resizable array of objects which implements the List interface.
Like an array, elements of the Java Vector can be accessed using an index.
Vector is synchronized.
Example:

Vector intVect = new Vector ( );		//declaring without initial size
Vector list = new Vector (3);		//declaring with initial size 
Vector <String> v = flew Vector<String> ( );

A vector can be declared without specifying any size explicitly. In contrast, all array must always have its size specified.


Advantages of Vectors over Arrays

1) It is convenient to use vectors to store objects.
2) A vector can be used to store a list of objects that may vary in size.
3) We can add and delete objects from the list as and when required.
4) A major constraint in using vectors is that we cannot directly store simple data type in a vector, we can only store objects. Therefore, we need to convert simple types to objects (for versions below jdkl.5). This can be done using wrapper classes.
5) From JDK 1.5, autoboxing takes care of converting primitives to objects.
6) The Vector class supports a number of methods that can be used to manipulate the vectors.
7) Each vector tries to optimize storage management by maintaining a capacity and a capacity Increment. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector’s storage increases in chunks the size of capacity Increment. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Example:

import java.utitl. *;
class ExampleVector {
	public static void main (String args []) {
		String name [ ] = {“JAVA”, “C++”, “FORTRAN”, “BASIC”}; 
		Vector list = new Vector ( ); 
		int length = name.length;
		for (int i = 0; i<length; i++) {
			list.addElement(name[i]);
		}
		list.insertElementAt (“COBO”,2);
		int size = list.size ( );	
		String listArray [ ] = new String [size]; 
		list.copyInto (listArray); 
		System.out.println (“list of Language”); 
		for (int i = 0; i<size; i++) {
			System.out.print(listArray[i]);
		}
	}
}
Output:


To know more about class Vector and Vector methods, visit Java Docs

name