Module 1 New
Module 1 New
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,
• 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;
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;
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;
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';
• 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..
Output:
22
21
Cont..
• Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
• 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
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.
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:
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
}
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
}
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);
}
}
• 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
+= 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;
• 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.
• 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.
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);
}
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.*;