Scanner Class in Java
Scanner is a class in java.util package
used for obtaining the input of the primitive types like int, double etc.
and strings.
It is the easiest way to read input in a Java program
To create an object of Scanner class, we usually pass the predefined
object System.in, which represents the standard input stream.
Syntax:
Scanner <<ref>> = new Scanner(<<input-ref>>);
Ex: Scanner scan = new Scanner(System.in);
Methods defined in Scaner class:
Integer Group
Return Type Method Name
byte nextByte( )
short nextShort( )
int nextInt( )
long nextLong( )
Float Group
Return Type Method Name
Float nextFloat( )
Double nextDouble( )
Character Group
Return Type Method Name
char next( ).charAt(0)
Boolean Group
Return Type Method Name
boolean nextBoolean( )
Java Tokens
Tokens are the various Java program elements which are identified by the
compiler.
A token is the smallest element of a program that is meaningful to the
compiler.
Tokens supported in Java include
o keywords
o Identifiers
o constants
Keywords
Note:
If we use goto or const keywords in java then it raises COMPILE TIME
ERROR
Used Words in Java
Data Flow Modifiers Exception Class Object Return
types Controls Handling Related Related type
Byte If public try class new enum(1.5) void
Short Else private catch interface this
Int Switch protected finally package super
Long Case static throw import instanceof
Float Default final throws extends
double For Abstract Assert implements
(1.6)
Char While Native
boolean Do synchronized
Break Volatile
Continue Transient
Return strictfp
Examples
class FundaDemo {
public static void main(String[] args)
{ int String = 10;
System.out.println(String);
}
O/P:- 10
Which of the following are valid java Reserved words ?
1) int, float, signed, double
2) abstract, final, volatile, virtual
3) new, delete
4) goto, constant, static 5) byte, short, int, long
Answer: (5)
Literals or Constants
• Integral Literals
– Decimal literals:
allowed digits are 0 to 9 Ex: int x = 10;
– Octal literals:
allowed digits are 0 to 7 but here literal value should be prefixed
with 0(zero) Ex: int x = 010;
– Hexadecimal literals:
The allowed digits are 0 to 9, A- F (Both lower, Upper case)
literals should be prefixed with 0x or oX Ex: int x = 0x10;
• Character Literal
– A char literal can be represented as a single character with in
single quotes.
Ex: char ch = 'a';
char ch = 'ab'; C.E: unclosed character literal.
char ch = a; --- Invalid
we can represent a char literal by using it’s Unicode value.
For the allowed Unicode values are 0 to 65535.
Ex:
char ch = 97;
System.out.println(ch); Output: a
char ch = 65535;
char ch = 65536; //C.E : possible loss of precision found : int
required :char
we can represent a char literal by using Unicode representation
which is nothing but \uxxxx’
Ex: char ch = '\u0061'
System.out.println(ch); Output:a
char ch = '\ubeef';
char ch = '\uface';
char ch = '\iface'; -Invalid
char ch = '\uface'; Invalid
we can also represent a char literal by using escape character.
Ex: char ch = '\b';
char ch = '\n';
char ch = '\l';
\b backspace
\n new line
\r carriage return
\f formfeed
\t horizontal tab
\’ single quote
\” double quote
\\ back slash
• String Literal
– A sequence of character with in double quotes is String literal.
New Features in Java 1.7
1. Binary --- 0B or 0b (Introduced in Java 1.7)
2. Usage of _ symbol in Integer literals.
Ex:1_23_456(increases the readibulity)
Identifiers
A name in java is called as Identifier.
An identifier can be a
o Class name
o Variable name
o Array name
o Method name
Rules to define an Identifier:
Identifier must begin with
o a letter (A-Z, a-z, or any other language letters supported by
UFT 16)
o An underscore (_)
o A dollar ($)
after which it can be sequence of letters/digits.
Digits: 0-9 or any Unicode that represents digit.
Length of the variable name is unlimited
Java reserved words should not be used as variable names.
Must begin with lower case
Must always begin your variable names with a letter, not "$" or "_".
Avoid abbreviations, use meaningful names.
If a variable consists of two or more words, then the second and
subsequent words should start with upper case.
Which of the following are valid Identifiers
1) total#
2) all@hands
3) 123total
4) break
5) String
6) total_number
7) $_$
8) $ca$h
Valid: (5) to (8)
Control Statements
Selection Statements
Java supports two selection statements:
if and switch.
In addition, the (? :) operator is an alternative to if in certain circumstances.
If Statement
The general form of the if statement is
If(expression)
statement;
[else
statement;]
Here a statement may consist of a single statement, a block of statements, or nothing. The else
clause is optional.
If expression evaluates to true , the statement or block that forms the target of if is executed,
otherwise the statement after the target of else is
executed, if it exists.
If Ladder
If we have several groups of statements and
one of the group is to be executed selectively specify
that intension by using if Ladder or switch in some
cases.
Syntax
if(expression)
statement;
else if(expression)
statement;
else if(expression)
statement;
.
.
.
else statement;
The conditions are evaluated from the top
downward. As soon as a true condition is found,
the statement associated with it is executed and
the rest of ladder is bypassed. If none of the
conditions are true, the final else is executed. If
the final else is not present, no action takes
place if all other conditions are false.
switch
java has a built-in multiple-branch selection statement, called switch, which successively test
the value of an expression against list of integer or character constant. When a match is found, the
statements associated with that constants are executed. The general form of switch statement is
switch(expression)
{
case constant1:
statement sequence
[break];
case constant2:
statement sequence
[break];
case constant3:
statement sequence
[break];
.
.
default:
statement sequence;
}
The expression must be evaluated to an integer type thus we can use character or integer values,
but floating point expressions, for example, are not allowed.
The value of the expression is tested against the values, one after another, of the constants specified
in the case statements. When a match is found, the statement sequence associated with that case is
executed until the break statement or the end of the switch statement is reached. The default
statement is executed if no matches are found. The default is optional, and if it is not present, no
action takes place if all matches fail.
There are the three important things to know about the switch statement:
The switch differs from if in that switch can only in equality, where as if can evaluate any
type of relational or logical expression.
No two case constants in the same switch can have identical values. If character constants
are used in the switch statement, they are automatically converted to integers.
Iteration statements
You do these things repeatedly, we can specify to the system by using one of the four repetition
statements:
1. while loop
2. do-while loop
3. for loop
4. foreach loop
The while loop
The general form is
while(condition)
statement;
Here statement may be an empty statement, a single statement, or a block of statements. The
condition must be boolean expression. The loop iterates while the condition is true. When the
condition becomes false, program control passes to the line of the code immediately following the
loop. Since we are checking the condition at the entrance there is no guarantee of the execution of
the loop body at least once. If loop is to be executed at least once use do-while instead of while.
The do-while loop
The general form of the do-while loop is
do
{
Statement;
}while(condition);
The do-while loop iterates until condition becomes false.
The do-while loop checks its condition at the bottom of the loop. This means that the do-while
always executes at least once.
The for loop
You do these things repeatedly varying so and so variable value from so and so to so with increment
or decrement so and so ,to specify use for statement.
The general form of for loop is
for(Initialization; Condition; Increment)
{
//statements
}
To display first fifteen numbers
for(int no=1;no<=15;no++)
{
printf(“%d “,no);
}
Jump Statements
Java has three statements that perform an unconditional branching:
return
break
continue
You can use return anywhere inside the function. You can use break and continue
statements inside any of the loop statements. You can also use break with switch.
The return statement
You return this value back to the calling area ,we can specify to the system by using return
statement. The general form is
return value / expression;
The second form
return;
The break Statement
The break statement has two uses
1. To break the switch
2. To break the loop
The general form
break [label];
The continue Statement
To opt for the early iteration use it.
General form
continue [label];
for (int i=1;i<=10; i++)
System.out.print(i+ “ “);
if(i%2 !=0 ) continue;
System.out.println();