Sie sind auf Seite 1von 66

INTRODUCTION TO JAVA

PROGRAMMING

5/12/16

BY: Raju Pal

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

public class HelloWorldApp


{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
}
}

Java is CASE SENSITIVE!


5/12/16

BY: Raju Pal

Getting Started
(2) Compile the program:
compile HelloWorldApp.java by using the following
command:
javac HelloWorldApp.java

it generates a file named HelloWorldApp.class

5/12/16

BY: Raju Pal

Getting Started
(3) Run the program:
run the code through:
java HelloWorldApp

Note that the command is java, not javac, and you


refer to
HelloWorldApp, not HelloWorldApp.java or
HelloWorldApp.class

5/12/16

BY: Raju Pal

Explaining first program


public class HelloWorldApp
{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
}
}

5/12/16

BY: Raju Pal

public: so that JVM can access


the main method
static: so that JVM can call
main method w/o creating
object.
void : no return type
main: starting point
String args[] : command line
argumentsto the main function
must be given string array and
array will be called args.

Explaining first program


public class HelloWorldApp
{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
Is a method of
}
printstream class
Object of printStream
}
Inbuilt class in Java.lang
package

5/12/16

class

BY: Raju Pal

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

5/12/16

BY: Raju Pal

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:

Integer literal : 100


Floating-point literal : 98.6
Character literal : s
String literal : sample

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/12/16

BY: Raju Pal

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/12/16

BY: Raju Pal

Data Types

1.
2.
3.
4.

Data type specify the size and type of values


Java defines eight simple types of data. These can be put into
four groups:
Integers
Floating-point numbers
Characters
Boolean

Range: -2x-1 to 2x-1-1 where x is number of bits.


Leftmost bit is reserved for the sign.
5/12/16

BY: Raju Pal

10

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/12/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

BY: Raju Pal

11

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/12/16

BY: Raju Pal

12

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

escape sequences) new line \n,

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/12/16

BY: Raju Pal

13

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/12/16

BY: Raju Pal

14

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/12/16

BY: Raju Pal

15

Constants

5/12/16

BY: Raju Pal

16

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/12/16

BY: Raju Pal

17

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/12/16

BY: Raju Pal

//

18

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/12/16

BY: Raju Pal

19

Array

Array is a list of finite number n of homogeneous data elements


such that:

The elements of the array are referenced respectively by


an index set of n consecutive numbers.

The element of the array are stored respectively in


successive memory location.

The number n of elements is called the length or size.

5/12/16

BY: Raju Pal

20

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

Declaring and defining in the same statement:

int[] students=new int[10];


double myList[] = new double[10];

5/12/16

BY: Raju Pal

21

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/12/16

BY: Raju Pal

22

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.

Creates and initializes the array of integers of length 7.

4.

In this case it is not necessary to use the new operator.

5/12/16

BY: Raju Pal

stude
nts
0
55
1

69

70

30

80

90

45

23

Array: Default Values


When an array is created, its elements are assigned the default
value of
0 for the numeric primitive data types,
'\u0000' for char types, and
false for boolean types
Once an array is created, its size is fixed. It cannot be changed.
You can find its size using
arrayRefVar.length
5/12/16

BY: Raju Pal

24

Processing Array Elements using loop


Often a for( ) loop is used to process each of the elements of the array in
turn.

The loop control variable, i, is used as the index to access array


components

5/12/16

BY: Raju Pal

25

Array as Parameters
Methods can accept arrays via parameters
Use square brackets [ ] in the parameter declaration:

5/12/16

BY: Raju Pal

26

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/12/16

BY: Raju Pal

27

Two Dimensional Arrays


Two dimensional arrays allows us to store data that are recorded in
table.
int[][] student=new int[4][4];
4 arrays each having 4 elements
First index: specifies array (row)
Second Index: specifies element in that array (column)

5/12/16

10

20

85

45

56

58

25

58

45

85

65

78

65

14

28

56
BY: Raju Pal

28

Accessing 2D Array Elements


Sum the Elements
Here is code that sums all the numbers in table.
The outer loop iterates four times and moves down the
rows.
Each time through the outer loop, the inner loop iterates
five times and moves across a different row.

5/12/16

BY: Raju Pal

29

Declaration and Instantiation of 2D


Array

Declaring and instantiating two-dimensional arrays are


