You are on page 1of 51

Advanced Programming

Chapter-1
Introduction to Java
Contents
Introduction
Data types, Variables and Keywords
Control Structures
Methods and Arrays

2
Introduction
What is java?
• Java is a general purpose, concurrent, class based,
object oriented programming language.
• Java as an object-oriented language was designed from
the outset to be platform independent, robust, and secure.
Java Design Goals
• To provide code for programs that would run on many different
hardware platforms.
• To produce robust programs - programs that would have as few
bugs (error) as possible.
• To be easy to learn and use.

3
Java Characteristics
 Java is simple in that it retains much familiar syntax of C++.
 It is strongly typed. This means that every thing must have a data
type.
 Java performs its own memory management avoiding the
memory leaks that plague programs written in languages like C
and C++.
 Java is completely object oriented.
 Java is multi-threaded, allowing a program to do more than one
thing at a time.
 Network-Savvy: extensive library of routines for coping with
TCP/IP protocols like HTTP and FTP.
 Secure and Robust: Java is intended for writing programs that are
reliable and secure in a variety of ways.
 Portable and architecture neutral. 4
The Java language Specifications, API, JDK
and IDE
• Java language Specifications: a technical specifications of the language
that includes the syntax and semantics of the language.
• API (Application Program Interface): Contains predefined classes and
interfaces for developing java programs.
Three editions of java API
– J2SE: Java 2 Standard Edition
– J2EE: Java 2 Enterprise Edition
– J2ME: Java 2 Micro Edition
• JDK(Java Development Toolkit): Consists of a set of programs for
developing and testing java programs each of which is invoked from a
command line .
Three major java development tools
– Jbulider
– NetBeans
– Eclipse 5
Java Application Vs Applet
• Java can be used to create two types of programs:
applications and applets.

• Application: is a stand alone program that runs on your


computer, under the operating system of your computer.

• Applet: is an application designed to be transmitted over


the internet and executed by the java compatible web
browser.
• The focus of an applet is the WWW, although several other
tools (such as applet viewer) can also run Java applets.
• Applets are normally embedded within HTML documents.

6
Getting Started with Java Programming

• A Simple Java Application


• Compiling Programs
• Executing Applications

7
Creating , Compiling and Executing a Java
program. Create/Modify Course code

Source Code

A bytecode file with Compile Source Code


Hello.class e.g javac Hello.java

Bytecode

Run Bytecode
e.g. java Hello

Result

8
The Java Virtual Machine (JVM) and Byte code
• Earlier programming languages are platform dependent, meaning they only
run on a predefined software or hardware.
• Java compiles the java source code, not into some particular machine code,
but into a machine code (byte code), for a hypothetical machine, and is what
is downloaded into the local machine.
• But the byte codes are not the native machine code of the local computer, so
we need a program in the local machine (called the interpreter) that reads,
the byte codes, interprets what operation have to be carried out on what data
and carries them out.
• A bytecode is an intermediate form of a program, where source code has
been translated to a generic, binary format that is unrelated to the instruction
set of any specific computing platform.
• The program that interprets a java program (bytecode) is often called a java
virtual machine (JVM).

9
Steps to create a Java application:
1. Using any text editor, write Java application source
code.

2. Compile the Java source code. When this is done, the


Java compiler creates a byte-code file.

3. Invoke the Java interpreter. It will run the byte-code


file.

4. Debug as necessary, by invoking the Java debugger


(jdb).
10
A Simple Application
Example 1:
//This application program prints Welcome to Java!
message on the console window.
public class Welcome
{
public static void main(String[] args)
{
System.out.println("Welcome to Java!");
}
} 11
Remarks
• Every java program must have at least one class

• A class is a construct that defines data and methods

• Everything must be in class

• By convention, class name start with an uppercase letter

• In order to run a class, the class must contain a method named main

Commands on a command prompt to Compile and Execute


 javac Welcome.java // compile
 java Welcome // run or execute
 output:...

12
Anatomy of a Java Program
• A java program contains:
– Comments
– Reserved words
– Package
– Modifiers
– Statements
– Blocks
– Classes
– Methods
– The main method

