You are on page 1of 39

Fundamental

Programming
Structures in Java
Lecture - 02
March 12,2013
1
Outline
Basic Java Programming Steps

Variables and Primitive Data Types

Operators

The Required Static main method

2
Basic Java Programming Steps
public class FirstSample
{
public static void main(String[] args)
{
System.out.println(“We will not use
Hello World”);
}
}

3
Analysis of Program Structure
Everything in a java program lives inside a class.
 Class is like a container for your program.

Keyword: public, this is called an access modifier.


 It lets you control the level of access other parts of a program
have to this code.
Naming Convention for class
 Names must begin with a letter
 They can have any combinations of letters and digits
 You can’t use java’s reserved keywords( see Appendix for a list
of reserved words)

4
Program Compilation and Execution
Points to Remember

1. You need to name your source code file the same as the
name of the public class with the extension .java
2. After successful compilation the Java Compiler
automatically names the byte code file FirstClass.class and
stores it in the same directory as the source file
3. During program execution using the keyword java on the
command line, the JVM always start executing your program
from the code in the main method in the class you indicate

5
Comments
Java has three kind of commenting styles available:
 // use this to write single line comments

 /*

*/ use this for comments that span multiple lines

Java also has a third way to let you mark comments


 This kind of comment can be used to generate documentation automatically

 /**

*/
 The JDK contains a tool, called javadoc, that generates HTML
documentation from your source files.

6
Variables
Variables are places where information can be stored
while a program is running.
Their values can be changed at any point over the
course of a program
To create a variable, declare its name and the type of
information that it will store.
The type is listed first, followed by the name.
Example:
int highScore ;

type name
7
Variables: Naming Convention
The name you choose for your java variable is called
identifier.
The identifier must:
 start with a letter, ($) dollar sign or (_) underscore
 Be a sequence of letters or digits
 Not contain +, @ or spaces
 Not be a java reserved keyword

The length of the identifier is essentially unlimited


Java is case sensitive, the capitalization of letters in
identifiers matters.
8
POP QUIZ
Which of the following are valid variable names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
Data Types
Java is a strongly typed language. This means
 Every variable must have a declared type.
 Each variable’s declared type does not change over the
course of the program
 Certain operations are only allowed with certain data
types
Java has 8 primitive data types:
 4 are integer types
 2 are floating-point types
 1 is the character type char, and
 1 is the boolean type for truth values.

10
Integer Data Types
There are four data types that can be used to
store integers.
The one you choose to use depends on the
size of the number that you want to store.
Data Type Value Range

byte -128 to +127

short -32768 to +32767

int -2147483648 to +2147483647

long -9223372036854775808 to +9223372036854775807


Examples
 Here are some examples of when you would
want to use integer types:

- byte smallValue;
smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;

Note: By adding an L to the end of the value in the last


example, the program is “forced” to consider the value
to be of a type long even if it was small enough to be
an int
Floating Point Data Types
There are two data types that can be used to store
decimal values (real numbers).
The one you choose to use depends on the size of
the number that you want to store.
Data Type Value Range
float 1.4×10-45 to 3.4×1038
double 4.9×10-324 to 1.7×10308

Double refers to the fact that these numbers have


twice the precision of the float type.
Example
Here are some examples of when you would want to
use floating point types:

double g = 7.7e100 ;
double tinyNumber = 5.82e-203;
float costOfBook = 49.99F;

Note: In the last example we added an F to the end of


the value. Without the F, it would have automatically
been considered a double instead.
Boolean Data Type
Boolean is a data type that can be used in situations
where there are two options, either true or false.

 Example:
boolean printready = true;
boolean fileOpen = false;
Character Data Types
Character is a data type that can be used to store a
single characters such as a letter, number,
punctuation mark, or other symbol.

Example:
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;

Note that you need to use singular quotation


marks when assigning char data types.
Escape Sequences

17
Introduction to String
Strings consist of a series of characters inside double

quotation marks.

Examples statements assign String variables:


String coAuthor = "John Smith";
String password = "swordfish786";

Strings are not one of the primitive data types, although

they are very commonly used.


18
POP QUIZ
What data types would you use to store the following
types of information?:

1)Population of Ethiopia int


2)Approximation of π double
3)Open/closed status of a file boolean
4)Your name String
5)First letter of your name char
6)$237.66 double
Constants
In Java you use the keyword final to denote a constant.
 e.g. final double CM_PER_INCH = 2.54;

Keyword final indicates that you can assign to the variable once,

