Anda di halaman 1dari 32

Tokens

Smallest individual units in a program


Java program is collection of tokens, comments
and white spaces
Types of tokens:
Keywords
Identifiers
Literals
Operators
Separators

Comments
Comments in a program are called inline
documentation
They should be included to explain the purpose of
the program and describe processing steps
They do not affect how a program works
Java comments can take following forms:
// this comment runs to the end of the line
/*

this comment runs to the terminating


symbol, even across line breaks

*/

White Space
Spaces, blank lines, and tabs are called white
space
White space is used to separate words and
symbols in a program
Extra white space is ignored
Programs should be formatted to enhance
readability, using consistent indentation

Identifiers
Identifiers are the words a programmer uses in a
program
For naming class, methods, variables, objects,
labels, package and interfaces.
An identifier can be made up of letters, digits, the
underscore character ( _ ), and the dollar sign
Identifiers cannot begin with a digit
Java is case sensitive - Total, total, and
TOTAL are different identifiers

keyWords
The Java reserved words: all are in lower case
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double

else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int

interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super

switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while

Literals
Sequence of characters (digits, letters, other
chars)
Types of literals:
Integer
Floating point
Character
String
Boolean
NULL

Operators
Symbol that takes one or more arguments and
operates on them to produce a result

Separators
Symbol used to indicate where codes are divided
and arranged
Parantheses ()
Braces {}
Brackets []
Semicolon ;
Comma ,
Period .

Errors
A program can have three types of errors
The compiler will find syntax errors and other
basic problems (compile-time errors)
If compile-time errors exist, an executable version of the
program is not created

A problem can occur during program execution,


such as trying to divide by zero, which causes a
program to terminate abnormally (run-time errors)
A program may run, but produce incorrect results,
perhaps using an incorrect formula (logical errors)

Constants
A constant is an identifier that is similar to a
variable except that it holds the same value during
its entire existence
As the name implies, it is constant, not variable
The compiler will issue an error if you try to
change the value of a constant
Types of constants
Backslash character constants

Escape Sequences
Some Java escape sequences:
Escape Sequence Meaning
\b
\t
\n
\"
\'
\\

backspace
tab
newline
double quote
single quote
backslash

Constants of a floating-point type can be written


in ordinary decimal fraction form (e.g.,
367000.0 or 0.000589) or in scientific
notation (e.g., 3.67e5 or 5.89e-4)

Constants of type char are expressed by


placing a single character in single
quotes (e.g., 'Z')
Constants for strings of characters are
enclosed by double quotes (e.g.,
"Welcome to Java")
There are only two boolean type
constants, true and false

Note that they must be spelled with all


lowercase letters

Symbolic Constants
Assignment of a symbolic name to constant
E.g.: PASS_MARK
Cannot be declared inside a method, only as class
data member
In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;

Variables
Identifier that denotes a storage location to store a
data value
Every variable in a Java program must be declared
before it is used
A variable declaration tells the compiler what kind of data
(type) will be stored in the variable
The type of the variable is followed by one or more
variable names separated by commas, and terminated
with a semicolon
Variables are generally declared just before they are used
or at the start of a block indicated by an opening brace {
Start the names of variables, classes, methods, and
objects with a lowercase letter, indicate word
boundaries with an uppercase letter, and restrict the
remaining characters to digits and lowercase letters
topSpeed bankRate1 timeOfArrival

Variables
Basic types in Java are called primitive types
Numeric
Integer
Byte
Short
Int
Long
Floating point
Float
Double
Non numeric
Character
Boolean

Non-primitive / derived

Class
Interface
Arrays

Variables [4M]

Scope of Variables
Instance variable
Instance variables belong to an instance of a class.
Another way of saying that is instance variables
belong to an object, since an object is an instance of a
class. Every object has its own copy of the instance
variables.

Class variable
Class variables, however, only have one copy of the
variable(s) shared with all instances of the class.

Local variable
Declared and used inside methods

e.g.:
class Animal(){
private int _numberOfLegs = 4; //instance
variable private static int numberOfAnimals =
0; //class variable
}

Type Casting [4M]


When there is need to store value of one type into
variable of another type
A type cast takes a value of one type and produces
a value of another type with an "equivalent" value
Process of converting one data type into another
is called casting
Used when method returns a type different than
required
Syntax: type var1 = (type) var2;
E.g.:
int m = 50;
long c = (long) m;
If n and m are integers to be divided, and the fractional
portion of the result must be preserved, at least one of
the two must be type cast before the division operation is
performed
double ans = n / (double)m;

Automatic type conversion


It is possible to assign value of one type to
different type without casting
Java does this conversion automatically known as
Only if destination type has enough precession to
store value
E.g: byte b = 45;
int a=b;
Assigning smaller type to a larger one widening
or promotion
Assigning larger type to a smaller one narrowing
may result in loss of info.

More Details About Type Casting


When type casting from a floating-point to an
integer type, the number is truncated, not rounded
(int)2.9 evaluates to 2, not 3

When the value of an integer type is assigned to a


variable of a floating-point type, Java performs an
automatic type cast
double d = 5;

In contrast, it is illegal to place a double value into


an int variable without an explicit type cast
int i = 5.5; // Illegal
int i = (int)5.5 // Correct

Sum of nos, calculate percentage of 4


subjects [4M]

Types of operators

Arithmetic

Relational

Logical

Assignment
=
Shorthand assignment
variable operator=

exp

Increment n Decrement

Conditional
Ternary operator
To decide which value should be assigned to the
variable

Bitwise

A=60
b=13
0011 1100
0000 1101
A&b 00001100 = 12
A<<2
1111 0000 = 240

Special
Instanceof

String name =abc;


boolean res = name instanceof String
Dot
To access instance variables and methods of class
objects

Mathematical functions[4M]

Static double pow(double y, double x)


Static double sqrt(double arg)
Static int max(int x, int y)
Static int min(int x, int y)
Static int round(float arg)

For-each version of for loop[2M]


Automatically cycles thru entire array obtaining
one element at a time in sequence from starting to
end
Syntax:
for(type iteration-var : collection)

Jumps in Loops: Break and continue statements[4M]


Break: Used to stop the entire loop
Can be used within switch, while, do while, for loops
When break is encountered inside loop, loop is
immediately exited and program continues with
statement following the loop
When loops are nested then it will only exit from the
innermost loop
Syntax: break [label];
Example:
int n[]={1,2,3,4,5,6,7,8,9};
for(int i : n){
if(i==4)
break;
S.o.pln(i);
}

Jumps in Loops: Break and continue statements[4M]


continue: causes the loop to be continued with the next
iteration after skipping any statements in b/w
Can be used in any loop control structure
Tells compiler, SKIP FOLLOWING STATEMENTS AND
CONTINUE WITH NEXT ITERATION
For loop: jump to update
while and do/while loop: condition
Syntax: continue [label];
Example:
int n[]={1,2,3,4,5,6,7,8,9};
for(int i : n){
if(i==7)
continue;
S.o.pln(i);
}

Programs [4M]

Reverse of a number/palindrome
Fibonacci series
Factorial of a number
Decimal to Binary
int w=1,d,s=0;
While(n!=0){
d=n%2;
s = d * w + s;
w=w*10;
n=n/2;
}

Sum of digits of number


Print * pattern
Whether entered number is prime or not
Find sum of all prime numbers from 1 to that no.

Anda mungkin juga menyukai