Vous êtes sur la page 1sur 15

JAVA PROGRAMMING UNIT I

JAVA

Java is a platform-independent programming language used to create secure and


robust application that may run on a single computer or may be distributed
among servers and clients over a network.
Java features such as platform-independency and portability ensure that while
developing Java EE enterprise applications, you do not face the problems related
to hardware , network , and the operating system.

HISTOY OF JAVA

Java was started as a project called "Oak" by James Gosling in June 1991.
Gosling's goals were to implement a virtual machine and a language that had a
familiar C like notation but with greater uniformity and simplicity than C/C++.
The First publication of Java 1.0 was released by Sun Microsystems in 1995.
It made the promise of "Write Once, Run Anywhere", with free runtimes on
popular platforms.
In 2006-2007 Sun released java as open source and and plateform independent
software.
Over time new enhanced versions of Java have been released.
The current version of Java is Java 1.7 which is also known as Java 7.

JVM (JAVA VIRTUAL MACHINE) & JRE( JAVA RUN TIME ENVIRONMENT)

The Java virtual machine (JVM) is a software implementation of a computer that


executes programs like a real machine.
The Java virtual machine is written specifically for a specific operating system,
e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into byte code.
The Java virtual machine interprets this byte code and executes the Java program.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries
and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java
programs.
The JDK consists therefore of a Java compiler, the Java virtual machine, and the
Java class libraries.

FEATURES OF JAVA / CHARACTERISTICS OF JAVA


The characteristics and features of java are as follows.
1) Simple

Java is a simple language because of its various features, Java Doesnt Support
Pointers, Operator Overloading etc.
It doesnt require unreferenced object because java support automatic garbage
collection.
Java provides bug free system due to the strong memory management.

2) Object-Oriented

Object-Oriented Programming Language (OOPs) is the methodology which


provides software development and maintenance by using object state, behavior,
and properties.
Object Oriented Programming Language must have the following characteristics.
o Encapsulation

1|Page

SS

Govt.

Arts

College

o Polymorphism
o Inheritance
o Abstraction
As the languages like Objective C, C++ fulfills the above four characteristics yet
they are not fully object oriented languages because they are structured as well
as object oriented languages
In java everything is an Object.
Java can be easily extended since it is based on the Object model.

3) Secure

Java is Secure Language because of its many features it enables to develop virusfree, tamper-free systems.
Authentication techniques are based on public-key encryption.
Java does not support pointer explicitly for the memory.
All Program Run under the sandbox.

4) Robust

Java was created as a strongly typed language.


Data type issues and problems are resolved at compile-time, and implicit casts of
a variable from one type to another are not allowed.
Memory management has been simplified java in two ways.
o First Java does not support direct pointer manipulation or arithmetic. This
make it possible for a java program to overwrite memory or corrupt data.
o Second , Java uses runtime garbage collection instead of instead of freeing
of memory. In languages like c++, it Is necessary to delete or free memory
once the program has finished with it.

5) Platform-independent

Java Language is platform-independent due to its hardware and software


environment.
Java code can be run on multiple platforms e.g. windows, Linux, sun Solaris,
Mac/Os etc.
Java code is compiled by the compiler and converted into byte code.
This byte code is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

6) Architecture neutral

It is not easy to write an application that can be used on Windows , UNIX and a
Macintosh.
Its getting more complicated with the move of windows to non Intel CPU
architectures.
Java takes a different approach. Because the Java compiler creates byte code
instructions that are subsequently interpreted by the java interpreter, architecture
neutrality is achieved in the implementation of the java interpreter for each new
architecture.

7) Portable

Java code is portable.


It was an important design goal of Java that it be portable so that as new
architectures are developed, the java environment could be ported to them.
In java, all primitive types(integers, longs, floats, doubles, and so on) are of
defined sizes, regardless of the machine or operating system on which the
program is run.

2|Page

SS

Govt.

Arts

College

This is in direct contrast to languages like C and C++ that leave the sized of
primitive types up to the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.

8) Dynamic

Because it is interpreted , Java is an extremely dynamic language, At runtime, the


java environment can extends itself by linking in classes that may be located on
remote servers on a network(for example, the internet)
At runtime, the java interpreter performs name resolution while linking in the
necessary classes. The Java interpreter is also responsible for determining the
placement of object in memory.
These two features of the Java interpreter solve the problem of changing the
definition of a class used by other classes.

9) Interpreted

We all know that Java is an interpreted language as well. With an interpreted


