Anda di halaman 1dari 22

JAVA

Introduction to JAVA

History of Java

Java is a programming language originally developed by James Gosling at Sun Microsystems


(which has since merged into Oracle Corporation) and released in 1995 as a core component of
Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but
has a simpler object model and fewer low-level facilities. Java applications are typically
compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of
computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented
language that is specifically designed to have as few implementation dependencies as possible.
It is intended to let application developers "write once, run anywhere" (WORA), meaning that
code that runs on one platform does not need to be recompiled to run on another. Java is as of
2016 one of the most popular programming languages in use, particularly for client-server web
applications, with a reported 10 million users.

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.

IPSR Solutions Ltd www.ipsr.edu.in 1


JAVA

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:

1. It should be "simple, object-oriented and familiar"


2. It should be "robust and secure"
3. It should be "architecture-neutral and portable"
4. It should execute with "high performance"
5. It should be "interpreted, threaded, and dynamic"

Java Program Structure

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.

IPSR Solutions Ltd www.ipsr.edu.in 3


JAVA

Java naming rules and conventions


All names and keywords in Java are case-sensitive.
Files
Source code is stored in files with the .java extension and must use the public class name within
the file as the prefix of the file name itself. The compiled classes are stored in a file with a .class
suffix – the prefix must again be the same as the name of the initial class held within the file.
Classes
Class names should be nouns. The first letter of each word in the class name should be
capitalized.
For example, MyFirstClass.
Methods
The name of each method is typically a verb. The first letter of the method name should be
lowercase; the first letter of subsequent words should be capitalized.
For example, myFirstMethod().
Variables
A variable name should be short but descriptive. Use the same mixed case as for method names.
For example, employeeTaxCode.
Constants
A constant should be declared with an all upper-case name, using underscores to separate
internalwords.
For example, STANDARD_VAT_RATE
Packages
Java uses “packages” to both group related classes and ensure that potential namespace conflicts
are minimized.Each class resides in a package – if the class does not include a package
specifier, the class is a member of the default package. Each Java class is fully qualified by the
fully qualified class name,which consists of the package name and the class name, concatenated
with dot notation.
Package names of “java”, “javax” and “sun” are reserved for use by Sun.
IPSR Solutions Ltd www.ipsr.edu.in 4
JAVA

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

IPSR Solutions Ltd www.ipsr.edu.in 5


JAVA

9,223,372,036,854,775,807

Int 32 –2,147,483,648 to 2,147,483,647


Short 16 –32,768 to 32,767
Byte 8 –128 to 127
• Floating-point numbersThis group includes float and double, which representnumbers with
fractional precision.
Name Width in Bits Approximate Range
Double 64 4.9e–324 to 1.8e+308
Float 32 1.4e–045 to 3.4e+038

• 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.

IPSR Solutions Ltd www.ipsr.edu.in 6


JAVA

parseXxx() and valueOf()


Both parseXxx() and valueOf() take a String as an argument, throw a NumberFormatException
(a.k.a. NFE) if the String argument is not properly formed, and can convert String objects from
different bases (radix), when the underlying primitive type is any of the four integer types. The
difference between the two methods is
 parseXxx() returns the named primitive.
 valueOf() returns a newly created wrapped object of the type that invoked the method.

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

IPSR Solutions Ltd www.ipsr.edu.in 8


JAVA

Boolean Logical Operators


The Boolean logical operators operate only on boolean operands. All of the binary logical
operators combine two boolean values to form a resultant boolean value.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
The Assignment Operator
The assignment operator allows you to create a chain of assignments. For example, consider
this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?. The ? has this general form:expression1 ? expression2 :
expression3. Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The

IPSR Solutions Ltd www.ipsr.edu.in 9


JAVA

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 output generated by the program is shown here:


Absolute value of 10 is 10
Absolute value of -10 is 10s

IPSR Solutions Ltd www.ipsr.edu.in 10


JAVA

Conditional and looping constructs


Conditional Statements
The if-then and if-then-else Statements

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;

The if-then-else Statement


if (condition) statement1;
else statement2;
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very common
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 and that is not
already associated with an else.

The switch Statement

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

IPSR Solutions Ltd www.ipsr.edu.in 11


JAVA

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

The for Statement


The general form of the for statement can be expressed as follows:

for (initialization; termination_expr; increment)


{
statement(s)
}
When using this version of the for statement, keep in mind that:
 The initialization expression initializes the loop; it's executed once, as the loop begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch statement. The break keyword will stop the execution of the
innermost loop and start executing the next line of code after the block.
Example:

This would produce following result:


10
20
IPSR Solutions Ltd www.ipsr.edu.in 13
JAVA

The continue Keyword:


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 flow of control to immediately jump to the
update statement.
• In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Example:

This would produce following result:


10
20
40
50

IPSR Solutions Ltd www.ipsr.edu.in 14


JAVA

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.

IPSR Solutions Ltd www.ipsr.edu.in 15


JAVA

Output of this program is :My Name is Ammu.


Instance variables
By its definition, an instance variable is unique to each instance of the class; so in general, each
time a class is "instantiated" with the new operator, there is another variable associated with it.
These variables are declared outside any methods you may have. These variables are declared
public, private or protected.
Example:

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.

IPSR Solutions Ltd www.ipsr.edu.in 16


JAVA

When you run the above program, this is the output:


8 -- Welcome -- 1
8 -- Welcome -- 2
8 -- Welcome – 3

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.

IPSR Solutions Ltd www.ipsr.edu.in 17


JAVA

 The parameter list in parenthesis—a comma-delimited list of input parameters, preceded


by their data types, enclosed by parentheses, (). If there are no parameters, you must use
empty parentheses.
 The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
Calling a Method:
To use a method, you have to call or invoke it. There are two ways to call a method; the choice
is based on whether the method returns a value or not.
When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its method-
ending closing brace is reached.
Syntax : method_name(args);
Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order
as their respective parameters in the method specification. This is known as parameter order
association.
When you invoke a method with a parameter, the value of the argument is passed to the
parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal
value, the value of the variable is passed to the parameter. The variable is not affected,
regardless of the changes made to the parameter inside the method.

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

Eg: public void sum(int… num)


{
}
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists

Return Type Methods


When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its method-
ending closing brace is reached.

IPSR Solutions Ltd www.ipsr.edu.in 19


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:

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.
You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

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:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.

IPSR Solutions Ltd www.ipsr.edu.in 20


JAVA

The foreach Loops:


JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.
This would produce following result:

Passing Arrays to Methods:


Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array:

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:

IPSR Solutions Ltd www.ipsr.edu.in 21


JAVA

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:

This program generates the following output:


01234
56789
10 11 12 13 14
15 16 17 18 19
IPSR Solutions Ltd www.ipsr.edu.in 22

Anda mungkin juga menyukai