2. 2
Arvind
Bhave
JAVA-INTRODUCTION
History
Primary aim to develop small comp. language for consumer
devices like Microwave Ovens, remote control, cable TV
switch Boxes etc.
Object-Oriented language developed by Sun Microsystem
(USA) in 1991.
Originally called “Oak” by James Gosling.
Renamed to “Java” in 1995.
4. 4
Arvind
Bhave
JAVA PROGRAM- APPLICATION
Application
Program that runs on your computer under the operating
system of that computer .
Application programs are mostly in the form of
character user interface (like C or C++).
Also in the form of GUI for Windows Environment.
5. 5
Arvind
Bhave
JAVA PROGRAM- APPLET
Tiny Java program
Mainly used for Internet applications.
Run on a web page.
Applets programs are used to make animations, display
images and run the sound also.
React the user input and dynamically changed.
6. 6
Arvind
Bhave
JAVA PROGRAM- SERVLETS
A mini server side program
Similar to applets
It is defined in the Java servlet API
Particularly used for producing dynamic web contents.
8. 8
Arvind
Bhave
JAVA FEATURES
Simple :-
If you know C++, then moving to Java is easy
Java inherits the C/C++ syntax.
Need to learn OOP concept.
Need to have some programming experience
Designed for professional programmer.
9. 9
Arvind
Bhave
JAVA FEATURES
Secure:-
Risk of viral infection while downloading
Some malicious program also exists.
These programs gather private information like credit card
no., passwords
For these, Java provides a “firewall” between networked
application and your computer
Can safely download Java Applet.
No use of pointers.
10. 10
Arvind
Bhave
JAVA FEATURES
Portable :-
Ensures portability in two ways
First- Java compiler generates Byte code that can be
implemented on any machine.
Second- Size of primitive data types are machine
independent.
11. 11
Arvind
Bhave
JAVA FEATURES
Object Oriented:-
All program code & data resides within objects and classes.
Java contains set of classes arranged in packages, that can be
use in program by inheritance.
Truly object oriented.
12. 12
Arvind
Bhave
JAVA FEATURES
Robust:-
Java is strictly typed language
It checks code compile time & run time (checking for
data types)
Consider two main reasons for program failure
Memory management and mishandled exceptional
conditions (i.e. run time errors)
Java virtually eliminates memory management by
managing allocations & de allocations of memory.
Java provides Object oriented exceptional handling.
Therefore Java is Robust.
13. 13
Arvind
Bhave
JAVA FEATURES
MultiThreaded :-
Handling multiple tasks simultaneously.
You can write programs that do many things
simultaneously
Java supports multithreaded programming.
14. 14
Arvind
Bhave
JAVA FEATURES
Architectural Neutral:-
Changes and up gradation in O.S., processors & system
resources will not force any changes in java programs.
It is “write once; run anywhere, anytime, forever “. (this
is goal)
Means platform Independent.
15. 15
Arvind
Bhave
JAVA FEATURES
Compiled & interpreted :-
Java compiler translates source code into bytecode
instructions.
Bytecodes are not machine instructions.
This bytecode is interpreted on any system having JVM.
16. 16
Arvind
Bhave
JAVA FEATURES
High performance :-
Java designed to perform well on a very low power
CPUs.
Java’s bytecode was carefully designed so that it would
be easy to translate directly into native machine code.
17. 17
Arvind
Bhave
JAVA FEATURES
Distributed:-
Designed for distributed environment of the internet
because it handles TCP/IP protocols.
Java application can open & access remote objects on
internet (like local system).
18. 18
Arvind
Bhave
JAVA FEATURES
Dynamic:-
Java program carry with them run-time type information.
Due to this, it is possible to link the code dynamically in
a safe manner.
19. 19
Arvind
Bhave
SOME OOP CONCEPT
Data Abstraction:-
Procedure of representing essential things without
including details.
Example 1- a computer is made of several part like CPU,
keyboard, mouse etc. but we can think it as a single unit.
Example 2- a car is a single object but it has several
parts.
Classes use theory of abstraction.
20. 20
Arvind
Bhave
SOME OOP CONCEPT
Encapsulation:-
The packing of data & functions into a single unit or
component.
class is an example of encapsulation.
A class contains data & member functions (methods)
common to all objects.
Each member is private or public.
Any non member function can not access the data of the
class.
21. 21
Arvind
Bhave
SOME OOP CONCEPT
Inheritance:-
Is the method by which object of one class get the
properties of another class.
Provides the thought of reusability.
We can add the new properties to the existing class
without changing it.
This can be achieved by deriving new class form existing
one.
22. 22
Arvind
Bhave
SOME OOP CONCEPT
Inheritance example:-
RED YELLOW BLUE
ORANGE GREEN VIOLET
YELLOW
ISH
BROWN
REDDIS
H
BROWN
BLUISH
BROWN
23. 23
Arvind
Bhave
SOME OOP CONCEPT
Polymorphism :- (many forms)
Allows the same function to act differently in different
classes.
Ability to take more than one form.
Ability of giving same name to methods in different
subclasses.
24. 24
Arvind
Bhave
SOME OOP CONCEPT
Polymorphism example –
Line
Display()
Dotted object
Display(dotted)
Single object
Display(Single)
Dash object
Display(dash)
25. 25
Arvind
Bhave
FIRST JAVA PROGRAM
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
26. 26
Arvind
Bhave
COMPILING THE PROGRAM
execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:>javac Example.java
The javac compiler creates a file called Example.class
that contains the bytecode version of the program. The
Java bytecode contains instructions the Java interpreter will
execute.
To actually run the program, you must use the Java
interpreter, called java.
C:>java Example
When the program is run, the following output is displayed:
This is a simple Java program
27. 27
Arvind
Bhave
COMPILING THE PROGRAM
When Java source code is compiled, each individual class
is put into its own output file named after the class and
using the .class extension.
This is why it is a good idea to give your Java source
files the same name as the class they contain—
the name of the source file will match the name of
the .class file. When you execute the Java
interpreter
as just shown, you are actually specifying the name of the
class that you want the interpreter to execute.
It will automatically search for a file by that name that
has the .class extension.
If it finds the file, it will execute the code contained
in the specified class.
28. 28
Arvind
Bhave
IF STATEMENT
if statement works much like the IF statement in any other language.
simplest form is
if(condition)
statement;
Here, condition is a Boolean expression.
If condition is true, then the statement is executed.
If condition is false, then the statement is bypassed.
Here is an example:
if(num < 100)
println("num is less than 100");
In this case, if num contains a value that is less than 100, the conditional
expression is true, and println( ) will execute. If num contains a value
greater than or equal to 100, then the println( ) method is bypassed.
29. 29
Arvind
Bhave
IF STATEMENT
. Here are a few Operator
< Less than
> Greater than
== Equal to
Notice that the test for equality is the double equal sign.
a program that illustrates the if statement:
/* Demonstrate the if Call this file "IfSample.java". */
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10; y = 20;
if(x < y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
30. 30
Arvind
Bhave
IF STATEMENT
The output generated by this program is shown
x is less than y
x now equal to y
x now greater than y
Notice one other thing in this program. The line
int x, y;
declares two variables, x and y, by use of a comma-
separated list.
31. 31
Arvind
Bhave
THE FOR LOOP
The simplest form of the for loop is shown here:
for(initialization; condition; iteration)
statement;
In common form, the initialization portion of the loop sets a loop
control
variable to an initial value.
The condition is a Boolean expression that tests the loop control
variable.
If the outcome of that test is true, the for loop continues to
iterate.
If it is false, the loop terminates.
The iteration expression determines how the loop control variable
is changed each time the loop iterates.
32. 32
Arvind
Bhave
THE FOR LOOP
Here is a short program that illustrates the for loop:
/*Demonstrate the for loop. Call this file "ForTest.java". */
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<5; x = x+1)
System.out.println("This is x: " + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
33. 33
Arvind
Bhave
THE FOR LOOP
In this example, x is the loop control variable. It is
initialized to zero in the initialization
portion of the for.
At the start of each iteration (including the first one),
the conditional test x < 10 is performed. If the
outcome of this test is true, the println( ) statement is
executed, and then the iteration portion of the loop is
executed. This process continues until the conditional
test is false.
The increment operator increases its operand by one.
34. 34
Arvind
Bhave
USING BLOCKS OF CODE
Java allows two or more statements to be grouped into blocks of code, also called
code blocks.
This is done by enclosing the statements between opening and closing curly braces.
Once a block of code has been created, it becomes a logical unit that can be used
any place that a single statement can.
For example, a block can be a target for Java’s if and for statements.
Consider this if statement:
if(x < y) { // begin a block
x = y;
y = 0;
} // end of block
Here, if x is less than y, then both statements inside the block will be executed.
Thus, the two statements inside the block form a logical unit, and one statement
cannot execute without the other also executing.
The key point here is that whenever you need to logically link two or more
statements, you do so by creating a block.
35. 35
Arvind
Bhave
USING BLOCKS OF CODE
Let’s look at another example. The following program uses a block of code as the
target of a for loop.
/* Demonstrate a block of code. Call this file "BlockTest.java“ */
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 20;
// the target of this loop is a block
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
}
36. 36
Arvind
Bhave
USING BLOCKS OF CODE
The output generated by this program is shown here:
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement.
Thus, each time the loop iterates, the three statements inside the block will be executed.
37. 37
Arvind
Bhave
DATA TYPES
Java is strongly Typed Language
First, every variable has a type, every expression has a
type, and every type is strictly defined.
Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for
type compatibility.
The Java compiler checks all expressions and parameters
to ensure that the types are compatible. Any type
mismatches are errors that must be corrected before
the compiler will finish compiling the class.
For example, in C/C++ you can assign a floating-
point value to an integer. In Java, you cannot.
38. 38
Arvind
Bhave
DATA TYPES
Data types can be put into 4 groups.
Integers : This group includes byte, short, int,
and long, which are for wholevalued signed
numbers.
Floating point : includes float and double,
which represent numbers with fractional
precision.
Characters : includes char, represents symbols
in a character set, like letters and numbers.
Boolean : includes boolean, which is a special
type for representing true/false values.
39. 39
Arvind
Bhave
DATA TYPES (INTEGERS)
byte, short, int, and long All of these are
signed, positive and negative values. Java does
not support unsigned, positive-only integers.
Name Width Range
byte 8 –128 to 127
short 16 –32,768 to
32,767
int 32 –2,147,483,648
to 2,147,483,647
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
40. 40
Arvind
Bhave
DATA TYPES
Long
The range of a long is quite large. This makes it useful when big, whole numbers are
needed. For example, here is a program that computes the number of miles that light will
travel in a specified number of days.
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
41. 41
Arvind
Bhave
DATA TYPES
Floating-Point Types
For example, calculations such as square root, or
transcendentals such as sine and cosine, result in a value
whose precision requires a floating-point type.
Name Width in Bits Approximate
Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
42. 42
Arvind
Bhave
DATA TYPES
float
The type float specifies a single-precision
value that uses 32 bits of storage
Double
uses 64 bits to store a value. Double precision
is actually faster than single precision. All
transcendental math functions, such as sin( ),
cos( ), and sqrt( ), return double values.
When you need to maintain accuracy over
many iterative calculations, or are manipulating
large-valued numbers, double is the best
choice
43. 43
Arvind
Bhave
DATA TYPES
Here is a short program that uses double variables
to compute the area of a circle:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
44. 44
Arvind
Bhave
DATA TYPES
Char
Java uses Unicode to represent characters.
Unicode defines a fully international character set
that can represent all of the characters found in
all human languages. It is a unification of dozens
of character sets, such as Latin, Greek, Arabic,
Cyrillic, Hebrew, Katakana, Hangul, and many
more.
Thus, in Java char is a 16-bit type. The range
of a char is 0 to 65,536. There are no
negative chars.
45. 45
Arvind
Bhave
DATA TYPES
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
46. 46
Arvind
Bhave
DATA TYPES
Booleans
boolean, for logical values. It can have only one
of two possible values, true or false. This is the
type returned by all relational operators, such as
a < b.
boolean is also the type required by the
conditional expressions that govern the control
statements such as if and for.
47. 47
Arvind
Bhave
DATA TYPES
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
48. 48
Arvind
Bhave
VARIABLES
The variable is the basic unit of storage
A variable is defined by the combination of an
identifier, a type, and an optional initializer.
All variables have a scope, which defines their
visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can
be used.
The basic form of a variable declaration
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a
class or interface
The identifier is the name of the variable
49. 49
Arvind
Bhave
VARIABLES
int a, b, c; // declares three ints, a, b, and
c.
int d = 3, e, f = 5; // declares three more ints,
initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
50. 50
Arvind
Bhave
DYNAMIC INITIALIZATION
Java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.
For example, here is a short program that computes the length of
the hypotenuse of a right triangle given the lengths of its two
opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b,and c—are declared. The first
two, a and b, are initialized by constants. However, c is
initialized dynamically to the length of the hypotenuse
(using the Pythagorean theorem).
51. 51
Arvind
Bhave
THE SCOPE AND LIFETIME OF
VARIABLES
Java allows variables to be declared within any block
A block is begun with an opening curly brace and ended by a closing curly brace.
A block defines a scope. Thus, each time you start a new block, you are creating a
new scope.
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
52. 52
Arvind
Bhave
LIFETIME OF A VARIABLE.
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
53. 53
Arvind
Bhave
TYPE CONVERSION AND CASTING
If the two types are compatible, then Java will
perform the conversion automatically. For
example, it is always possible to assign an int
value to a long variable. However, not all
types are compatible, and thus, not all type
conversions are implicitly allowed.
For instance, there is no conversion defined from
double to byte. Fortunately, it is still
possible to obtain a conversion between
incompatible types.
To do so, you must use a cast, which performs an
explicit conversion between incompatible types.
54. 54
Arvind
Bhave
JAVA’S AUTOMATIC CONVERSIONS
When one type of data is assigned to another type
of variable, an automatic type conversion will take
place if the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the source
type.
When these two conditions are met, a widening
conversion takes place.
For example,
the int type is always large enough to hold
all valid byte values, so no explicit cast
statement is required.
55. 55
Arvind
Bhave
CASTING INCOMPATIBLE TYPES
Although the automatic type conversions are
helpful, they will not fulfill all needs.
For example, what if you want to assign an int
value to a byte variable?
This conversion will not be performed
automatically, because a byte is smaller than
an int.
This kind of conversion is sometimes called a
narrowing conversion, since you are explicitly
making the value narrower so that it will fit into
the target type.
56. 56
Arvind
Bhave
CASTING INCOMPATIBLE TYPES
To create a conversion between two incompatible
types, you must use a cast. A cast is simply an
explicit type conversion.
It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert
the specified value to.
For example, the following fragment casts an int to
a byte.
If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder
of an integer division by the) byte’s range
57. 57
Arvind
Bhave
CASTING INCOMPATIBLE TYPES
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
As you know, integers do not have fractional components.
Thus, when a floating-point value is assigned to an integer
type, the fractional component is lost.
For example, if the value 1.23 is assigned to an integer, the
resulting value will simply be 1. The 0.23 will have been
truncated.
Of course, if the size of the whole number component is too
large to fit into the target integer type, then that value will be
reduced modulo the target type’s range.
58. 58
Arvind
Bhave
CASTING INCOMPATIBLE TYPES
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
59. 59
Arvind
Bhave
CASTING INCOMPATIBLE TYPES
Output
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
When the value 257 is cast into a byte variable, the result is
the remainder of the division of 257 by 256 (the range of a
byte), which is 1 in this case.
When the d is converted to an int, its fractional
component is lost.
When d is converted to a byte, its fractional component is
lost, and the value is reduced modulo 256, which in this case
is 67.
60. 60
Arvind
Bhave
AUTOMATIC TYPE PROMOTION IN
EXPRESSIONS
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the
range of either of its byte operands. To handle this
kind of problem, Java automatically promotes each
byte or short operand to int when evaluating an
expression. This means that the sub expression a * b is
performed using integers—not bytes.
Thus, 2,000, the result of the intermediate expression, 50 *
40, is legal even though a and b are both specified as
type byte.
61. 61
Arvind
Bhave
AUTOMATIC TYPE PROMOTION IN
EXPRESSIONS
As useful as the automatic promotions are, they
can cause confusing compile-time errors.
For example, this seemingly correct code causes a
problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
62. 62
Arvind
Bhave
AUTOMATIC TYPE PROMOTION IN
EXPRESSIONS
The code is attempting to store 50 * 2, a perfectly valid
byte value, back into a byte variable.
However, because the operands were automatically
promoted to int when the expression was evaluated,
the result has also been promoted to int. Thus, the
result of the expression is now of type int, which
cannot be assigned to a byte without the use of a
cast. This is true even if, as in this particular case, the
value being assigned would still fit in the target type.
In cases where you understand the consequences of
overflow, you should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
63. 63
Arvind
Bhave
THE TYPE PROMOTION RULES
Java defines several type promotion rules that
apply to expressions. They are as follows.
First, all byte and short values are promoted
to int, as just described. Then, if one
operand is a long, the whole expression is
promoted to long.
If one operand is a float, the entire
expression is promoted to float.
If any of the operands is double, the result is
double.
64. 64
Arvind
Bhave
THE TYPE PROMOTION RULES
The following program demonstrates how each value in the expression
gets promoted to match the second argument to each binary operator:
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
65. 65
Arvind
Bhave
Let’s look closely at the type promotions that occur in this line
from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and
the result of the sub expression is float.
Next, in the sub expression i / c, c is promoted to int, and
the result is of type int.
Then, in d * s, the value of s is promoted to double, and
the type of the subexpression is double.
Finally, these three intermediate values, float, int, and
double, are considered.
The outcome of float plus an int is a float. Then the
resultant float minus the last double is promoted to
double, which is the type for the final result of the
expression.
66. 66
Arvind
Bhave
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
67. 67
Arvind
Bhave
ONE-DIMENSIONAL ARRAYS
A one-dimensional array is, essentially, a list of like-typed
variables.. The general form of a one dimensional array
declaration is
type var-name[ ];
Here, type declares the base type of the array. The base
type determines the data type of each element that
comprises the array.
For example, the following declares an array
named month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that
month_days is an array variable, no array actually
exists. In fact, the value of month_days is set to null,
which represents an array with no value.
68. 68
Arvind
Bhave
ONE-DIMENSIONAL ARRAYS
To link month_days with an actual, physical
array of integers, you must allocate one using
new and assign it to month_days. new is a
special operator that allocates memory.
The general form of new as it applies to one-
dimensional arrays appears as follows:
array-var = new type[size];
Here, type specifies the type of data being
allocated, size specifies the number of elements in
the array, and array-var is the array variable
that is linked to the array.
69. 69
Arvind
Bhave
ONE-DIMENSIONAL ARRAYS
This example allocates a 12-element array of
integers and links them to month_days.
month_days = new int[12];
After this statement executes, month_days will
refer to an array of 12 integers. Further, all
elements in the array will be initialized to zero.
70. 70
Arvind
Bhave
ONE-DIMENSIONAL ARRAYS
Here is one more example that uses a one-dimensional
array. It finds the average of a set of numbers.
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
71. 71
Arvind
Bhave
MULTIDIMENSIONAL ARRAYS
In Java, multidimensional arrays are actually
arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays.
For example, the following declares a two-
dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to
twoD. Internally this matrix is implemented
as an array of arrays of int.
72. 72
Arvind
Bhave
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
74. 74
Arvind
Bhave
2 D ARRAY
It is possible to initialize multidimensional arrays.
Enclose each dimension’s initializer within its own
set of curly braces.
Initialization of 2 D Array
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
0*0=column*row
75. 75
Arvind
Bhave
ALTERNATIVE ARRAY
DECLARATION SYNTAX
There is a second form that may be used to declare
an array:
type[ ] var-name;
Here, the square brackets follow the type specifier,
and not the name of the array variable. For ex, the
following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char ch1[][] = new char[3][4];
char[][] ch2 = new char[3][4];
76. 76
Arvind
Bhave
STRING TYPE
Java’s string type, called String, is not a simple
type. Nor is it simply an array of characters (as
are strings in C/C++).
Rather, String defines an object, and a full
description of it requires an understanding
of several object-related features.
The String type is used to declare string
variables. You can also declare arrays of
strings.
A quoted string constant can be assigned to a
String variable.
77. 77
Arvind
Bhave
A variable of type String can be assigned to
another variable of type String.
You can use an object of type String as an
argument to println( ).
For example, consider the following
fragment:
String str = "this is a test";
System.out.println(str);
Here, str is an object of type String. It is
assigned the string “this is a test”. This
string is displayed by the println( ) statement.
78. 78
Arvind
Bhave
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:
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
– – Decrement
79. 79
Arvind
Bhave
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:
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The outcome of these operations is a boolean
value
80. 80
Arvind
Bhave
BOOLEAN LOGICAL OPERATORS
The Boolean logical operators shown here operate only on boolean
operands. All of the binary logical operators combine two
boolean values to form a resultant boolean value.
& 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
81. 81
Arvind
Bhave
A B A | B A & B A ^ B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False
82. 82
Arvind
Bhave
CONTROL STATEMENTS
If
If-else
Nested ifs
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
84. 84
Arvind
Bhave
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.
85. 85
Arvind
Bhave
// 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 + ".");
}
}
87. 87
Arvind
Bhave
A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}