Introduction to JAVA
History of Java
Java platform
One characteristic of Java is portability, which means that computer programs written in the
Java language must run similarly on any hardware/operating-system platform. This is achieved
by compiling the Java language code to an intermediate representation called Java bytecode,
instead of directly to platform-specific machine code. Java bytecode instructions are analogous
to machine code, but are intended to be interpreted by a virtual machine (VM) written
specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE)
installed on their own machine for standalone Java applications, or in a Web browser for Java
applets. Standardized libraries provide a generic way to access host-specific features such as
graphics, threading, and networking.
Performance
Programs written in Java have a reputation for being slower and requiring more memory than
those written in C. However, Java programs' execution speed improved significantly with the
introduction of Just-in-time compilation in 1997/1998 for Java 1.1, the addition of language
features supporting better code analysis (such as inner classes, StringBuffer class, optional
assertions, etc.), and optimizations in the Java Virtual Machine itself, such as HotSpot,
becoming the default for Sun's JVM in 2000. Some platforms offer direct hardware support for
Java; there are microcontrollers that can run Java in hardware instead of a software Java Virtual
Machine
Principles
There were five primary goals in the creation of the Java language:
The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for
structured, generic, and object-oriented programming, Java was built almost exclusively as an
object-oriented language. All code is written inside a class, and everything is an object, with the
exception of the primitive data types (integers, floating-point numbers, boolean values, and
characters), which are not classes for performance reasons.
Unlike C++, Java does not support operator overloading or multiple inheritance for classes.
This simplifies the language and aids in preventing potential errors and anti-pattern design.
IPSR Solutions Ltd www.ipsr.edu.in 2
JAVA
Source files must be named after the public class they contain, appending the suffix .java. The
Java source file may only contain one public class but can contain multiple classes with other
than public access and any number of public inner classes. A class that is not declared public
may be stored in any .java file.
The compiler will generate a class file for each class defined in the source file. The name of the
class file is the name of the class, with .class appended. For class file generation, anonymous
classes are treated as if their name were the concatenation of the name of their enclosing class, a
$, and an integer.
The method name "main" is not a keyword in the Java language. It is simply the name of the
method the Java launcher calls to pass control to the program. Java classes that run in managed
environments such as applets and Enterprise JavaBean do not use or need a main() method. A
Java program may contain multiple classes that have main methods, which means that the VM
needs to be explicitly told which class to launch from.
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. Since Java 5, the main method can also
use variable arguments, in the form of public static void main (String... args), allowing the main
method to be invoked with an arbitrary number of String arguments. The effect of this alternate
declaration is semantically identical (the args parameter is still an array of String objects), but
allows an alternative syntax for creating and passing the array.
The Java launcher launches Java by loading a given class (specified on the command line or as
an attribute in a JAR) and starting its public static void main(String[]) method. Stand-alone
programs must declare this method explicitly. The String[] args parameter is an array of String
objects containing any arguments passed to the class. The parameters to main are often passed
by means of a command line.
Set path
How to run Java Program in Command Prompt
RunCommand Prompt (found under All Programs/Accessories in the Start menu). Type
C:\> cd \mywork
This makes C:\mywork the current directory.
C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.7.0_01\bin
This tells the system where to find JDK programs.
C:\mywork> javac HelloWorld.java
This runs javac.exe, the compiler. You should see nothing but the next system prompt...
C:\mywork> java HelloWorld
This runs the Java interpreter. You should see the program output:
Hello, World!
If the system cannot find javac, check the set path command. If javac runs but you get errors,
check your Java text. If the program compiles but you get an exception, check the spelling and
capitalization in the file name and the class name and the java HelloWorld command. Java is
case-sensitive!
Data types
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
The primitive types are also commonly referred to as simple types
These can be put in four groups:
• Integers
This group includes byte, short, int, and long, which are for whole-valued signed numbers.
Name Width Range
Long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
• Characters This group includes char, which represents symbols in a character set, like letters
and numbers.
•Boolean This group includes boolean, which is a special type for representing true/false
values.
Wrapper Class
There is a wrapper class for every primitive in Java. For instance, the wrapper class for int is
Integer, the class for float is Float, and so on.
Variables – types (local, instance and class) and how to declare variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
eg: public int i; ,char c;
Local variables. Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables. Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance variables can
be accessed from inside any method, constructor or blocks of that particular class.
Class variables. Class variables are variables declared with in a class, outside any
method, with the static keyword.
Basic Operators
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:
IPSR Solutions Ltd www.ipsr.edu.in 7
JAVA
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
Relational Operators
The relational operators determine the relationship that one operand has to the other.
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
result of the ? operation is that of the expression evaluated. Both expression2 and expression3
are required to return the same type, which can’t be void.
The if Statement
The if-then statement is the most basic of all the control flow statements. It tells your program
to execute a certain section of code only if a particular test evaluates to true.
if (condition) statement1;
Unlike if-then and if-then-else statements, the switch statement can have a number of possible
execution paths. A switch works with the byte, short, char, and int primitive data types. It also
works with enumerated types the String class, and a few special classes that wrap certain
primitive types: Character, Byte, Short, and Integer
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
default:
}
Looping Constructs
The while and do-while Statements
The while statement continually executes a block of statements while a particular condition is
true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. The while
statement continues testing the expression and executing its block until the expression evaluates
to false.
The Java programming language also provides a do-while statement, which can be expressed as
follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of at the top.
IPSR Solutions Ltd www.ipsr.edu.in 12
JAVA
Example:
Introduction to class
The General Form of a Class
class MyClass {
// field, constructor, and
// method declarations
}
In general, class declarations can include these components, in order:
Modifiers such as public or no modifier
The class name, with the initial letter capitalized by convention.
The name of the class's parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
The class body, surrounded by braces, {}.
Creating an Object:
A class provides the blueprints for objects. So basically an object is created from a class. In java
the new key word is used to create new objects.
There are three steps when creating an object from a class:
Declaration . A variable declaration with a variable name with an object type.
Instantiation . The 'new' key word is used to create the object.
Initialization . The 'new' keyword is followed by a call to a constructor. This call initializes the
new object.
Output
x=1
x=1
Static variables
In java, a static variable (also called a class variable), is a variable that is given a fixed block of
memory. The static keyword tells the compiler that there is exactly one copy of this variable in
existence; no matter how many times the class has been instantiated.
Introducing Methods
The syntax of function declaration and definition is:
Modifier return_type method_name (argument list)
{
method_body;
}
More generally, method declarations have six components, in order:
Modifiers—such as public, private, protected or no modifier.
The return type—the data type of the value returned by the method, or void if the method
does not return a value.
The method name—the rules for field names apply to method names as well, but the
convention is a little different.
Variable Arguments(var-args):
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The
parameter in the method is declared as follows:
Typename… argname
Only one variable-length parameter may be specified in a method, and this parameter must be
the last parameter. Any regular parameters must precede it.
IPSR Solutions Ltd www.ipsr.edu.in 18
JAVA
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Array Declaration
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can refer. Here is the syntax for declaring an array
variable:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
A method may also return an array. For example, the method, shown below, returns an array
that is the reversal of another array:
Multidimensional Arrays
Multidimensional arrays are simply arrays of arrays. So a two dimensional array of type int is
really an object of type int array (int []), with each element in that array holding a reference to
another int array. The second dimension holds the actual int primitives. The following code
declares and constructs a two-dimensional array of type int:int[][] myArray = new int[3][];
Notice that only the first brackets are given a size. That's acceptable in Java, since the JVM
needs to know only the size of the object assigned to the variable myArray.
The following program numbers each element in the array from left to right, top to bottom, and
then displays these values: