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

Module 1 New

Uploaded by

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

Module 1 New

Uploaded by

sumanthcm.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Module-1

Tokens in Java
• Tokens are the various elements in the java program that are identified by Java compiler. A
token is the smallest individual element (unit) in a program that is meaningful to the compiler.

• In simple words, a java program is a group of tokens, comments, and white spaces. For example,

• consider the below java statements:


final double p = 3.14 // A constant.
x = a + b; // An expression.
v = Math.pow(10, 1); // An inbuilt java function.

• Java language contains five types of tokens that are as follows:


1. Keywords
2. Identifiers
3. Literals
4. Special Symbols
5. Operators
Keywords
• Keywords are reserved words in programming languages. These are used to indicate
predefined terms and actions in a program.
• Keywords are not allowed to be used as names of variables or objects.
• Keywords are case-sensitive and always written in lowercase.
• Java has the following keywords:
Identifiers
• A method name, class name, variable name, or label is an identifier in Java. The user
typically defines these.
• The identifier names cannot be the same as any reserved keyword.
• Let's see an example to understand identifiers:
public class Test {
public static void main(String[]args)
{
int num = 10;
}
}
Identifiers present in the above program are:
Test: The name of the class.
main: The name of a method.
String: A predefined class name.
args: A variable name.
num: A variable name.
Cont..

Rules for naming identifiers.

• The characters allowed are [A-Z], [a-z], [0-9], _ and $.

• Identifiers are case-sensitive.


• That is, “java” is not the same as “JAVA”.

• Identifier names should not start with a digit.


• For example, “007IamFine” is an invalid identifier.

• Whitespace is not allowed inside an identifier.

• Keywords can’t be used as an identifier.


Literals
• Literals represent fixed values in a source code. These are similar to standard variables with the difference
that these are constant.

• These can be classified as an integer literal, a string literal, a boolean etc.

• The user defines these mainly to define constants.

• Syntax to define literals:

final data_type variable_name;

• There are five types of literals in Java:

• Integer
• Floating Point
• Boolean
• Character
• String
Example-1:
public class JavaIntegerLiterals {
public static void main (String[]args){
//initialize variables with integer literals
int decimalNum = 25;
int hexaNum = 0xa5;
int binaryNum = 0b1101;
int octalNum = 0172;

//print out the values of the literal


System.out.println("Decimal Integer: " + decimalNum);
System.out.println("Octal Integer: " + octalNum);
System.out.println("Hexadecimal Integer: " + hexaNum);
System.out.println("Binary Integer: " + binaryNum);
}
}

Output
Decimal Integer: 25
Octal Integer: 122
Hexadecimal Integer: 165
Binary Integer: 13
Example-2:
public class JavaBooleanLiterals {
public static void main(String[] args) {
boolean isTrue = true;
boolean isFalse =false;

System.out.println("The boolean value of isTrue: " + isTrue);


System.out.println("The boolean value of isFalse: " + isFalse);
}
}

Output
The boolean value of isTrue: true
The boolean value of isFalse: false
Example-3:
public class JavaFloatLiterals {
public static void main(String[] args) {
double piDoubleValue = 3.1415926535;
float piFloatValue = 3.1415926535F;
double piScientific = 3.1415926535e0;

System.out.println("Pi to ten decimal places: " + piDoubleValue);


System.out.println("A rounded value of Pi: " + piFloatValue);
System.out.println("Pi from a scientific notation: " + piScientific);
}
}

Output
Pi to ten decimal places: 3.1415926535
A rounded value of Pi: 3.1415927
Pi from a scientific notation: 3.1415926535
Example-4:
public class JavaCharLiterals {
public static void main(String[] args) {
char myFirstChar = 'a';
char mySecondChar = 'b';
char myThirdChar = 'c';
char plusInUnicode = '\u002b';

System.out.println("First three letters of the alphabet: "


+ myFirstChar + mySecondChar + myThirdChar);

//Escape sequence as character literals


System.out.println("The same three characters on separate lines: "
+ "\n" + myFirstChar
+ "\n\t" + mySecondChar
+ "\n" +myThirdChar);

//Unicode character literal


System.out.println("Letter a added to letter b: " +
myFirstChar + plusInUnicode + mySecondChar); Output
} First three letters of the alphabet: abc
} The same three characters on separate lines:
a
b
c
Letter a added to letter b: a+b
Operators in Java
• Operator in Java is a symbol that is used to perform operations.
• For example: +, -, *, / etc.
• There are many types of operators in Java which are given below:
• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Java Unary Operator

• The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
• incrementing/decrementing a value by one
• negating an expression
• inverting the value of a Boolean
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11) Output:
System.out.println(++x);//12 10
12
System.out.println(x--);//12 (11) 12
System.out.println(--x);//10 10
}
}
Cont..

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);
}
}

Output:
22
21
Cont..

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}
}
Output:
-11
9
false
true
Java Arithmetic Operator

• Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
System.out.println(10*10/5+3-1*4/2); // 21
}
}
Java Relational Operators

• Relational operators are used to check the relationship between two operands.
• It returns either true or false.
• Relational operators are used in decision making and loops.
Operator Description Example
== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
Greater Than or Equal
>= 3 >= 5 returns false
To

<= Less Than or Equal To 3 <= 5 returns true


Java Relational Operators: Example

class RelationalOperators {
public static void main(String[] args) {

int a = 7, b = 11;
System.out.println("a is " + a + " and b is " + b);
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a < b); // true
System.out.println(a >= b); // false
System.out.println(a <= b); // true
}
}
Java Logical Operators

