You are on page 1of 36

GIRNE AMERICAN UNIVERSITY

FACULTY OF ENGINEERING
DEPARTMENT OF COMPUTER ENGINEERING

JAVAPROGRAMMING
CHAPTER1 ProgrammingFundamentals
Duration:2Weeks(6Hrs.)
(
)

PreparedBy,
Dr.TamerTULGAR

WhatisJAVA?

HISTORY

Java began at Sun Microsystems around 1990 and was developed primarily
by James Gosling with inspiration from Bill Joy.
Called
C
ll d Oak
O k originally,
i i ll the
th language
l
was intended
i t d d as control
t l software
ft
for
f
embedded microprocessors in consumer items like cable set-top
boxes,VCR's, toasters, etc, as well as personal data assistants (PDA). This
meant that it should be
Platform independent since the processors would come from multiple
manufacturers.
Extremely reliable and compact.
compact
The interactive TV and PDA markets never took off, but in 1993 the internet
and the Web began to explode and the Java emphasis was quickly shifted to
internet applications.
Not much attention paid until the HotJava browser, written in Java at Sun in
a few months, appeared in 1994. It illustrated the power of applets, Java
programs downloaded over the net and run in the browser at the client end.

JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

WhatisJAVA?

HISTORY

In 1996 the Java Development Kit (JDK) Version 1.0 was released by Sun and
available free for downloading. Version 1.1, with substantially greater
capabilities, was released in 1997.
Netscape 2.0-4.0 included Java 1.0. Microsoft and other companies also
licensed Java.
Battles began over control of Java. Microsoft added capabilities to its
version of Java to take advantage of native Windows functions but this
reduced Java
s platform independence
independence. Sun came out with the "100%
100% Pure
Java's
Java" campaign.
Sun is trying to turn Java over to a standards body yet still maintain status
as the primary source. Sun also wants control of the copyrights to logos,
etc.

JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

WhatisJAVA?

JAVA Features