language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into
computations. Thus, Java as an interpreted language depends on an interpreter
program.
The versatility of being platform independent makes Java to outshine from other
languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging
quality. Due to this any error occurring in the program gets traced. This is how it is
different to work with Java.

10) High performance

For all but the simplest or most infrequently used applications, performance is
always a consideration for most applications, including graphics-intensive ones
such as are commonly found on the WWW, the performance of java is more than
adequate.

11) Multithreaded

Writing a computer program that only does a single thing at a time is an artificial
constraint that weve lived with in most programming languages.
With java, we no longer have to live with this limitation. Support for multiple,
synchronized threads is built directly into the Java language and runtime
environment.
Synchronized threads are extremely useful in creating distributed, network-aware
applications. Such as application may be communicating with a remote server in
one thread while interacting with a user in a different thread.

12) Distributed

Java facilitates the building of distributed application by a collection of classes for


use in networked applications.
By using javas URL class, an application can easily access a remote server.
Classes also are provided for establishing socket-level connections.

CONCEPT OF OBJECT ORIENTED PROGRAMMING


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
3|Page

SS

Govt.

Arts

College

objects. It simplifies the software development and maintenance by providing some


concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Object
Any entity that has state and behavior is known as an object.

For example: chair, pen, table, keyboard, bike etc.

It can be physical and logical.

Class
Collection of objects is called class.

It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance.

It provides code reusability.

It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism.

For example: to convenience the customer differently, to draw something e.g.


shape or rectangle etc.

In java, we use method overloading and method overriding to achieve


polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks
woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction.

4|Page

SS

Govt.

Arts

College

For example: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known
as encapsulation.

For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation.

Java bean is the fully encapsulated class because all the data members are
private here.

JAVA TOKENS
Java tokens are the smallest individual units that form part of a Java Program. Different
types of java tokens are:

Reserved Keywords Reserved keywords are java tokens with predefined


meaning. Java has 60 reserved keywords.

Identifiers Identifiers are java tokens designed and decided by the java
programmer. Examples for java tokens namely identifiers are: name for the class,
name for members of the class, and temporary variables in class methods.

Literals Literals are java tokens containing set of characters. Literals are used
to represent a constant that has to be stored in a variable.

Operators Operators are java tokens containing a special symbol and


predefined meaning in Java. Operators can be used with one or more operands to
achieve a result.

Separators Separators are java tokens that are used to divide as well as
arrange codes in group.

VARIABLE

A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of
the variable's memory.
The range of values that can be stored within that memory and the set of
operations that can be applied to the variable.

Syntax:
data type variable [ = value][, variable [= value] ...] ;
Example:
int a, b, c;

5|Page

SS

Govt.

Arts

College

int a = 10, b = 10;


byte B = 22
DATA TYPES
Java primitive data types are the basic data types that are built-in to Java language. A
data type is a classification mechanism whereby it can be identified that what kind of
data is stored inside the variable, and what operations it supports.
Type

Size in Bytes

Range

byte

1 byte

-128 to 127

short

2 bytes

-32,768 to 32,767

int

4 bytes

-2,147,483,648 to 2,147,483, 647

long

8 bytes

-9,223,372,036,854,775,808
to 9,223,372,036,854,775,807

float

4 bytes

approximately 3.40282347E+38F

double

8 bytes

approximately 1.79769313486231570E+308

char

2 byte

0 to 65,536 (unsigned)

boolean

not
defined*

precisely true or false

ARRAYS
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
There are two types of array.
Single Dimensional Array
type var-name[ ];
array-var = new type [size];
eg.
int month_days[];
month_days[1] = 28;
Multidimensional Array
type var-name [size][size]=new type[size][size];
eg.
int twoD[][] = new int[4][5];
JAVA TYPE CASTING

6|Page

SS

Govt.

Arts

College

Assigning a value of one type to a variable of another type is known as Type


Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,

Widening Casting(Implicit)

Narrowing Casting(Explicitly done)

Widening or Automatic type conversion


Automatic Type casting take place when,the two types are compatible the target type is
larger than the source type
Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);

7|Page

SS

Govt.

Arts

College

System.out.println("Float value "+f);


}
}
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need
to perform explicit type casting.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}

JAVA CONTROL STATEMENTS

A programming language uses control statements to cause the flow of execution to


advance and branch based on changes to the state of a program.
Javas program control statements can be put into the following categories:
selection

8|Page

SS

Govt.

Arts

College

iteration
jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).
Jump statements allow your program to execute in a nonlinear fashion.

JAVAS SELECTION STATEMENTS

Java supports two selection statements: if and switch.


