Lecture 2
Lecture 2
2
What is a Variable in Java?
• The Java variables have mainly three types : Local, Instance and Static.
3
Variable Declaration
• To declare a variable, you must specify the data type & give the variable a
unique name.
5
Variable Initialization
• In this way, a name can only be given to a memory location. It can be
assigned values in two ways:
– Variable Initialization
– Assigning value by taking input
6
Variable Initialization
• datatype: Type of data that can be stored in this variable.
• variable_name: Name given to the variable.
• value: It is the initial value stored in the variable.
• Examples:
– float simpleInterest; //Declaring float variable
– int time = 10, speed = 20; //Declaring and Initializing integer variable
– char var = 'h'; // Declaring and Initializing character variable
7
Naming Convention
• Variables naming convention in java:
1. Variables naming cannot contain white spaces,
for example: int num ber = 100; is invalid because the variable name has
space in it.
2. Variable name can begin with special characters such as $ and _
3. As per the java coding standards the variable name should begin with a
lower case letter, for example int number;
4. For lengthy variables names that has more than one words do it like this:
int smallNumber; int bigNumber; (start the second word with capital letter).
5. Variable names are case sensitive in Java.
8
Types of variables
• In Java, there are three types of variables:
– Local Variables
– Instance Variables
– Static Variables
9
Types of variables
• Local Variables
– Local Variables are a variable that are declared inside the body of a method.
• 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.
• 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.
10
Types of variables
Example to understand the types of variables in java
class A{
int data=50; //instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
}//end of class
11
Data Types in Java
• Data Types in Java are defined as specifiers that allocate different sizes
and types of values that can be stored in the variable or an identifier. Java
has a rich set of data types. Data types in Java can be divided into two
parts :
– Primitive Data Types :- which include integer, character, boolean, and float
– Non-primitive Data Types :- which include classes, arrays and interfaces.
12
Data Types in Java
• There are 8 types of primitive data types:
– boolean data type
– byte data type
– char data type
– short data type
– int data type
– long data type
– float data type
– double data type
13
Data Types in Java
• Boolean Data Type
• The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false
conditions.
14
Data Types in Java
• Short Data Type
• The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive).
• The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.
15
Data Types in Java
• Long Data Type
• The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive).
16
Data Types in Java
• Double Data Type
• The double data type is a double-precision 64-bit. Its value range is
unlimited. The double data type is generally used for decimal values just
like float. The double data type also should never be used for precise
values, such as currency. Its default value is 0.0d.
17
Java Variable Type Conversion &
Type Casting
• A variable of one type can receive the value of another type. Here there
are 2 cases -
18
Java Variable Type Conversion &
Type Casting
• Case 2) Variable of larger capacity is be assigned to another variable of
smaller capacity
• In such cases, you have to explicitly specify the type cast operator. This
process is known as Type Casting.
• In case, you do not specify a type cast operator; the compiler gives an
error. Since this rule is enforced by the compiler, it makes the programmer
aware that the conversion he is about to do may cause some loss in data
and prevents accidental losses. 19
Java Variable Type Conversion &
Type Casting
Example 1 Example 2
20
What are Strings?
• A string in literal terms is a series of characters.
//Representation of String
String strSample_2 = "ROSE";
21
String Concatenation
• Concatenation is joining of two or more strings.
22
String Concatenation
• Check the below code snippet and it explains the two methods to
perform string concatenation.
output:
Length of String: 8
24
String "indexOf" Method
• If I know the length, how would I find which character is in which
position? In short, how will I find the index of a character?
• There is an “indexOf” method that will help you determine the
location of a specific character that you specify.
• Output:
Character at position 5: t
26
String "CompareTo" Method
• How do I compare two Strings?
• Use the method “compareTo” and specify the String that you would
like to compare.
• The result will have the value 0 if the argument string is equal to
this string
• The result will have a value less than 0 if this string is
lexicographically less than the string argument
• The result will have a value greater than 0 if this string is
lexicographically greater than the string argument.
27
String "CompareTo" Method
public class Sample_String{
public static void main(String[] args) {
//Compare to a String
String str_Sample = "RockStar";
System.out.println("Compare To 'ROCKSTAR': " +
str_Sample.compareTo("rockstar")) ;
• Output:
Compare To 'ROCKSTAR': -32
Compare To 'ROCKSTAR' - Case Ignored: 0 28
String "Contain" Method
• How do I confirm if the String contains a sequence of characters I
specify?
• Use the method “contains” and specify the characters you need to
check.
• Returns true if and only if this string contains the specified
sequence of char values.
• Output:
30
EndsWith character 'r': true
String "replaceAll" & "replaceFirst"
Method
• Java String Replace, replaceAll and replaceFirst methods. You can
specify the part of the String you want to replace and the
replacement String in the arguments.
• Output:
Replace 'Rock' with 'Duke': DukeStar
31
String Java "tolowercase" & Java
"touppercase" Method
• I want my entire String to be shown in lower case or Uppercase?
• Just use the “toLowercase()” or “ToUpperCase()” methods against
the Strings that need to be converted.
• Output:
Convert to LowerCase: rockstar
Convert to UpperCase: ROCKSTAR
32
Basic Operators
• Java provides a rich set of operators to manipulate variables. We
can divide all the Java operators into the following groups:
– Arithmetic Operators
– Relational Operators
– Bitwise Operators
– Logical Operators
– Assignment Operators
– Misc Operators
33
Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra. The following table lists
the arithmetic operators:
34
Arithmetic Operators
Operator Description Example
+ (Addition) Adds values on either side of the A + B will give 30
operator.
- (Subtraction) Subtracts right-hand operand from A - B will give -10
left-hand operand.
37
Relational Operators
38
Relational Operators Example
public class Test {
Output
public static void main(String args[]) {
int a = 10; a == b = false
int b = 20; a != b = true
a > b = false
System.out.println("a == b = " + (a == b) ); a < b = true
System.out.println("a != b = " + (a != b) ); b >= a = true
System.out.println("a > b = " + (a > b) ); b <= a = false
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
39
Logical Operators
• The following table lists the logical operators
• Assume Boolean variables A holds true and variable B holds false,
then
40
Logical Operators Example
public class Test {
Output
public static void main(String args[]) {
boolean a = true; a && b = false
boolean b = false; a || b = true
!(a && b) = true
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
41
Assignment Operators
• Following are the assignment operators supported by Java
Operator Description Example
= Simple assignment operator. Assigns values C = A + B will
from right side operands to left side operand. assign value of
A + B into C
+= Add AND assignment operator. It adds right C += A is
operand to the left operand and assign the equivalent to C
result to left operand. =C+A
-= Subtract AND assignment operator. It C -= A is
subtracts right operand from the left operand equivalent to C
and assign the result to left operand. =C–A
*= Multiply AND assignment operator. It C *= A is
multiplies right operand with the left operand equivalent to C
and assign the result to left operand. =C*A
/= Divide AND assignment operator. It divides C /= A is
left operand with the right operand and equivalent to C
42
assign the result to left operand. =C/A
Assignment Operators Example
public class Test {
Output
public static void main(String args[]) {
int a = 10;
int b = 20;
c = a + b = 30
int c = 0; c += a = 40
c = a + b; c -= a = 30
System.out.println("c = a + b = " + c ); c *= a = 300
c += a ;
c /= a = 1
System.out.println("c += a = " + c );
c -= a ; c %= a = 5
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
} 43
}
44
45
46
47