Simplicity
Si
li i - (at
( least
l
compared
d to C and
d C++
C )
no pointers,
no preprocessor
automatic garbage collection
Familiarity - similar enough to C and C++ that programmers can get going quickly.

Object Oriented throughout, e.g. no coding outside of class definitions,


including main(). Comes with an extensive standard class library.
Compiler/Interpreter Combo - code is compiled to bytecodes which are interpreted by a virtual
machine.
compilation, which does extensive code checking
checking, and
machine Offers the advantages of compilation
interpretation, which allows for portability.
Security - several features work to provide greater security:
no memory pointers
programs run inside the virtual machine which can limit the size of the "sandbox" allowed to
the program.
code checked for pathologies by the
bytecode verifier
class loader
security manager
Robustness - exception handling built
built-in,
in strong type checking (i.e.
(i e all variables must be given
explicit type), local variables must be initialized, extensive compile and run time checking.
JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

WhatisJAVA?

JAVA Features

Platform Independence - once the virtual interpreter is ported to a given machine, the
Java routines will run on that platform without code modification or re-compilation.
Good Performance - interpretation of bytecodes instead of text, as in Basic, provides
fast performance, although can still be substantially slower than programs compiled
to native machine code. However, just-in-time compilers, which compile the Java
bytecodes to native code on the fly, will provide performance at 50-90% the speed of
C/C
C/C++ programs.
Built-in Networking - since Java was designed with networking in mind, it comes with
many classes available for internet communications. Can easily design routines to
communicate via URL's as well as design standalone server/client systems using
more direct communications.
Th di - multiple
lti l Lightweight
Li ht i ht processes, called
ll d threads,
th d can easily
il be
b spun off
ff to
t
Threading
perform multi-processing. These are used, for example, in multi-media programs
where one thread presents graphics and another plays the sound recordings.
Dynamic - objects of new classes can be added dynamically at run-time. For example,
a routine implementing a new kind of compression/decompression format could be
downloaded along with the data file to carry out the decompression of the picture

JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

WhatisJAVA?

JAVA Features

To code in JAVA what we need is actually only


the JDK ( JAVA DEVELOPMENT KIT))
programs we have to have JRE
To run JAVA programs,
(JAVA Runtime Environment) installed on
the
th computer
t or the
th machine
hi environment
i
t
(PDA, Mobile phone, toaster, microwave oven
etc.)
That is to say, JRE is the name of the
VIRTUAL MACHINE
MACHINE.
JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

YOURFIRSTJAVAPROGRAM

Anatomy of the Program

First thing to learn : JAVA is designed to be Object Oriented.


Anything, everything you code will be in th form of classes,
member data (FIELDS) of a Class,
member functions (METHODS) of a Class,
A d the
And
th instances
i t
off the
th classes
l
you code
d ( O B J E C T S)
BECAREFUL!! Your program code
and executable will have name
HelloWorld (case sensitive)

Your program is a class itself


itself.
That is why the extension of a
JAVA executable is .class
In JAVA, the main function is a
method of your main program class.

Since JAVA main() functions CANNOT return


any value, main in JAVA has void return type.

Remember !!! In C/C++, since


the program must inform the
OS at all times, the main
function MUST return int

The main program must be invoked without being called as the first function. Only static functions can be called
without creating
g the instance to the classes. So we are declaring
g it as static.
Because public is an access specifier and static is the keyword that executes instantly when java program run ...we
can access the main () in the another class if we need
JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Classical Way

1 . Write
W it your source code
d in
i
any text editor and save it in a
folder you want with .java
extension.

2. Compile your code with


javac (JAVA Compiler).
Compiler will produce a .class
class
file.

3. Run your program using


java command.
Remember, .class runs on the
JAVA virtual machine.
i.e. Your program is not
compiled for the real machine.
JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Netbeans IDE

ATTENTION !!! COMMON STUDENT MISTAKE !!!


IDE(Integrated Development Environment) IS NOT THE COMPILER
JAVAPROGRAMMING

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Netbeans IDE

1 . CREATE A NEW PROJECT

JAVAPROGRAMMING

10

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Netbeans IDE

2 . FOR BASIC CONSOLE APPLICATION CHOOSE Java Application


pp

JAVAPROGRAMMING

11

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Netbeans IDE

2 . Set the name and the folder of your program

BECAREFUL!! THE NAME YOU WRITE


HERE WILL BE NAME OF YOUR MAIN
SOURCE JAVA FILE.
I this
thi example,
l you are setting
tti
In
a
HelloWorld.java source filename
JAVAPROGRAMMING

12

PreparedBy,Dr.TamerTULGAR

HOWTOCOMPILEANDRUNAJAVAPROGRAM

Netbeans IDE

3 . Write your source code, compile run and see the output. (IDE)

Compile and run your program by


clicking this icon.(GREEN PLAY icon)

Error messages, warnings or the


output will appear here.

JAVAPROGRAMMING

13

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Programming Fundamentals

BASIC DATA TYPES,, FUNDAMENTAL


FLOW CONTROL STATEMENTS etc.
HAVE EXTREMELY SIMILAR SYNTAX
AND SEMANTICS TO C FAMILY...
LETS
SO LET
S DIRECTLY USE OUR C/C++
LANGUAGE KNOWLEDGE AND
WARM UP WITH SOME REAL
EXAMPLES
EXAMPLES...
JAVAPROGRAMMING

14

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

1. Display
y Hello World 10 times

JAVAPROGRAMMING

15

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

2. Display
p y Hello World only
y on the even counts of the loop
p

JAVAPROGRAMMING

16

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

3. Display
p y the for loop
p counter

JAVAPROGRAMMING

17

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

4. Lets use if statement

JAVAPROGRAMMING

18

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

5. Lets use while loop

JAVAPROGRAMMING

19

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

6. PAY ATTENTION TO ARRAY DECLERATION

JAVAPROGRAMMING

20

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

7. PAY ATTENTION USER INPUT PART and ARRAY DECLERATION

JAVAPROGRAMMING

21

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE
!! HOMEWORK !!

WRITE THE FOLLOWING JAVA PROGRAMS:

1
1.

Create a random integer and display the prime numbers between 0 and that random
number.

2.

Declare a matrix, fill it by user input, display the sum and the avarage of the
elements.

3.

Declare three 10 by 10 matrices, assign the matrix product of the first two to the third
matrix Display the product.
product
matrix.

4.

Take integers from the user until he/she enters 1000, display the sum and the avarage
of the numbers.

5.

Declare an integer array of 100 elements. Fill your array with random numbers and
sort your array in ascending order using:
I
I.
Bubble Sort
II.
Quick Sort

http://www.oracle.com/technetwork/java/javase/downloads/index.html

JDK is FREE YOU CAN DOWNLOAD


JDK + NetBeans Bundle using
g the URL
given above.
JAVAPROGRAMMING

22

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Operators and White Spaces in Java

Escape Codes

Operator Precedence Table


Highest
Precedence

LETS REMEMBER SOME OF THE


MOST WIDELY USED OPERATORS
AND SPECIAL CHARACTERS

Lowest
Precedence
JAVAPROGRAMMING

23

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Primitive Data Types in Java

Integer data can be stored with int type. There are various sizes of int;

The floating-point number, which has the type float or double.


Floating-point numbers are numbers with a decimal point. The float type can
handle any number from 1.4E
1 4E-45
45 to 3.4E+38.
3 4E+38 If not enough,
enough the double type can
be used for more precise numbers ranging from 4.9E-324 to 1.7E+308.

The char type is used for individual characters, such as letters, numbers,
punctuation, and other symbols.

Lastly, in Java we have boolean type which can be either true or false.

JAVAPROGRAMMING

24

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Keyword final in Java

A java variable can be declared using the keyword final.


final
Then the final variable can be assigned only once.
- A variable
i bl that
th t is
i declared
d l
d as final
fi l and
d nott initialized
i iti li d is
i called
ll d a
blank final variable.
A blank final variable forces the constructors to initialize it.
- Java classes declared as final cannot be extended.
Restricting
g inheritance!
- Methods declared as final cannot be overridden.

eg
e.g.
final float a = 3.56;

JAVAPROGRAMMING

// a is constant now, it cannot be


changed later in the program.

25

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Arrays in Java

In general, a one-dimensional array is a list of related variables referenced by a


common name
name. In JAVA above definition is also valid but there is a very important
implementation detail:

IN JAVA ARRAYS ARE IMPLEMENTED AS OBJECTS


General form of array declaretion in JAVA:
type array_name[] = new type[size];
Th creation
The
ti
off an array is
i a two
t
step
t process.
step1 Declare an array reference
step 2 Allocate memory for the array and assign the reference to that memory.
For example;
(step 1) int array1[];
(step 2) array1 = new int[50];

int array1[] = new int[50];

!!! The keyword new is used to dynamically allocate memory for


objects. Thus, we will be using the new keyword for any

object creation.
JAVAPROGRAMMING

26

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Flow Control Fundamentals

Using for-each loop (EXTREMELY USEFUL WITH LISTS OF OBJECTS)

Here you can use


i < arr.length
Data member(field)

elm will get the consecutive


elements of the array during
the iterations of the for loop.
e.g.
iteration 0 ..... elm <- arr[0]
iteration 1 ..... elm <- arr[1]
iteration 2 ..... elm <- arr[2]
..........

JAVAPROGRAMMING

27

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Arrays in Java

Two-dimensional arrays are, in fact, arrays of arrays.Therefore, two-dimensional


arrays are created
t d in
i th
the same way as one-dimensional
di
i
l arrays.
int array2[][] = new int[10][5];
Above declaretion creates a matrix with 10 rows and 5 columns in memory.
array2[0]
array2[1]
array2[2]

array2[9]

JAVAPROGRAMMING

28

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Arrays in Java

In JAVA, multi dimensional array


y declaration can be done manually.
y
This feature creates a very important advantage for JAVA.
Example
int sample[][] = new int[6][]; Here you can declare the
second dimension seperately
sample[0]
0 = new int[5];
sample[1] = new int[5];
sample[2] = new int[5];
sample[0]
p [ ]
sample[3]
l [3] = new int[3];
i t[3]
sample[4] = new int[2];
sample[1]
sample[5] = new int[2];
ADVANTAGE OF
IRREGULAR ARRAYS
YOU DO NOT WASTE MEMORY
SPACE. (i.e. You can allocate
exactyle what you need.)
THIS POSSIBLE ONLY BECAUSE
ARRAYS ARE LISTS OF OBJECTS.
JAVAPROGRAMMING

sample[2]
sample[3]
sample[4]
l [5]
sample[5]
29

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Arrays in Java

Using two dimensional arrays and random number generators

for (int r = 0; r < a.length; r++)


for (int c = 0; c<a[r].length; c++)
Using length is more flexible
especially when using
irregular arrays.

JAVAPROGRAMMING

30

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Arrays in Java

Using irregular arrays

JAVAPROGRAMMING

31

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Strings in Java

In most of the programming langugaes, a string is a one-dimensional array of


characters.

IN JAVA STRINGS ARE NOT CHARACTER ARRAYS.


THEY ARE OBJECTS ON THEIR OWN.
General form of String declaretion in JAVA:
S i
String
str1
1 =
Hello
ll World;
ld
String str2;
String str3 = str2;
BECAREFUL, since the String is the name of the class data type
String
S.
g starts with capital
p
Some useful methods of the String class.
str1.length()
Returns the length of the string
str1.equals(str2) Returns true if str1 and str2 are equal.
str1.charAt(idx) Returns the character at the index idx.
str1.compareTo(str2)
str1 and str2,, returns zero if str1==str2
p
(
) Compares
p
if str1 < str2, returns negative int
if str1 > str2, returns positive int
JAVAPROGRAMMING

32

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Strings in Java

Using switch-case statement block. Pay attention to .charAt method

Here you can use


i < a.length()
Method!!!!

JAVAPROGRAMMING

33

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Strings in Java

Using if-else statement block. Pay attention to .equals method

JAVAPROGRAMMING

34

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Strings in Java

Using do-while loop. Pay attention to .equals method

JAVAPROGRAMMING

35

PreparedBy,Dr.TamerTULGAR

JAVALANGUAGE

Working with Strings in Java

Arrays of Strings

In JAVA we can create arrays


of Strings. (i.e.array of objects)
Every string in the array can
have different length.
Also, pay attention that in
JAVA string concatenation is
performed
f
d by
b the
th + operator.
t

JAVAPROGRAMMING

36

PreparedBy,Dr.TamerTULGAR

You might also like