0% found this document useful (0 votes)
5 views

Chapter 2 Basics of Java

basics of java

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 2 Basics of Java

basics of java

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 2

Basics in Java Programming

1 Prepared by: Melkamu D.


Introduction
 A class in java is defined by a set of declaration
statements and methods containing executable
statements.
 Most statements contain expressions, which
describe the actions carried out on data.
 Smallest individual units in a program are known as
tokens.
 In simplest terms, a java program is a collection of
tokens, comments, and white spaces.
2 Prepared by: Melkamu D.
 Java has five types of tokens: Reserved
1. Keywords
 Keywords are standard identifiers and their functions is
predefined by the compiler. We cannot use keywords as
variable names, class names, or method names, or as any
other identifier. Keywords in java are case sensitive, all
characters being lower case.
 Java language has reserved 60 words as
keywords.

3 Prepared by: Melkamu D.


2. Identifiers
 Are programmer-designed tokens.
 Are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a
program.
 Java identifiers follow the following rules:
 They can have alphabets, digits, and the
underscore and dollar sign characters.
 They must not begin with a digit
 Uppercase and lowercase letters are distinct.
4 Prepared by: Melkamu D.

POP QUIZ

Which of the following are valid Identifiers?

1) $amount 5) score
2) 6tally 6) first Name
3) my*Name 7) total#
4) salary 8) this

5 Prepared by: Melkamu D.


3. Literals
 Literals in Java are a sequence of characters(digits,
letters and other characters) that represent
constant values to be stored in variables.
 Five major types of literals in Java:
I. Integer Literals: refers to a sequence of digits (decimal
integer, octal integer and hexadecimal integer)
II. Floating-point Literals

III. Character Literals

IV. String Literals

V. Boolean Literals

6 Prepared by: Melkamu D.


4. Separators
 Are symbols used to indicate where groups of code
are divided and arranged.
 They basically define the shape and functions of our
code.
 Java separators include:

I. Parenthesis ( ) :- used to enclose parameters, to


define precedence in expressions, surrounding
cast types

II. Braces { } :- used to contain the values of

7 automatically initialized
Preparedarrays and to define a
by: Melkamu D.
Contd.
III. Brackets [ ] :- are used to declare array types
and for dereferencing array values.

IV. Semicolon ; :- used to separate statements.

V. Comma , :- used to separate consecutive


identifiers in a variable declaration, also used to
chain statements together inside a “for”
statement.

VI. Period . :- Used to separate package names


from sub-package names and classes; also used
8 to separate a variable or method
Prepared by: Melkamu D. from a
5. Operators
 Are symbols that take one or more arguments
(operands) and operates on them to a produce a
result.
 Are used to in programs to manipulate data and
variables.
 They usually form a part of mathematical or
logical expressions.

 Expressions can be combinations of


9 variables, primitivesPrepared
and operators
by: Melkamu D. that
Java Operators
 There are 8 different groups of operators in
Java:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operator
 Increment/Decrement operators
 Conditional operators
 Bitwise operators
10  Special operators Prepared by: Melkamu D.
A. Arithmetic Operators
 Java has five basic arithmetic operators
Operato Meaning
r
+ Addition or unary plus
– Subtraction or unary
minus
* Multiplication
/ Division
 They all%work theModulo
samedivision
way as they do in other
languages.
 We cannot use these operators on boolean type .
 Unlike C and C++, modulus operator can be
applied to the floating point data.
 Order of operations (or precedence) when
11 evaluating an expression isby:the
Prepared same
Melkamu D. as you
B. Relational Operators
 Relational operators compare two values
 Produces a boolean value (true or false) depending on
the relationship.
 Java supports six relational operators:
Operato Meaning
r
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
 Relational expressions are used in decision statements such
as, if and while to decide the course of action of a running
program.
12 Prepared by: Melkamu D.
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)
13 Prepared by: Melkamu D.
C. Logical Operators
Symbol Name
&& Logical AND
|| Logical OR
! Logical NOT

 Logical operators can be referred to as boolean


operators, because they are only used to combine
expressions that have a value of true or false.
 The logical operators && and || are used when we
want to form compound conditions by combining
two or more relations.
 An expression which combines two or more
