Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
PROGRAMMING
javadoc
HTML Files
javah
Header Files
javac
java
Output
jdb
The SDK is a set of command line tools for developing Java applications:
javac - Java Compiler
java - Java Interpreter (Java VM)
appletviewer - Run applets without a browser
javadoc - automated documentation generator
jdb - Java debugger
Language
(general)
java.lang
GUI
java.awt
java.awt.event
javax.swing
Misc. Utilities
and Collections
java.util
Input/Output
java.io
Networking
java.net
Sockets, Datagrams
Getting Started
(1) Create the source file:
open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a
file (HelloWorldApp.java)
file and class name are case sensitive and must be matched exactly (except the .java part)
Example Code: HelloWorldApp.java
Getting Started
(2) Compile the program:
compile HelloWorldApp.java by using the following command:
javac HelloWorldApp.java
javac
external
Getting Started
(3) Run the program:
run the code through:
java HelloWorldApp
if you see this error, you may need to set the environment
variable CLASSPATH.
class
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java implements several security
Java Is Robust
mechanisms to protect your
Java Is Secure
system against harm caused by
stray programs.
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Because Java is architecture
Java Is Portable
neutral, Java programs are
Java's Performance portable. They can be run on any
platform without being
Java Is Multithreaded recompiled.
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Javas performance Because Java
Java Is Portable
is architecture neutral, Java
Java's Performance programs are portable. They can
be run on any platform without
Java Is Multithreaded being recompiled.
Java Is Dynamic
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java's Performance Multithread programming is smoothly
integrated in Java, whereas in other
Java Is Multithreadedlanguages you have to call
procedures specific to the operating
Java Is Dynamic
system to enable multithreading.
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is ArchitectureNeutral
Java Is Portable
Java was designed to adapt to an
Java's Performance evolving environment. New code can be
loaded on the fly without recompilation.
Java Is MultithreadedThere is no need for developers to create,
and for users to install, major new
Java Is Dynamic
software versions. New features can be
incorporated transparently as needed.
Main Differences
Java vs C++
Java is (an interpreted) write once, run anywhere
language.
- Write once, run everywhere does (nearly) NEVER work with C++, but
does (nearly) ALWAYS work with JAVA.
- Acheived using bytecode concept.
JAVA vs C++
Instead of controlling blocks of
declarations like C++ does, the
access specifiers (public, private, and
protected) are placed on each
definition for each member of a class
Without an explicit access specifier, an element defaults
to "friendly," which means that it is accessible to other
elements in the same package (which is a collection of
classes being friends)
The class, and each method within the class, has an
access specifier to determine whether its visible outside
the file.
JAVA vs C++
Everything must be in a class.
There are no global functions or global data. If you want
the equivalent of globals, make static methods and
static data within a class.
There are no structs or enumerations or unions, only
classes.
Class definitions are roughly the same form in Java as in C++,
but theres no closing semicolon.
JAVA vs C++
All the primitive types in Java have
specified sizes that are machine
independent for portability.
- The char type uses the international 16-bit Unicode
character set, so it can automatically represent most
national characters.
JAVA vs C++
There are Strings in JAVA
Strings are represented by the String-class, they arent
only some renamed pointers
Static quoted strings are automatically converted into
String objects.
There is no independent static character array string like
there is in C and C++.
JAVA vs C++
Although they look similar, arrays have a very
different structure and behavior in Java than they do
in C++.
Theres a read-only length member that tells you how big the array
is, and run-time checking throws an exception if you go out of bounds.
All arrays are created on the heap, and you can assign one array to
another (the array handle is simply copied).
JAVA vs C++
Java has method overloading, but no
operator overloading.
Java has both kinds of comments like C++ does.
Theres no goto in Java.
The one unconditional jump mechanism is the break label or
continue label, which is used to jump out of the middle of
multiply-nested loops.
Lexical Issues
There are many atomic elements of Java. Java programs are a
collection of whitespace, identifiers, comments, literals, operators,
separators and keywords.
Whitespace
Java is a free-form language. It means we do not need to follow any special
indentation rules. In java whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names and variable names.
An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollor-sign characters.
5/7/16
37
Lexical Issues
Literals
A constant value in Java is created by using a literal representation. A literal is
allowed to use anywhere in the program.
Eg:
Comments
// This comment extends to the end of the line.
/*..............the multi-line comments are given with in this comment
............................................................................................................*/
/**....... Documentation comments..........*/
(readable to both human and computer)
5/7/16
38
Lexical Issues
Separators
Separators are used to terminate statements. In java there are few
characters are used as separators . They are, parentheses(), braces{},
brackets[], semicolon;, period., and comma,.
Java Keywords ( 49 )
5/7/16
39
Data Types
1.
2.
3.
4.
40
Data Types
Integers
Name
Width(Size)
Range
byte
8 bits
-128 to 127
short
16 bits
-32768 to 32767
int
32 bits
-2147483648 to 2147483647
long
64 bits
-264-1 to 264-1 -1
Floating-point
5/7/16
Name
Width(Size)
Range
float
32 bits
1.4e-045 to 3.4e+038
double
64 bits
4.9e-324 to 1.8e+038
41
Data Types
Characters
A char variable stores a single character from the Unicode
character set
A character set is an ordered list of characters, and each
character corresponds to a unique number
Unicode is an international character set, containing symbols
and characters from many world languages
The Unicode character set uses 16 bits per character, allowing
for 65,536 unique characters
Character literals are enclosed in single quotes:
A' c' 3' '$' .' '\n
5/7/16
42
Data Types
You might have heard about the ASCII character set
ASCII is older and smaller than Unicode, but is still quite popular
The ASCII characters are a subset of the Unicode character set, including:
uppercase letters A, B, C,
lowercase letters a, b, c,
digits 0, 1, 2,
special symbols *, &, +, ?,
control characters
backspace \b
Characters
Data type used to store character is char.
It requires 16 bits.
Range of a char is 0 to 65536 (no negative char)
5/7/16
43
Data Types
Boolean
Used to test a particular condition
It can take only two values: true and false
Uses only 1 bit of storage
All comparison operators return boolean value
5/7/16
44
Constants
Refer to fixed values that do not change during the execution of a
program.
Integer Constants: sequence of digits
123 037 0X2
Real Constants: numbers containing fractional parts
0.0083 -0.75 435.36
Single character Constants: single character
5 A ;
String Constants: sequence of characters
Hello World ?+;;;;.#
Backslash character (Symbolic) Constants: used in output methods
\n\b\t \ \\ \\
5/7/16
45
Constants
5/7/16
46
Symbolic Constants
Some constants may appear repeatedly in a number of places in
the program.
These constants can be defined as a symbolic name
Make a program:
easily modifiable
More understandable
final type symbolic name = value
ex:
final float PI = 3.14159
5/7/16
47
Variables
An identifier that denotes a storage location used to store a data value.
May take different values at different times during the execution of the
program
Naming Conventions: may consists of alphabets, digits, underscore and dollar
with following conditions
Must not begin with a digit
Uppercase and Lowercase are distinct.
Should not be a keyword
Space is not allowed
Variable declaration and assignment
<type> variable_name;
Variable_name =value; // initializtaion
Variable_name=Math.sqrt(Variable_name* Variable_name);
dynamic initialization
5/7/16
//
48
Scope of Variables
Classified into three kinds:
Instance Variables
Created when the objects are instantiated
Take different values for each object
Class Variables
Global to a class
Belong to the entire set of objects that class creates
Only one memory location is created
Local Variables
Used inside methods or inside program blocks.
Blocks are defined between opening brace { and a closing brace }
Visible to program only from the beginning to the end of the block.
5/7/16
49
Type Casting
5/7/16
50
Type Casting
Type
Casting
Widening
(implicit)
5/7/16
Narrowing
(Explicit)
byte b = 75
int a = 75
int a =b
byte b = (byte) a
BY: Raju Pal
51
Type Casting
5/7/16
52
Type Casting
5/7/16
53
Type Casting
5/7/16
54
Array
5/7/16
55
Creation of Arrays
After declaring arrays, we need to allocate memory for
storage array items.
In Java, this is carried out by using new operator, as
follows:
stude
Arrayname = new type[size];
nts
0
Examples:
1
students = new int[7];
2
3
5/7/16
56
Initialization of Arrays
1. Once arrays are created, they need to be initialised with
some values before access their content. A general form of
initialisation is:
Arrayname [index/subscript] = value;
2. Example:
stude
nts
students[0] = 50;
0
50
students[1] = 40;
1
3. Array index starts with 0 and ends with n-1
2
3
4. Trying to access an array beyond its
4
boundaries will generate an error message.
5
students[7] = 100;
6
5/7/16
57
Explicit initialization
1.
Arrays can also be initialised like standard variables at the time of their
declaration.
Type arrayname[] = {list of values};
2.
Example:
int[] students = {55, 69, 70, 30, 80, 90, 45};
3.
4.
5/7/16
stude
nts
0
55
1
69
70
30
80
90
45
58
59
5/7/16
60
Array as Parameters
Methods can accept arrays via parameters
Use square brackets [ ] in the parameter declaration:
5/7/16
61
Returning Array
A method may return an array as its result
double [] readArray(int n)
{
double result[] = new double[n];
for (i = 0; i < n; i++)
{
result[i] = i;
}
return result;
}
5/7/16
62
5/7/16
10
20
85
45
56
58
25
58
45
85
65
78
65
14
28
56
BY: Raju Pal
63
5/7/16
64
65
5/7/16
66
[0]
[0
]
[1]
[2]
[1
]
5/7/16
67
Multidimensional Arrays
Example: A farmer has 10 farms of beans each in 5
countries, and each farm has 30 fields!
Three-dimensional array:
long[][][] beans=new long[5][10][30];
//beans[country][farm][fields]
5/7/16
68
5/7/16
69
Exercise-1
1.
2.
3.
4.
WAP in Java that create an array and simple print the element of the array.
(Array Traversing).
WAP in Java that implements following three methods:
1. boolean Search( int [] A, int Key): it takes an array A and a Key as input and
returns true if Key is in the array else return false.
2. int Position(int [] A, int Key): it takes an array A and a Key as input and
returns the position of Key in the array.
3. int [] Sort(int [] A): it takes an array A and returns another array. The output
array has same element as in input array but in ascending order.
WAP in Java that takes an two dimensional array as input parameter to a method
and returns one dimensional array. Each element of the output array is the sum
of the element of corresponding row in input array.
WAP in Java to add, multiply, and subtract two Matrices. The decision of
operation should be made based on users choice.
5/7/16
70
Classes
A class is a user-defined data type. Once defined, this
new type can be used to create variables of that type.
These variables are termed as instances of classes,
which are the actual objects.
A class is a template for an object, and an object is an
instance of a class.
5/7/16
71
A class template
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Circle Object 2
Circle Object 3
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is 125
Three objects of
the Circle class
72
Class cont..
//Basic form of a class
class classname
{
type variable1
type variable2
-----------------------------type methodname1(parameter_list)
{
//body of method
}
type methodname2(parameter_list)
{
//body of method
}
--------------}
5/7/16
73
Box myBox;
Creating Objects
objectReference = new ClassName();
Example: myBox = new Box();
The object reference is assigned to the object reference variable.
Declaring/Creating Objects in a Single Step
ClassName objectReference = new ClassName();
Example: Box myBox = new Box();
5/7/16
74
Accessing Objects
Referencing the objects data:
objectRefVar.data
e.g., myBox.width
myBox.height
myBox.depth
75
myBox
null
5/7/16
76
null
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
Create a Box
5/7/16
77
Assign object
reference to myBox
Box
Width
Height
Depth
yourBox.depth= 50;
5/7/16
reference value
78
reference value
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
yourBox
null
Declare yourBox
5/7/16
79
reference value
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
null
yourBox
Create a new
Box object
5/7/16
Box
Width
Height
Depth
80
reference value
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
yourBox
Assign object
reference to yourBox
5/7/16
reference value
Box
Width
Height
Depth
81
reference value
yourBox.width = 100;
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
reference value
yourBox
Change variables in
yourBox
5/7/16
Box
Width =100
Height=10
Depth =50
82
reference value
Box
yourBox.height = 10;
Width
Height
Depth
yourBox.depth= 50;
myBox = yourBox;
yourBox
reference value
Box
Assigning Object
Reference Variables
5/7/16
Width =100
Height=10
Depth =50
83
Garbage Collection
5/7/16
84
85
int i = 1
Object type
Circle c
reference
c: Circle
Created using
new Circle()
5/7/16
radius = 1
86
Before:
After:
c1
c1
c2
c2
5/7/16
Before:
After:
c1: Circle
c2: Circle
radius = 5
radius = 9
87
Introducing Methods
type name(parameter-list)
{
//body of method
return value; (if type is not void)
}
Define the interface to most classes.
Hide specific layout of internal data structures(Abstraction)
Add method to Box class
void volume()
{
System.out.print(Volume is: );;
System.out.println(width*height*depth);
}
5/7/16
88
Returning a Value
double volume()
{
return width*height*depth;
}
89
Parameterized Methods
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
90
Constructors
Box()
{
//default constructor
}
Box()
{
width = 10;
height = 10;
depth = 10;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box myBox = Box();
Box yourBox = Box(20,20,20);
5/7/16
91
Constructors cont
A constructor with no parameters is referred to as a default
constructor.
Constructors must have the same name as the class itself.
Constructors do not have a return typenot even void.
Implicit return type of a class constructor is the class type
itself.
Constructors are invoked using the new operator when
an object is created.
Constructors play the role of initializing objects.
5/7/16
92
93
94
Overloading Methods
Method overloading defines several different versions of a method
all with the same name, but each with a different parameter list.
At the time of method call, java compiler will know which one you
mean by the number and/or types of the parameters.
Overloaded methods must differ in the type and/or number of their
parameters.
Implements polymorphism
May have different return types.
To overload a method, you just define it more than once,
specifying a new parameter list different from every other
5/7/16
95
96
Overloading Constructors
Works like overloading other methods.
Define the constructor a number of times, each time with a different parameter
list.
//when all dimensions specified
Box(double w, double h, double d){
Width = w;
Height = h;
Depth = d;
}
//when cube is created
Box(double l){
Width = Height = Depth = l;
}
Box myBox = new Box(10,20,15);
Box yourBox = new Box(25);
5/7/16
97
98
99
100
5/7/16
20
10
101
5/7/16
102
5/7/16
103
5/7/16
104
105
Public Visibility
Members that are declared as public can be accessed from any
class that can access the class of the member
We expose methods that are part of the interface of the class by
declaring them as public
We do not want to reveal the internal representation of the
objects data. So we usually do not declare its state variables as
public (encapsulation)
5/7/16
106
Private Visibility
A class member that is declared as private, can be accessed only
by code that is within the class of this member.
We hide the internal implementation of the class by declaring its
state variables and auxiliary methods as private.
Data hiding is essential for encapsulation.
5/7/16
107
class Data
{
public int []
a={0,0,0,0,0,0,0};
}
class app
{
public static void main(String
args[])
{
Data d= new Data();
for(int i=0;i<d.a.length;i+
+)
System.out.println(d.a[i]);
}
}
5/7/16
class Data
{public int [] a={1,0,0,0,0,0,0};}
class app
{
void print(Data obj)
{System.out.println(obj.a[0]);
108
class Test {
class AccessTest {
int a; // default access
public int b; // public access public static void main(String args[]) {
private int c; // private accessTest ob = new Test();
// These are OK, a and b may be accessed
// methods to access c
directly
void setc(int i)
ob.a = 10;
{ // set c's value
ob.b = 20;
c = i;
// This is not OK and will cause an error
}
// ob.c = 100; // Error!
int getc() { // get c's value // You must access c through its methods
ob.setc(100); // OK
return c;
System.out.println("a, b, and c: " + ob.a + "
}
"+
}
ob.b + " " + ob.getc());
}
}
5/7/16
109
110
static Methods
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
final Keyword
A variable can be declared as final.
contents of the variable cannot can not be modified.
Must initialize a final variable when it is declared.
Final int a=10;
Final flaot = 10.45f
5/7/16
111
112
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
Output:
a = 42
b = 99
class StaticByName {
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " +
StaticDemo.b);
}
}
5/7/16
113
114
// Demonstrating Strings.
class StringDemo {
public static void main(String args[])
{
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " +
strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
5/7/16
115
5/7/16
116
Using Command-Line
Arguments
// Display all command-line
arguments.
class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: "
+args[i]);
}
} CommandLine this is a test 100 -1
java
args[0]:
args[1]:
args[2]:
args[3]:
args[4]:
args[5]:
5/7/16
this
is
a
test
100
-1
117
118
5/7/16
119