13
Comments
• Preceded by two slashes (//) in a line, or enclosed
between /* and */ in one or multiple lines.

Reserved Words
• Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used
for other purposes in the program.

Example:
class, public, static, and void .

14
Packages
• A group of predefined classes
Example:
• JOptionPane is in javax.swing package i.e it
is imported to a program using import
statement.
• java.lang package is imported implicitly in
every java program. e.g. System class is not
imported because it is in this package

15
Modifiers
• Reserved words that specify the properties of the data,
methods, and classes and how they can be used.
• E.g. public and static, private, final, abstract, and protected.

Statements
• Represents an action or a sequence of actions.
• E.g.: System.out.println("Welcome to Java!"); is a statement to
display the greeting "Welcome to Java!"
• Should end with a semicolon (;).

Block
• A pair of braces in a program forms a block that groups components of
a program.

16
Classes
• The essential Java construct that serves as a template or blueprint for
objects.

Methods
• A collection of statements that performs a sequence of operations.

Main Method
• The main method provides the control of program flow.
• The Java interpreter executes the application by invoking the main
method.
•  The main method looks like this:

  public static void main(String[] args)


{
// Statements;
}
17
Java Class Library
• These libraries of classes provide support for I/O, the graphic user interface,
string manipulation, math and so on.
• The basic java library that accompanies your java development software is
stored in a file called class.zip.
• Inside class.zip is a hierarchy of packages, each of which contains a group of
related java classes.

• There are four basic packages inside class.zip.


– java.lang: contains support for arithmetic manipulation, numeric data types, and arrays.
– java.io: contains support for I/O.
– java.util: contains a variety of utility routines, including a random number generator
and a date class.
– java.awt: contains classes for a GUI as well as some simple drawing routines.
• The class.zip file also contains java.net, which provides support for interacting
with a network.

18
Data Types, Variables and Keywords
References and Primitive Data Types
In java there are two categories of data types:
– Primitive (Basic/Simple) types: consists of int, float, char and
Boolean.
– Reference types: consists of interfaces, classes, and arrays.

19
Variables
• A variable is an identifier that is to represent some specified type of
information within a designated portion of a program.
• An identifier is a name that uniquely identifies a variable, a method
(function), a class or any other element in java that requires a name.
• The following are considered valid in identifiers names:
– Upper case and lower case letters a through z. E.g. int x, string
name…
– Underscore character (_). E.g. string Stud_name…
– The dollar sign ($). E.g. char val$...
– Except for the first character, the digits 0-9. E.g. int x1, x2,.. int 1x,
2x (Wrong)
– Identifiers are case sensitive. E.g. String Name is not the same as
String name

20
• The syntax for declaring a variable is
datatype variableName;
Eg:
int count;
double radius;
double interestRate;
• Variables often have initial values.
Eg. int count=1;

21
Constants Variables
• Represents permanent data that never changes.

• Syntax for declaring a constant:

final data_type CONSTANTNAME = VALUE;

• The word final is a Java keyword for declaring a


constant.

Eg. final double PI = 3.14159;

22
Character and String Data Type
Character data type:
– Used to represent a single character
– A character literal is enclosed in single quotation
marks.
Eg. char letter=‘A’;
String Data type
– Represent a string of character
– A predefined class in java library
– It is known as reference type
Eg. String message =“Welcome to Java”
23
Programming errors
 Categorized into three types
1. Syntax Errors
• Occur during compilation
• Result from errors in code construction, such as mistyping a keyword,
omitting some necessary punctuation, or using an opening brace
without a corresponding closing brace.
• Usually easy to detect, b/c the compiler tells you where they are and
what caused them.

2. Runtime Errors
• Cause a program to terminate abnormally.
• Occur while a program is running if the environment detects an
operation that is impossible to carry out.
– Eg. Input errors 24
3. Logical Errors
• Logic errors occur when a program does not perform the way it
was intended to.
• Finding logic errors, can be very challenging
• Logic errors are called bugs. The process of finding and correcting
errors is called debugging.
• Can hand-trace the program i.e this approach might work for a
short, simple program.
• Debugger utility: the most effective approach for large, and
complex program.

25
Control Structures
• Control structures are a way to alter the natural sequence
of execution in a Java program.
• They act as “direction signals” to control the path a
program takes.
• The process of performing one statement after another is
called the flow of execution or flow of control.
• Control structures include:
 Block statements
 Decision statements
 Loops
26
Decision Statements
• The control statements that allow alternative actions based up on
conditions that are evaluated at run time are generally called decision or
selection statements.
• These include if and switch statements.
If Statements
• A simple if statement executes an action if and only if the condition is
true.
• The syntax:
if (boolean-expression)
{
statement(s);
} 27
28
If … Else Statement
• To take alternative actions when the condition is false, you can
use an if… else statement.
• The actions that a if…else statement specifies differ based on
whether the condition is true or false.
• The syntax:
if (boolean-expression)
{
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
} 29
30
Nested if Statements
• The nested if statement can be used to implement multiple
alternatives.
Eg. if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F'; 31
Switch Statements
• Java provides it to handle multiple conditions efficiently, replace
the nested if statement.
• The syntax:
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
32
Decision Statements…
• Some most useful program use data objects that contain sequences of
numbered elements.
• These sequences are easily processed by iteration statement blocks.
• Such programming statements are called loops, because the flow of
execution “loops back” to the beginning of the block.
The while Loop
• The syntax:
while (condition)
{
// Loop body
Statement(s);
} 33
34
The do-while Loop
• The do-while loop is a variation of the while loop.
• Syntax :
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• Executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or
terminate the loop.

35
36
The for Loop
• A for loop can be used to simplify the proceeding loop:

for (i = initialValue; i < endValue; i++)


{
// Loop body
...
}

37
38
Methods
• The syntax for defining a method is as follows:

modifier returnValueType methodName(list of parameters)


{
// method body;
}
• The method header specifies the modifiers, return value
type, method name, and parameters of the method.

39
40
• If a method returns a value, it is called a value returning
method, otherwise it is a void method.
• Formal parameters : variables defined in the method header.
• Actual parameter or argument, when a method is invoked, it’s
value passed as a parameter..
• In order for a value-returning method to return a result, a
return statement using the keyword return is required. .
• Methods can be used to reduce redundant code and enable
code reuse.
Overloading Methods
• Two methods have the same name but different parameter lists
within one class.
41
Array Basics
• Used to store a collection of data,
• A collection of variables of the same type.
Declaring Array Variables
• Syntax
dataType[] arrayName;
• For example, declares a variable myList that references an
array of double data type elements.

double[] myList;

42
Creating Arrays
• After an array variable is declared, you can create an array by
using the new operator with the following syntax:

arrayName = new dataType[arraySize];


• This statement does two things:
(1) It creates an array using new dataType[array-Size];
(2) It assigns the reference of the newly created array to the
variable arrayName

43
• Here is an example:
double[] myList = new double[10];
• To assign values to the elements, use the syntax:
arrayName[index] = value;
• 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
• Each element in the array is represented using the following
syntax, known as an indexed variable:
arrayName[index];

44
45
Array Initializers
• Combines in one statement declaring an array, creating an array,
and initializing, using the following syntax:

dataType[] arrayName = {value0, value1, ..., valuek};


Example:
double[] myList = {1.9, 2.9, 3.4, 3.5};
Processing Arrays
• We will often use a for loop—for two reasons:
1. All of the elements in an array are of the same type. They are
evenly processed in the same fashion repeatedly using a loop.
2. Since the size of the array is known, it is natural to use a for loop
46
For-each Loops
• Java supports a convenient for loop, known as a for-each loop or
enhanced for loop, which enables to traverse the array
sequentially without using an index variable.

Syntax
for (elementType element: arrayRefVar)
{
// Process the element
}

47
• Eg, the following code displays all the elements in the array
myList:

for (double u: myList)


{
System.out.println(u);
}
• You can read the code as “for each element u in myList” do the
following.

• U, must be declared the same type as the elements in myList.

48
Passing Arrays to Methods
• Java uses pass-by-value to pass arguments to a method.

• There are important differences between passing the values of


variables of primitive data types and passing arrays.

• For an argument of a primitive type, the argument’s value is


passed.

• For an argument of an array type, the value of the argument is a


reference to an array; this reference value is passed to the method.

49
Two-Dimensional Array Basics
• Used to represent a matrix or a table

• syntax for declaring a two-dimensional array:


dataType[][] arrayNamr;
or
dataType arrayName[][]; // Allowed, but not preferred
• As an example, here is how you would declare a two-dimensional
array variable matrix of int values:

int[][] matrix;

50
End of Ch.1

51

You might also like