relational expressions is termed as a logical
expression or aPrepared compound
by: Melkamu D.
relational
14
expression.
Examples of Logiacal 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


15 Prepared by: Melkamu D.
4. Assignment Operator
 Are used to assign the value of an expression to a
variable.
 In addition to the usual assignment operator(=),
java has a set of ‘shorthand’ assignment
operators which are used in the form:
var op = expr ;
Where var is a variable, op is a binary operator
and expr is an expression. The operator op= is
known as shorthand assignment operator.
 The assignment statement: var op= expr; is
equivalent to var=var op(expr);
 Examples:
x += y + 5; is equivalent to x = x+
(y+5);
16
y *= 7; is equivalent to
Prepared by: Melkamu D.
y = y *
5. 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.


 Both ++ and -- are unary operators.
17 Prepared by: Melkamu D.
The increment/decrement operator has two forms:
The prefix form ++count, --count
first adds/subtracts1 to/from 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
18
Prepared by: Melkamu D.
6. Conditional Operators
 The character pair ?: is a ternary operator
available in java.
 It is used to construct conditional expression of
the form:
exp1 ? exp2: exp3;
where exp1, exp2 and exp3 are expressions.
 The operator ?: works as follwos:
 exp1 is evaluated first. If it is nonzero (true), then
the expression exp2 is evaluated and becomes
the value of the conditional expression. exp3 is
evaluated and becomes the value of the conditional
expression if exp1 is false.
 Example:
Given a=10, b=15 the expression
19 x=(a>b)? a:b; will assign
Prepared by: Melkamu the
D. value of
6. Bitwise Operators
 One of the unique features of java compared to other
high-level languages is that it allows direct
manipulation of individual bits within a word.
 Bitwise operators are used to manipulate data at
values of bit level.
 They are used for testing the bits, or shifting them to
the right or left.
 They may not be applied
Operat to float or double data types.
Meaning
or
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
20 Prepared by: Melkamu D.
7. Special Operators
 Java supports some special operators of interest such
as instanceof operator and member selection
operator(.).

7.1 instanceof Operator: is an object reference operator


and returns true if the object on the left-hand side is an
instance of the class given on the right-hand side.
Example :
person instanceof student;
is true if the object person belongs to the class student;
otherwise it is false
7.2 Dot Operator: is used to access the instance
variables and methods of class objects.
Example:
person. age; // Reference to the variable age.
21
person1.salary();Prepared
// by:
Reference
Melkamu D.
to the method
salary.
Type Conversion in Expressions
A. Automatic Type Conversion: If the
operands of an expression are of different types,
the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds. That
is, the result is of the ‘higher’ type.
Example :

int a=110;

float b=23.5;

the expression a+b yields a floating point


22 Prepared by: Melkamu D.
number 133.5 since the ‘higher’ type here is float.
Contd.
B. Casting a value: is used to force type
conversion.
 The general form of a cast is:

(type-name)expression;
where type-name is one of the standard data
types.
Example :

x=(int)7.5; will assign 7 to x

a=(int)21.3/(int)3.5; a will be 7
23 Prepared by: Melkamu D.
Operator Precedence and Associativity.
Operator Description Associativity Rank
. Member Selection
() Function call
Left to right 1
[] Array elements
reference
- Unary Minus
++ Increment
-- Decrement
! Logical negation Right to left 2

~ One’s complement
(type) Casting
* Multiplication
Left to right 3
/ Division
% Modulus
24 Prepared by: Melkamu D.
Contd.
Operator Description Associativity Rank
+ Addition
Left to right 4
- Subtraction
<< Left Shift
Left to right 5
>> Right Shift
>>> Right shift with zero fill
< Less than
<= Less than or equal to
> Greater than Left to right 6
>= Greater than or equal
to
instanceof Type comparison
== Equality
Left to right 7
!= Inequality
25 Prepared by: Melkamu D.
Operator Precedence and Associativity.
Operato Description Associativity Rank
r
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10

&& Logical AND Left to right 11


|| Logical OR Left to right 12
?: Conditional Left to right 13
Operator
= Assignment Left to right 14
operator
Op= Shorthand Left to right 15
assignment

26 Prepared by: Melkamu D.