and then the value is set once and for all.


It is customary to name constants in all upper cases.

It is probably more common in java to want a constant that is

available to multiple methods inside a single class.


These are usually called class constants.

You setup a class constant with the keyword static final.


20
What are Operators?
Operators are special symbols used for
 Mathematical functions
 Assignment statements
 Logical comparisons

Examples:
 3 + 5 // uses + operator
 14 + 5 – 4 * (5 – 3) // uses +, -, * operators

Expressions can be combinations of variables, primitives

and operators that result in a value


21
The Operator Groups
There are 5 different groups of operators:

 Arithmetic operators

 Assignment operator

 Increment/Decrement operators

 Relational operators

 Conditional operators
Arithmetic Operators
Java has 6 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
^ exponent (to the power of )

Order of operations (or precedence) when evaluating an


expression is the same as you learned in school
(PEMDAS).
Order of Operations
Example: 10 + 15 / 5;

The result is different depending on whether the


addition or division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13

Without parentheses, Java will choose the second


case

Note: you should be explicit and use parentheses


to avoid confusion
Integer Division
In the previous example, we were lucky that (10
+ 15) / 5 gives an exact integer answer (5).

But what if we divide 63 by 35?

Depending on the data types of the variables that


store the numbers, we will get different results.
Integer Division Example
 int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1

 double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8

The result of integer division is just the


integer part of the quotient!
Assignment Operator
The basic assignment operator (=) assigns the value of
expr to var.
var = expr ;
Java allows you to combine arithmetic and assignment
operators into a single operator.
Examples:
x = x + 5; is equivalent to x += 5;
y = y * 7; is equivalent to y *= 7;
Increment/Decrement Operators
count = count + 1;
can be written as:
++count; or count++;

++ is called the increment operator.

count = count - 1;
can be written as:
--count; or count--;

-- is called the decrement operator.


The increment/decrement operator has
two forms:
 The prefix form ++count, --count first adds 1 to the variable and then continues to any
other operator in the expression

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

 The postfix form count++, count-- first evaluates the expression and then adds 1 to the
variable

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Relational (Comparison) Operators
• Relational operators compare two values

• Produces a boolean value (true or false)


depending on the relationship
operation is true when . . .
a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
Examples of Relational Operations
int x = 3;
int y = 5;
boolean result;

1) result = (x > y);


now result is assigned the value false because
3 is not greater than 5

2) result = (15 == x*y);


now result is assigned the value true because the product of
3 and 5 equals 15

3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Conditional Operators
Symbol Name

&& AND
|| OR
! NOT

Conditional operators can be referred to as boolean


operators, because they are only used to combine
expressions that have a value of true or false.
Truth Table for Conditional Operators
x y x && y x || y !x

True True True True False

True False False True False

False True False True True

False False False False True


Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;

1. Let result = (x && y);

now result is assigned the value false


(see truth table!)
2. Let result = ((x || y) && x);

(x || y) evaluates to true
(true && x) evaluates to true

now result is assigned the value true


Using && and ||
Examples:
(a && (b++ > 3))
(x || y)

Java will evaluate these expressions from left


to right and so will evaluate
a before (b++ > 3)
x before y

Java performs short-circuit evaluation:


it evaluates && and || expressions from left
to right and once it finds the result, it stops.
Short-Circuit Evaluations
(a && (b++ > 3))
What happens if a is false?
Java will not evaluate the right-hand expression (b++ >
3) if the left-hand operator a is false, since the result is
already determined in this case to be false. This means
b will not be incremented!

(x || y)
What happens if x is true?
Similarly, Java will not evaluate the right-hand operator y
if the left-hand operator x is true, since the result is
already determined in this case to be true.
POP QUIZ
1) What is the value of number? -12
int number = 5 * 3 – 3 / 6 – 9 * 3;

2) What is the value of result? false


int x = 8;
int y = 2;
boolean result = (15 == x * y);

3) What is the value of result? true


boolean x = 7;
boolean result = (x < 8) && (x > 4);

4) What is the value of numCars?


27
int numBlueCars = 5;
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
Required Static Main Method
public static void main(String[] args)

Main method is the entry point for any java program.

You can call static methods without having any objects.

The main method does not operate any object. In fact, when a

program starts, there are not any objects yet.

The static main method executes, and constructs the objects that the

program needs.

Since main method is static JVM can call it without creating any

instance of class which contains main method.


38
Class Exercise
Course Survey and Programming exercise

39

You might also like