accomplished by extending the processes used for onedimensional arrays:
Declaration:
int myArray [][];
Creation or Instantiation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
- Single Value;
myArray[0][0] = 10;
- Multiple values:
int table[2][3] = {{10, 15, 30}, {14, 30, 33}};
int table[][] = {{10, 15, 30}, {14, 30, 33}};
5/12/16

BY: Raju Pal

30

2D Array as Array of Arrays


int table [][] = new int[4][5];

The variable table references an array of four elements.


Each of these elements in turn references an array of five integers.

5/12/16

BY: Raju Pal

31

Variable Size Arrays


Java treats multidimensional arrays as arrays of arrays. It
is possible to declare a 2D arrays as follows:
int a[][] = new int [3][];
a[0]= new int [2];
a[1]= new int [3];

[0]

[0
]

[1]

[0] [1] [2]

[2]

[0] [1] [2] [3]

[1
]

a[2]= new int [4];

5/12/16

BY: Raju Pal

32

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/12/16

BY: Raju Pal

33

Varying length in Multidimensional


Arrays
Same features apply to multi-dimensional arrays as those of 2
dimensional arrays
long beans=new long[3][][]; //3 countries
beans[0]=new long[4][]; //First country has 4 farms
beans[0][4]=new long[10];//Each farm in first country has 10
fields

5/12/16

BY: Raju Pal

34

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/12/16

BY: Raju Pal

35

Classes and Objects


Class Name: Circle

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

An object has both a state and behavior. The state


defines the object, and the behavior defines what
the object does.
5/12/16

BY: Raju Pal

36

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/12/16

BY: Raju Pal

//A Simple Class


class Box
{
double width
double height
double depth
}
Data is encapsulated in a class
by placing data fields inside
the body of the class definition.

37

Declaring (creating) Objects


Declaring Object Reference Variables
ClassName objectReference;
Example:

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/12/16

BY: Raju Pal

38

Accessing Objects
Referencing the objects data:
objectRefVar.data
e.g., myBox.width
myBox.height
myBox.depth

Invoking the objects method:


objectRefVar.methodName(arguments)
e.g., myBox.getArea()
5/12/16

BY: Raju Pal

39

Classes and Objects


Trace Code
Declare myBox

Box myBox = new Box();

myBox

null

Box yourBox = new Box();


yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;

5/12/16

BY: Raju Pal

40

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;

null

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

Create a Box

5/12/16

BY: Raju Pal

41

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;
yourBox.height = 10;

Assign object
reference to myBox

Box
Width
Height
Depth

yourBox.depth= 50;

5/12/16

reference value

BY: Raju Pal

42

Classes and Objects


Trace Code, cont.
Box myBox = new Box();
myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

yourBox

null

Declare yourBox

5/12/16

BY: Raju Pal

43

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

null

yourBox
Create a new
Box object
5/12/16

BY: Raju Pal

Box
Width
Height
Depth

44

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

yourBox
Assign object
reference to yourBox
5/12/16

BY: Raju Pal

reference value

Box
Width
Height
Depth

45

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();

reference value

yourBox.width = 100;

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;

reference value

yourBox
Change variables in
yourBox

5/12/16

BY: Raju Pal

Box
Width =100
Height=10
Depth =50

46

Classes and Objects


Trace Code, cont.

Box myBox = new Box();


myBox

Box yourBox = new Box();


yourBox.width = 100;

reference value

Box

yourBox.height = 10;

Width
Height
Depth

yourBox.depth= 50;
myBox = yourBox;

yourBox

reference value

Box
Assigning Object
Reference Variables
5/12/16

BY: Raju Pal

Width =100
Height=10
Depth =50

47

Garbage Collection

When no references to an object exist, that object is assumed too


be no longer needed, and the memory occupied by the object
can be reclaimed.
As shown in the previous figure, after the assignment statement
myBox = yourBox, myBox points to the same object referenced
by yourBox. The object previously referenced by myBox is no
longer referenced. This object is known as garbage. Garbage is
automatically collected by JVM.
If you know that an object is no longer needed, you can
explicitly assign null to a reference variable for the object. The
JVM will automatically collect the space if the object is not
referenced by any variable.

5/12/16

BY: Raju Pal

48

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/12/16

BY: Raju Pal

49

Returning a Value
double volume()
{
return width*height*depth;
}

The type of data returned by a method must be compatible


with the return type specified by the method.
The variable receiving the value returned by a method must
also be compatible with the return type specified for the
method.
5/12/16

BY: Raju Pal

50

Parameterized Methods
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

Parameters: variable defined by a method that receives a value