//Demonstration of Java Expressions
public class DemoExpress
{
public static void main(String[] args)
{
System.out.println("===== BEGINNING OF THE
PROGRAM =====\n");
//Declaration and Initialization
int a=10,b=5,c=8,d=2;
float x=6.4f,y=3.0f;

//Order of Evaluation
int answer1=a*b+c/++d;
int answer2=--a*(b+++c)/d++;

//Type Conversion
float answer3=a/c;
float answer4=(float)a/c;
float answer5=a/y;
27 Prepared by: Melkamu D.
//Modulo Operations
int answer6=a%c;
float answer7=x%y;

//Logical Operations
boolean bool1=a>b && c>d;
boolean bool2=a<b && c>d;
boolean bool3=a<b || c>d;
boolean bool4=!(a-b==c);

System.out.println("Order of Evaluation");
System.out.println("a*b+c/++d + "+answer1);
System.out.println("--a*(b+++c)/d++ = " +answer2);

System.out.println("================");
System.out.println("Type Conversion");
System.out.println(" a/c = "+answer3);
System.out.println("(float)a/c = " + answer4);
System.out.println(" a/y = " + answer5);
28 Prepared by: Melkamu D.
System.out.println("================");
System.out.println("Modulo Operations");
System.out.println(" a%c = "+answer6);
System.out.println(" x%y = "+answer7);

System.out.println("================");
System.out.println("Logical Operations");
System.out.println(" a>b && c>d = "+bool1);
System.out.println(" a<b && c>d = "+bool2);
System.out.println(" a<b || c>d = "+bool3);
System.out.println(" !(a-b==c) = "+bool4);

System.out.println("================");
System.out.println("Bitwise Operations");

29 Prepared by: Melkamu D.


//Shift Operators
int l=8, m=-8,n=2;
System.out.println(" n & 2= "+(n&2));
System.out.println(" l | n= "+(l|n));
System.out.println(" m | n= "+(m|n));
System.out.println(" l >> 2= "+(l>>2));
System.out.println(" l >>> 1= "+(l>>>1));
System.out.println(" l << 1= "+(l<<1));
System.out.println(" m >> 2= "+(m>>2));
System.out.println(" m >>> 1= "+(m>>>1));
System.out.println("\n===== END OF THE PROGRAM
=====");

30 Prepared by: Melkamu D.


POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3; -12

2) What is the value of result?


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

3) What is the value of result?


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

4) What is the value of numCars?


int numBlueCars = 5;
int numGreenCars = 10; 27
int numCars = numGreenCars + ++numBlueCars + +
+numGreeenCars;
31 Prepared by: Melkamu D.
Variables and Primitive Data Types

32 Prepared by: Melkamu D.


Variables
 A variable is an identifier that denotes a storage
location used to store a data value.
 Unlike constants, that remain unchanged during
the execution of a program, a variable may take
different values at different times during the
execution of the program.
 It is good practice to select variable names that
give a good indication of the sort of data they
hold:
 For example, if you want to record the size of a
hat, hatSize is a good choice for a name
whereas qqq would be a bad choice.
33 Prepared by: Melkamu D.
Contd.
 Variable names may consist of alphabets, digits,
the underscore (_) and dollar ($) characters,
subject to the following conditions:
1. They should not begin with a digit.
2. Keywords should not be used as a variable
name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A
rose is not a Rose is not a ROSE.
34 Prepared by: Melkamu D.
5. Variable names can be of any length.
Data Types
 Every variable in Java has a data type.
 Data types specify the size and type of values that
can be stored.
 Java language is rich in the data types.
 Java data types are of two type:
 Primitive Data Types (also called intrinsic or
built-in data types)
 Non-Primitive data Types (also known as
Derived or reference types)
35 Prepared by: Melkamu D.
Data Types in
Java

Non-
Primitive
Primitive
(Intrinsic)
(Derived)

Non- Class Array


Numeric
Numeric es s

Interface
Floating- Charact s
Integer Boolean
Point er

Data Types in Java


36 Prepared by: Melkamu D.
Primitive Data Types
 There are eight built-in data types in Java:
• 4 integer types (byte, short, int, long)
• 2 floating point types (float, double)
• Boolean (boolean)
• Character (char)
 All variables must be declared with a data type
before they are used.
 Each variable's declared type does not change
over the course of the program.

37 Prepared by: Melkamu D.


A. 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 we want to store.

38 Prepared by: Melkamu D.


B. Floating-Point Types
 Integer types can hold only whole numbers and
therefore we need another type known as floating
point type to hold numbers containing fractional
parts.
 There are two data types that can be used to store
decimal values (real numbers).

39 Prepared by: Melkamu D.


C. Character Type
 Is used to store character constants in memory.
 Java provides a character data type called char
 The char data type assumes a size of 2 bytes but,
basically, it can hold only a single character.
 Note that you need to use singular quotation marks
while initializing a variable whose data type is
char.
Example:
char firstLetterOfName = 'e' ;
char
40
myQuestion = '?' ;
Prepared by: Melkamu D.
D. Boolean Type
 Boolean is a data type used when we want to test a
particular condition during the execution of the
program.
 There are only two values that a Boolean can take: true
or false.
 Boolean type is denoted by the keyword boolean and
uses only one bit of storage.
 All comparison operators return boolean type values.
 Boolean values are often used in selection and iteration
statements.
41 Prepared by: Melkamu D.
Size of data type in Java
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

42 Prepared by: Melkamu D.


Declaration of Variables
 After designing suitable variable names, we must declare
them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is

2. It specifies what type of data the variable will hold

3. The place of declaration (in the program) declares the scope of the variable.