These statements allow you to control the flow of your programs execution based
upon conditions known only during run time.
If Statement
The if statement is Javas conditional branch statement. It can be used to route program
execution through
two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block). The condition is any expression that returns a boolean
value. The else clause is optional. The if works like this: If the condition is true, then
statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will
both statements be executed.
For example,
consider the following:
int a, b;
//...
if(a < b) a = 0;
else b = 0;
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the ifelseif ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final else statement
will be executed. The final else acts as a default condition; that is, if all other conditional
tests fail, then the last else statement is performed. If there is no final else and all other
conditions are false, then no action will take place.

9|Page

SS

Govt.

Arts

College

Example
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
switch Statement

The switch statement is Javas multiway branch statement.


It provides an easy way to dispatch execution to different parts of your code
based on the value of an expression.
It provides a better alternative than a large series of if-else-if statements. Here is
the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
The switch statement works like this:
The value of the expression is compared with each of the values in the case
statements.
If a match is found, the code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default
statement is executed.
However, the default statement is optional.
If no case matches and no default is present, then no further action is taken.

10 | P a g e

SS

Govt.

Arts

College

The break statement is used inside the switch to terminate a statement


sequence.
When a break statement is encountered, execution branches to the first line of
code that follows the entire switch statement. This has the effect of jumping
out of the switch.
Example
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
Nested switch Statements
You can use a switch as part of the statement sequence of an outer switch. This is
called a nested switch. Since a switch statement defines its own block, no conflicts
arise between the case constants in the inner switch and those in the outer switch. For
example, the following fragment is perfectly valid:
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
11 | P a g e

SS

Govt.

Arts

College

Here, the case 1: statement in the inner switch does not conflict with the case 1:
statement in the outer switch. The count variable is compared only with the list of cases
at the outer level. If count is 1, then target is compared with the inner list cases.
Important features of the switch statement

The switch differs from the if in that switch can only test for equality, whereas if
can evaluate any type of Boolean expression. That is, the switch looks only for a
match between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in
common.
A switch statement is usually more efficient than a set of nested ifs.

ITERATION STATEMENTS

Javas iteration statements are for, while, and do-while.


These statements create what we commonly call loops.

while Statement
The while loop is Javas most fundamental loop statement. It repeats a statement or
block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed
as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop. The curly braces are
unnecessary if only a single statement is being repeated.
Example
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
do-while Statement
In while statement, if the conditional expression controlling a while loop is initially false,
then the body of the loop will not be executed at all. However, sometimes it is desirable
to execute the body of a loop at least once, even if the conditional expression is false to
begin with. In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning. Java supplies a loop that
does just that: the do-while. The do-while loop always executes its body at least once,
because its conditional expression is at the bottom of the loop.

12 | P a g e

SS

Govt.

Arts

College

do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Javas loops, condition must be a Boolean
expression.
Example
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
for Statement
Loop statements are an important part of nearly any programming language. Java supplies a
powerful assortment of loop constructs. Perhaps the most versatile is the for loop.

The general form of the traditional for statement:


for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows.

When the loop first starts, the initialization portion of the loop is executed.
Generally, this is an expression that sets the value of the loop control variable, which
acts as a counter that controls the loop.
It is important to understand that the initialization expression is executed only once.
Next, condition is evaluated. This must be a Boolean expression.
It usually tests the loop control variable against a target value. If this expression is
true, then the body of the loop is executed.
If it is false, the loop terminates. Next, the iteration portion of the loop is executed.
This is usually an expression that increments or decrements the loop control variable.
The loop then iterates, first evaluating the conditional expression, then executing the
body of the loop, and then executing the iteration expression with each pass.
This process repeats until the controlling expression is false.

Example
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}

13 | P a g e

SS

Govt.

Arts

College

Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
Using break
In Java, the break statement has three uses. First, it terminates a statement sequence in
a switch statement. Second, it can be used to exit a loop. Third, it can be used as a
civilized form of goto.
Example
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
continue Statement
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the
loops end. The continue statement performs such an action. In while and do-while
loops, a continue statement causes control to be transferred directly to the conditional
expression that controls the loop. In a for loop, control goes first to the iteration portion
of the for statement and then to the conditional expression. For all three loops, any
intermediate code is bypassed.
Example
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
14 | P a g e

SS

Govt.

Arts

College

}
}
Return
The last control statement is return. The return statement is used to explicitly return
from a method. At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the return statement
immediately terminates the method in which it is executed.
Example
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

15 | P a g e

SS

Govt.

Arts

College

Vous aimerez peut-être aussi