Lecture Notes 2 Chapter2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Chapter 2

Notes

Summarized by:
Ahmad Shawaqfeh

5
Chapter 2: Java Application

• Trace a Program Execution


• Variables
• Reading Input from the Console
• Operators
• Assignment operator (=)
• Compound assignment operator
• Increment and decrement operators
• Conversion between primitive types
• Parentheses for grouping subexpressions

Trace a Program Execution


A java application is a computer program that executes when you use the java command to
launch the JVM.

public class ComputeArea{


/** Main method */
public static void main(String [] args){
double radius;
double area;

//Assign radius
radius = 20;

//Compute area
area = radius * 3.14159;

//Display results
System.out.println(“The area for the circle of radius “ + radius + “ is “ +
area);
}
}

1. public class ComputeArea {: This line starts the definition of the ComputeArea class.
2. /** Main method */: This is a comment that describes the purpose of the following method.
3. public static void main(String[] args) {: This line defines the main method, which is the
entry point for the program.
4. double radius;: This line declares a double variable named radius. It is not initialized with a
value yet.
5. double area;: This line declares another double variable named area.
6. radius = 20;: Here, the radius variable is assigned the value 20. This sets the radius of the circle
to 20 units.
6
7. area = radius * radius * 3.14159;: This line calculates the area of the circle using the
formula πr2. It assigns the result to the area variable. In this case, radius is 20, and the value of π
is approximated as 3.14159.
8. System.out.println("The area for the circle of radius " + radius + " is " +
area);: This line prints a message to the console using System.out.println. It includes the value
of radius and the calculated area. The + operator is used for string concatenation.

When you run this program, it will display the following output:

The area for the circle of radius 20.0 is 1256.636

Notes

o A white space can be blank line, space character or tab, ignored by the compiler. It makes
programs easier to read.
o Java is case sensitive – a1 is different than A1
By convention, all class names in Java begin with a capital letter (each subsequent word begins
with a capital letter).
The class name is an identifier (series of characters consisting of letters, digits, underscores
and $ that doesn’t begin with a digit and doesn’t contain spaces.) ◦ Examples of valid
identifiers: hello, valid_$1, $23, _Name ◦ Examples of invalid identifiers: 123Here, exam-1,
student ID, not@valid, class
o In a java application, JVM will not execute the application if the main method does not exist,
i.e. for a java application, exactly one of the methods must be called main, otherwise the JVM
will not execute the application. A method is a function that performs tasks and returns
information.
static: a static method can be called without first creating an object of the class in which the
method is declared.
void: keyword that indicates that this method will perform a task but will not return any
information when it completes its task.

Variables
A variable is a location in the computer's memory where a value can be stored for use later in a
program.
Variables must be declared with a name and a type:
• A variable name can be any valid identifier. By convention, variable-name identifiers begin with
a lowercase letter, and every word in the name after the first begins with a capital letter. E.g.
firstNumber
• Variable's type specifies the kind of information stored at that location in memory.

Named Constants

7
o Use final keyword.
o E.g. final int SIZE = 3;
o Cannot be modified later in the program

Primitive Data Types

Category Description JAVA Size Values


byte 8 bits -128 to 127 (-2 to 27-1)
7

short 16 bits -32768 to 32767 (-215 to 215-1)


whole numbers (without decimal int 32 bits -2147483648 to 2147483647
points) (-231 to 231-1)
numbers
long 64 bits (-263 to 263-1)

float 32 bits e.g. 17.345f


real numbers
double 64 bits e.g. 12452.212
characters single characters char 8 bits e.g. 'a', '1' and '?'
booleans boolean values boolean 8 bits true or false

Variables of the same type may be declared in one declaration or in multiple declarations. For
examples, if you want to declare n1 and n2 as integer variables you can use any of the following:
1. int n1; Or 3. int n1, n2;
2. int n2;

Local variables (those declared in the body of a particular method) must be initialized before being
used. For example:

4. int n1; Or 6. int n1=15;


5. n1 = 15; 7.

(or their values can be obtained from the user)

8
Reading Input from the Console
1. import java.util.Scanner;
o is an import declaration that helps the compiler locate a class that is used in this program.
The above declaration indicates that the program uses java's predefined Scanner class from
package (java.util).
o All import declarations must appear before the first class declaration in the file.

2. Scanner input = new Scanner (System.in);


o is a variable declaration statement: variable name is input, type is Scanner. [A Scanner
enables a program to read data (e.g numbers) for use in a program, the data can come from
a file or the keyboard].
o It creates an object of class Scanner (using the keyword new) and the source of data is
specified by System.in (standard input object), which is the keyboard.

3. number1 = input.nextInt();

o uses the method nextInt to obtain an integer from the user.

Other Scanner methods:

Method Description

nextByte() reads an integer of the byte type.


nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

Operators
Arithmetic operators
Java operation Arithmetic operator Algebraic expression Java expression
Addition + f+7 f +7
Subtraction - p-c p–c
Multiplication * bm b*m
Division (integer or real division) / x/y or x÷y x/y

Remainder % r mod s r%s

9
o Integer division yields integer quotient (provided that both operands are integers). Fractions in
the result are truncated (no rounding occurs). Examples:

8. int x = 7/4; //x=1

double y = 7/4; //y=1.0

double z= 7/4.0 //z=1.75

Remainder operator yields the remainder after division. For example:


7%4 = 3
17%5 = 2
2%5=2
12%2=0

Assignment operator (=)


Used to assign values to variables. Everything to the right of the assignment operator is always
evaluated before the assignment is performed.

Compound assignment operator


Any statement of the form: variable = variable operator expression;
Where operator is one of the binary operators +, -, *, / or % can be written in the form:
Variable operator= expression;
e.g. c=c+3 can be written as c+=3;
Assume: int c=3, d=5, e=4, f=6, g=12;
Assignment operator Sample expression Explanation assigns
+= c+=7 c=c+7 10 to c
-= d-=4 d=d-4 1 to d
*= e*=5 e=e*5 20 to e
/= f/=3 F=f/3 2 to f
%= g%=9 g=g%9 3 to g

10
Increment and decrement operators
Java provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric
variable. The unary increment operator, ++, and the unary decrement operator, --
Operator Operator name Sample Explanation
expression
++ Prefix increment ++a Increment a by 1, then use the new value of a in the
expression in which a resides.
++ Postfix increment a++ Use the current value of a in the expression in
which a resides, then increment a by 1.
-- Prefix decrement --b Decrement b by 1, then use the new value of b in
the expression in which b resides.
-- Postfix decrement b-- Use the current value of b in the expression in
which b resides, then decrement b by 1.

Example:
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

Conversion between primitive types


o promotions: implicit conversion, conversion without losing data. Promotions allowed for primitive types:
Type Valid promotions
double None
float double
long float or double
int long, float or double
char int, long, float or double
short int, long, float or double (but not char)
byte short, int, long, float or double (but not char)
Boolean None (Boolean values are not considered to be numbers in java.
For example, the following statements are correct:

int y = 4;
char c = 'A';
double x = y; //x=4.0
int d = c; // d=65

11
but:
double a = 4.5;
int m = 65;
int b = a; //Error!
Char c = m;//Error!

Casting: explicit conversion, conversion may cause loss of data. For example:
int a = (int) 3.5; //a=3

long b = 5;
int a = (int) b; //a=5 (note that the value of b is not changed)

Note: when you declare a float variable and initialize it to some value, you should cast this value because it
is considered as double. For example:

float x=4.5; //Error


float x=(float) 4.5; //correct
float x=4.5f; //correct

float c=5.6f;
long b=c; //Error

float c =5.6f;
long b=(long) c; //b=5

12
Parentheses for grouping subexpressions
To multiply a times the quantity b+c, we write: a*(b+c) if an expression contains nested
parentheses, such as ((a+b)*c)
The expression in the innermost set of parentheses is evaluated first.

Rules of operator precedence:


Operators Associativity Type

++ -- Left to right Increment and decrement operators

* / % Left to right Multiplicative

+ - Left to right Additive


< <= > >= Left to right Relational
== != Left to right Equality
?: (will be explained later) Right to left Conditional

= += -= *= /= %= Right to left assignment


Examples:

Algebra java

m=(a+b+c+d+e)/5;

m=a+b+c+d+e/5;

y = mx +b y= m*x+b;

z = pr mod q+ w/x-y z = p * r % q + w / x - y;

y = ax2+bx+c y = a * x * x + b * x + c;

z= p * r % q + w / x - y;
6 1 2 4 3 5

y = a * x * x + b * x + c;
6 1 2 4 3 5

13

You might also like