• Logical operators are used to check whether an expression is true or false. They are used
in decision making.
• It returns either true or false.

Operator Example Meaning


true only if both
&& (Logical AND) expression1 & expression2 expression1 and
expression2 are true
true if either
|| (Logical OR) expression1 | expression2 expression1 or
expression2 is true
true if expression is
! (Logical NOT) !expression
false and vice versa
Java Logical Operators: Example

class LogicalOperators {
public static void main(String[] args) {
// && operator
System.out.println((5 > 3) & (8 > 5)); // true
System.out.println((8<5)&(5 > 3)); // false

// || operator
System.out.println((5 < 3) | (8 > 5)); // true
System.out.println((5 > 3) | (8 < 5)); // true
System.out.println((5 < 3) | (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Short-Circuit Logical Operators:

• Java supports Short-circuit logical operators


• Short-circuit AND operator is &&
• Short-circuit OR operator is ||
• The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
• The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
Short-Circuit Logical Operators: Example

class ShortCircuitLogicalOperators {
public static void main(String[] args) {
int n,d,q;
n=10;
d=2;
if(d!=0 && (n%d)==0)
System.out.println(d+” is a factor of “+n);
d=0;
// since d is zero, second operand is not evaluated
if(d!=0 && (n%d)==0)
System.out.println(d+” is a factor of “+n);
else
System.out.println(d+” is not a factor of “+n);
// Now, try same thing without short-circuit operator
this cause a divide-by-zero error
if(d!=0 & (n%d)==0)
System.out.println(d+” is a factor of “+n);
}
}
Short-Circuit Logical Operators: Example

public class ShortCircuitAndOperatorExample {


public static void main(String[] args) {
int a = 4;
int b = 5;
if (a > 5 && b < 10) {
System.out.println("Both conditions are true.");
}
else {
System.out.println("At least one condition is false.");

}
if (b > 5 || b > 10) {
System.out.println("At least one condition is true.");
}
else {
System.out.println("Both conditions are false.");
}
}
}
Short-Circuit Logical Operators: Example

public class ShortCircuitAndOperatorExample {


public static void main(String[] args) {
int a = 4;
int b = 5; Output:
if (a++ > 5 && ++b < 10) { a=5 b=5
System.out.println("Both conditions are true.");

}
System.out.println("a="+a+" b="+b);
}
public class ShortCircuitAndOperatorExample {
} public static void main(String[] args) {
int a = 4;
int b = 5; Output:
if (a++ > 5 || ++b > 10) { a=5 b=6
System.out.println("Both conditions are false.");
}
System.out.println("a="+a+" b="+b);
}
}
Java Ternary Operator (? :)

• The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
Here's how it works.
• If the Expression is true, expression1 is assigned to the variable.
• If the Expression is false, expression2 is assigned to the variable.
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}

Output: Leap year


Java Assignment Operators

• Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is
assigned to the variable age

Operator Example Equivalent to


= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;
Java Assignment Operators: Example

class Main {
public static void main(String[] args) {
// create variables
int a = 4;
int var;

// assign value using = Output:


var = a; var using =: 4
System.out.println("var using =: " + var);
var using +=: 8
// assign value using =+ var using *=: 32
var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Java instanceof Operator

• The instanceof operator checks whether an object is an instanceof a particular


class.
class Main {
public static void main(String[] args) {

String str = "Program";


boolean result;

// checks if str is an instance of the String class


result = str instanceof String;
System.out.println("Is str an object of String?"+result);
}
}
Output:
Is str an object of String? true
Java Left Shift Operator

• The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Java Right Shift Operator

• The Java right shift operator >> is used to move the value of the left operand to right by
the number of bits specified by the right operand.

public class OperatorExample{


public static void main(String args[]){
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
Java Variables
• A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
• Variable is a name of memory location.
• Variable value can be changed.

datatype variable [ = value][, variable [ = value] ...] ;


Local Variables
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.
Example: Here, age is a local variable. This is defined inside pupAge() method and its
scope is limited to only this method.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}

Output
Puppy age is: 7
Example: Following example uses age without initializing it, so it would give an error at
the time of compilation.
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}

Output
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
Instance Variables
• Instance variables are declared with in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap, a slot for each instance variable value is created.
• Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor or
block, or essential parts of an object's state that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class. Normally, it is
recommended to make these variables private (access level). However, visibility for subclasses can
be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers, the default value is 0, for Booleans it is
false, and for object references it is null. Values can be assigned during the declaration or within the
constructor.
• Instance variables can be accessed directly by calling the variable name inside the class. However,
within static methods (when instance variables are given accessibility), they should be called using
the fully qualified name. ObjectReference.VariableName.
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) {
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal;
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
} Output
public static void main(String args[]) { name : Suchith
Employee empOne = new Employee(“Suchith"); salary :10000.0
empOne.setSalary(10000);
empOne.printEmp();
}
}
Class/Static Variables
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are variables
that are declared as public/private, final, and static. Constant variables never change from
their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
• Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
• Static variables can be accessed by calling with the class name ClassName.VariableName.
• When declaring class variables as public static final, then variable names (constants) are all
in upper case. If the static variables are not public and final, the naming syntax is the same
as instance and local variables.
import java.io.*;

public class Employee {

// salary variable is a private static variable


private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
Output
Development average salary:1000

You might also like