when the method is called
Arguments: value that is passed to a method when it is invoked.
5/12/16

BY: Raju Pal

51

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/12/16

BY: Raju Pal

Constructors are a special


kind of methods that are
invoked to construct
objects.
A Constructor initializes
an object immediately
upon creation.
Automatic initialization.

52

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/12/16

BY: Raju Pal

53

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/12/16

BY: Raju Pal

54

Overloading Methods example


Class calculator
{
int add(int op1, int op2)
{
return op1+op2;
}
int add(int op1, int op2, op3)
{
return op1+op2+op3;
}
}
5/12/16

BY: Raju Pal

55

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/12/16

BY: Raju Pal

56

Using Objects as Parameters


An object of a class can be passed as parameter to both methods and
constructors of a class.
/*construct a new object so that it is initially the same
as some existing object.
Define a new constructor Box that takes an object of its
class as a parameter.
*/
Box(Box ob){
Width = ob.Width;
Height = ob.Height;
Depth = ob.Depth;
}
Box myBox = new Box(10,20,15);
Box yourBox = new Box(myBox);
5/12/16

BY: Raju Pal

57

Using Objects as Parameters cont


//objects may be passed to methods
class Test{
int a,b;
Test(int i, int j){
a = i;
b = j;
}
//return true if obj is equal to the invoking obbject
boolean equals(Test obj){
if(obj.a == a && obj.b == b) return true;
else return false;
}
}
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1,-1);
ob1.equals(ob2); true
Ob1.equals(ob3); false
5/12/16

BY: Raju Pal

58

Type of Argument Passing


Call-by-value:
When you pass an item of a simple data type to a method.
Method only gets a copy of the data item.
The code in the method cannot affect the original data item at all.
class Test{
void math(int i, int j){
i=i*2;
j=j/2;
}
}
Test ob = new Test();
int a = 15, b = 20;
System.out.println( a and b before call: +a+ +b); 15 20
ob.math(a,b);
Systeem.out.println( a and b after call: +a+ +b); 15 20
5/12/16

BY: Raju Pal

59

Type of Argument Passing cont


Call-by-reference:
When you pass an object to a method.
Java actually passes a reference to the object.
Code in the method can reach the original object.
Any change made to the passed object affect the original object .
class Test{
int a,b;
Test(int i, int j){
a = i;
b = j;
}
void math(Test o){
o.a = o.a*2;
o.b = o.b/2;
}
}
Test ob = new Test(15,20);
Systeem.out.println( a and b before call: +a+ +b); 15
ob.math(ob);
Systeem.out.println( a and b after call: +a+ +b); 30

5/12/16

BY: Raju Pal

20
10

60

Returning Objects from Methods


A method can return objects just like other data types.
The object created by a method will continue to exist as long as
there is a reference to it.
No need to worry about an object going out-of-scope because
the method in which it was created terminates.

5/12/16

BY: Raju Pal

61

Returning Objects Example


class Test{
int a;
Test (int i){
a = i;
}
Test incrByTen(){
Test temp = new Test(a+10);
return temp;
}
}
Class RetOb{
public static void main(String args[]){
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println(ob1.a: +ob1.a);
System.out.println(ob2.a: +ob2.a);
}
}
ob1.a = 2;
ob2.a = 12;

5/12/16

BY: Raju Pal

62

The static Keyword


Create a member that can be used by itself, without reference to a specific instance or object.
A static member can be accessed before any objects of its class are created.
You can declare both methods and variables to be static.
These variables are, essentially, global variables.
No copy of a static variable is made when objects of its class are declared.
All instances of the class share the same static variables.

5/12/16

BY: Raju Pal

63

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.

If the final keyword is attached to a variable then the variable becomes


constant i.e. its value cannot be changed in the program.
If a method is marked as final then the method cannot be overridden by
any other method.
If a class is marked as final then this class cannot be inherited by any other
class.
Final int a=10;
Final flaot = 10.45f
5/12/16

BY: Raju Pal

64

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/12/16

this
is
a
test
100
-1

BY: Raju Pal

65

Taking Input from User


import java.io.*;
class StringDemo
{
public static void main(String args[]) throws IOException
{
System.out.println("Enter");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String A= br.readLine();
int a=Integer.parseInt(br.readLine());
char c=(char)br.read();
System.out.println(a);
System.out.println(A);
}
}
5/12/16

BY: Raju Pal

66

Das könnte Ihnen auch gefallen