Java 1.3
Java 1.3
Types of Tokens
1. Keywords
2. Identifiers
3. Constant or Literals
4. Operators
5. Special symbols or
Separators
6. Comments
1. Keywords:
These are the pre- Java provides
defined reserved words of the following
any programming language. 50 -52 java
Each keyword has a special keywords:
meaning. It is always written
in lower case.
Some valid identifiers are:
2. Identifier: PhoneNumber
Identifiers are used to name a variable, constant, function, class, and array. It PRICE
usually defined by the user. It uses letters, underscores, or a dollar sign as radius
the first character. Remember that the identifier name must be different a
from the reserved keywords. There are some rules to declare identifiers are: a1
1. The first letter of an identifier must be a letter, underscore or a dollar _phonenumber
sign. It cannot start with digits but may contain digits. $circumference
2. The whitespace cannot be included in the identifier. jagged_array
3. Identifiers are case sensitive. 12radius //invalid
3. Constant or Literals:
It is a notation that represents a fixed value (constant) in the source Literal Type
code. It is defined by the programmer. Once it has been defined cannot 23 int
be changed. Java provides five types of literals are as follows:
1. Integer 9.86 Float, double
2. Floating Point false, true boolean
3. Character
'K', '7', '-' char
4. String
5. Boolean “college" String
null any reference type
4. Operators:
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Unary Operators
5. Logical Operators
6. Ternary Operators
7. Bitwise Operators
8. Shift Operators
Operator Operation
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic + Addition
operations on variables and data. - Subtraction
* Multiplication
For example, a+b;
/ Division
Modulo Operation
%
2. Assignment Operators (Remainder after division)
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
int x = 10;
Expansions for the prefix and postfix shorthand forms 8. b=--a expands to
a = a - 1;
1. a++ expands to 4. --a expands to b = a;
a=a+1; a = a - 1;
9. print(a++)
2. a-- expands to 5. b = a++ expands to print(a)
a = a-1; temp = a; a = a + 1;
a = a + 1;
3. ++a expands to b = temp; 10. print(++a)
a = a+1; a = a + 1;
print(a);
Example 1
Example 2 Example 3
a=5 int a=4;
++a; System.out.println(a--);
System.out.println(--a);
a++; System.out.println(a);
--a;
a--; Output ?
Output ?
Answer
Example 1
(a) Prefix (b) Postfix 5. Java Logical Operators
X= 10 X= 10
Y = X++
Logical operators are used to determine the logic between variables or values:
Y = ++X
Y ? 11 Y ? 10
X ? 11 X ? 11 Operator Name Description Example
(c) Prefix (d) Postfix && Logical and Returns true if both x < 5 && x < 10
X= 10 X= 10 statements are true
Y = --X Y = X--
Y?9 || Logical or Returns true if one of the x < 5 || x < 4
Y ? 10
X?9 statements is true
X?9
! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
Example 2
a=5
++a; // a becomes 6 6. Ternary Operators in Java
a++; // a becomes 7
This operator displays the result based on the condition. The condition
--a; // a becomes 6
a--; // a becomes 5 is an expression that returns a boolean value.
(Condition) ? (Statement1) : (Statement2);
Example 3
int a=4;
System.out.println(a--);
System.out.println(--a);
System.out.println(a);
Ans: 2
Example The operator precedence of
int a = 10, b = 5, c = 1, result; prefix ++ is higher than that
result = a - ++c - ++b; of - subtraction operator
5. Special symbols or Separators:
The separators in Java is also known as punctuators. In Java, there are a few characters that are
used as separators. The most commonly used
separator in Java is the semicolon, it is used to terminate statements.
Symbol Name Purpose
Parentheses Used to contain lists of parameters in method definition and invocation. Also used for
() defining precedence in expressions, containing expressions in control statements, and
surrounding cast types.
Braces Used to contain the values of automatically initialized arrays. Also used to define a
{} block of code, for classes, methods, and local scopes.
Brackets Used to declare array types. Also used when dereferencing array values.
[]
Semicolon Terminates statements.
;
Comma Separates consecutive identifiers in a variable declaration. Also used to chain
, statements together inside a for statement.
Period Used to separate package names from subpackages and classes. Also used to separate a
. variable or method from a reference variable.
6. Comments:
Comments allow us to specify information about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form further processing. The Java compiler treats
comments as whitespaces. Java provides the following two types of comments:
1. Single Line : It begins with a pair of forwarding slashes (//).
2. Multi line: These begin with a /* and end with */. can be several lines long
Single Line comment
System.out.println(i); //printing the variable i
Multi Line comment
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
When you compile a program, the compiler scans the text in the source code
and extracts individual tokens. While tokenizing the source file, the compiler
recognizes and subsequently removes or ignores two things:
2. White spaces :
Java is a free form language which means that there are no specific indentation rules
while writing programs. However, note that there has to be at least one whitespace
character between each token. A whitespace can be a space, a tab or a newline.
Variable in Java is a data container that stores the data values during Java program execution. Every
variable is assigned data type which designates the type and quantity of value it can hold. Variable is a
memory location name of the data.
Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables
int data=10;
int a,b,c;
You can combine variable declaration and initialization.
Types of variables
In Java, there are three types of variables:
1.Local Variables
2.Instance Variables class gcek
3.Static Variables {
static int a = 1; //static variable
void method1()
1) Local Variables {
Local Variables are a variable that are declared int b = 90; //local variable
inside the body of a method. }
}
2) Instance Variables
Instance variables are defined without the
STATIC keyword .They are defined Outside a
method declaration. They are Object specific
and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables. and it
can not be changed
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1.Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
Short(2 byte)
The short data type can store whole numbers from -32768 to 32767 short myNum = 5000;
System.out.println(myNum);
The short data type is a 16-bit signed two's complement integer.
Int(4 byte)
The int data type can store whole numbers from -2147483648 to int myNum = 100000;
2147483647. In general, the int data type is the preferred data type System.out.println(myNum);
when we create variables with a numeric value.
Long(8 byte)
long myNum = 15000000000L;
The long data type is used when int is not large enough to store
System.out.println(myNum);
the value. Note that you should end the value with an "L":
Float
You should use a floating point type whenever you need a number with a decimal, such as
9.99 or 3.14515.
Float(4 byte)
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the
value with an "f":
Double(8 byte)
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
The precision of float is only six
double myNum = 19.99d; or seven decimal digits,
System.out.println(myNum); while double variables have a
precision of about 15 digits.
Char(2 byte)
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c’:
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
char myGrade = 'B’; you can use ASCII char myVar1 = 65,
values to display
System.out.println(myGrade); certain characters: System.out.println(myVar1);
Why char uses 2 byte in java (1 byte in C, C++)
Before Unicode, there were many language
It is because java uses Unicode system not ASCII code system. standards:
Unicode is a universal international standard character encoding •ASCII (American Standard Code for Information
that is capable of representing most of the world's written Interchange) for the United States.
languages. •ISO 8859-1 for Western European Language.
•KOI-8 for Russian.
•GB18030 and BIG-5 for chinese, and so on.
Java supports unsigned 16-bit (2 byte) Unicode characters.
•The char range lies between 0 to 65,535 (inclusive). This caused two problems:
•Its default value is '\u0000'. 1. A particular code value corresponds
to different letters in the various
language standards.
2. The encodings for languages with
large character sets have variable
length. Some common characters are
encoded as single bytes, other require
Strings
two or more byte.
Solution
The String data type is used to store a sequence of characters To solve these problems, a new
(text). String values must be surrounded by double quotes: language standard was developed i.e.
Unicode System.
String greeting = "Hello World"; In unicode, character holds 2 byte, so
System.out.println(greeting); java also uses 2 byte for characters.
lowest value:\u0000
A String in Java is actually a non-primitive data type highest value:\uFFFF
Type casting is a method or process that converts a data type into another data type in both ways
manually and automatically. The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
In Java, there are two types of casting:
1. Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Control flow is the order in which the statements execute. For example, the
program’s flow is usually from top to bottom(Sequential flow), but what if we
want a particular block of code to only be executed when it fulfills a specific
condition or wants to run a block of the code a specified number of times?
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Syntax: public class IfDemo1
1.1 If {
public static void main(String[] args)
if(condition) {
{ int marks=70;
// Statements to execute if if(marks > 65)
// condition is true {
} System.out.print("First division");
}
}
}
if(condition1)
{ //code for if condition1 is true
}
else if(condition2)
{ //code for if condition2 is true
}
else if(condition3)
{ //code for if condition3 is true
}
...
else { //code if all conditions are false
} Question:
1. Write a program to find greatest among 3 numbers
WAP to print Grade by using marks of a student
Example:
while loop
WAP to print first 3
numbers using for loop SYNTAX:
Break
In Java, break is majorly used for:
• Terminate a sequence in a switch statement.
• To exit a loop. Using break we can leave a loop even if the condition for its
end is not fulfilled.
• The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
WAP using break inside the loop, the loop will terminate when the value is 3.
For example, if we want to store the employee ID of 100 people then we can create an array of the int type
int empid [ ];
To create an array of integers, you could write:
int empid[] = {10, 20, 30, 40};
we have created an array named age and initialized it with the values by ANY two ways
(A) using the ARRAY index number (B) inside the curly brackets.
// initialize array Note that we have not provided the size of the array.
age[0] = 12; In this case, the Java compiler automatically specifies
age[1] = 4; the size by counting the number of elements in the
age[2] = 5; array (i.e. 5).
Write a program in java to show the access of array elements and length of array
public class arrayx
{
public static void main(String[] args)
{
// create an array
int[] age = {12, 4, 5, 2, 5};
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
Syntax to Declare an 1D Array in Java a[4]=50;
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70; Output:
a[3]=40; 10
a[4]=50; 20
70
40
for(int i=0;i<a.length;i++)//length is the property of array 50
System.out.println(a[i]);
}
}
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form)
int[][] arr=new int[3][3];//3 row and 3 column Program to print elements of 2Dimensional array.
The Scanner class is one of the simplest ways to get user input in Java. This class provides several built-
in methods to get the input of various types like int and float. Here, we used the nextInt() method to
get the int type of the input:
import java.io.BufferedReader;
import java.io.InputStreamReader; Here, the readLine()
public class Test method reads the user
{ input and returns a
public static void main(String[] args) string as a result
{
//make object using BufferReader
BufferedReader myobj =
new BufferedReader(new InputStreamReader(System.in));
2.Explain
SCANNER and BUFFEREDREADER class in java?
Why they are used?