 A variable must be declared before it is used in the


program.

 The general form of declaration of Variables is:


type variable1, variable2,...., variableN;

Example:
int count, x,y; //Declaration
char
43 firstLetterOfName = 'e' Prepared
; //by:Declaration
Melkamu D. & initialization
Assigning Values to Variables
 A variable must be given a value after it has been declared

but before it is used in an expression in two ways:


 By using an assignment statement

 By using a read statement

Assignment Statement
 A simple method of giving value to a variable is
through the assignment statement as follows:
variableName = value;
Example: x = 123, y = -34;
 It is possible to assign a value to a variable at the
time of declaration as: type variableName =
value; Prepared by: Melkamu D. 44
Read Statement
 It is also to assign value for variables interactively through
the keyboard using the readLine() method which belongs to
the DataInputStream class.
 The readLine() method reads the input from the keyboard as
a string which is then converted into the corresponding data
type using the data type wrapper classes.
 The wrapper classes are contained in the java.lang package.
 Wrapper classes wrap a value of the primitive types into an
object.
 The keywords try and catch are used to handle any errors
that might occur during the reading process.
45 Prepared by: Melkamu D.
// A program to read data from the Keyboard
import java.io.DataInputStream;
public class Reading{
public static void main(String[] args) {
DataInputStream in = new DataInputStream(System.in);
int intNumber=0;
float floatNumber=0.0f;
double doubleNumber=0.0;
String Name=null;
try{
System.out.println("Enter your Name: ");
Name=in.readLine();
System.out.println("Enter an Integer Number: ");
intNumber=Integer.parseInt(in.readLine());
System.out.println("Enter a float Number: ");
floatNumber=Float.parseFloat(in.readLine());
System.out.println("Enter a Double Number Number: ");
doubleNumber=Double.parseDouble(in.readLine());
}
catch(Exception e){}
System.out.println("Hello : "+Name);
System.out.println("The Integer Number is : "+intNumber);
System.out.println("The Float Number is : "+floatNumber);
System.out.println("The Double Number is :
"+doubleNumber);
}
}
46 Prepared by: Melkamu D.
Scope of Variables
1. Instance Variables: are declared in a class, but outside a
method, constructor or any block.
• are created when an object is created with the use of the key word 'new' and
destroyed when the object is destroyed.

• They take different values for each object

2. Class Variables: are also known as static variables, are declared


with the static keyword in a class, but outside a method,
constructor or a block.
• Are global to a class and belong to the entire set of objects that class creates.

• Only one memory location is created for each class variable.

3. Local Variables: are variables declared and used inside


methods.
• Can also be declared inside program blocks that are define between { and }.
47 Prepared by: Melkamu D.
EN D
T he
! ! !
Yo u
a n k
Th
48 Prepared by: Melkamu D.

You might also like