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

Lecture 2

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

Lecture 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Lecture 2:

Variables, Data Types, String and


String Manipulation in-built
functions, Operators

Object Oriented Programming


1
What is a Variable in Java?
• 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.

• A variable is a name given to a memory location. It is the basic unit of


storage in a program.
– The value stored in a variable can be changed during program execution.
– A variable is only a name given to a memory location, all the operations done
on the variable effects that memory location.
– In Java, all the variables must be declared before use.

2
What is a Variable in Java?
• The Java variables have mainly three types : Local, Instance and Static.

• In order to use a variable in a program you to need to perform 2 steps


– Variable Declaration
– Variable Initialization

3
Variable Declaration
• To declare a variable, you must specify the data type & give the variable a
unique name.

• type: Type of data that can be stored in this variable.


• name: Name given to the variable.

• Examples of other Valid Declarations are


– int a,b,c;
– float pi;
– double d;
– char a;
4
Assigning value to a variable
• Variable Initialization:
• To initialize a variable, you must assign it a valid value.

• Assigning value to a variable

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.

• Primitive Data Types


– Primitive Data Types are predefined and available within the Java language.
Primitive values do not share state with other primitive values.

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.

• Example: Boolean one = false

• Byte Data Type


• The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.

• Example: byte a = 10, byte b = -20

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).

• Example: short s = 10000, short r = -5000

• Int Data Type


• The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive).

• The int data type is generally used as a default data type for integral
values unless if there is no problem about memory.

• Example: int a = 100000, int b = -200000

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).

• Example: long a = 100000L, long b = -200000L

• Float Data Type


• The float data type is a single-precision 32-bit. Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type
should never be used for precise values, such as currency.

• Example: float f1 = 234.5f

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.

• Example: double d1 = 12.3

• Char Data Type


• 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.

• Example: char letterA = 'A'

17
Java Variable Type Conversion &
Type Casting
• A variable of one type can receive the value of another type. Here there
are 2 cases -

• Case 1) Variable of smaller capacity is be assigned to another variable of


bigger capacity.

• This process is Automatic, and non-explicit is known as Conversion

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

class Simple{ class Simple{


public static void main(String[] args){ public static void main(String[] args){
int a=10; float f=10.5f;
float f=a; //int a=f;//Compile time error
System.out.println(a); int a=(int)f;
System.out.println(f); System.out.println(f);
} System.out.println(a);
} }
Output: }
10 Output:
10.0 10.5
10

20
What are Strings?
• A string in literal terms is a series of characters.

• we can define the String in Java as follows:

//Representation of String
String strSample_2 = "ROSE";

21
String Concatenation
• Concatenation is joining of two or more strings.

• We have two strings str1 = “Rock” and str2 = “Star”

• If we add up these two strings, we should have a result as str3=


“RockStar”.

22
String Concatenation
• Check the below code snippet and it explains the two methods to
perform string concatenation.

public class Sample_String{


public static void main(String[] args){
//String Concatenation
String str1 = "Rock";
String str2 = "Star";
//Method 1 : Using concat
String str3 = str1.concat(str2);
System.out.println(str3);
//Method 2 : Using "+" operator
String str4 = str1 + str2;
System.out.println(str4);
}
}
• First is using “concat” method of String class and second is using
23
arithmetic “+” operator. Both results in the same output
String "Length" Method
• How will you determine the length of given String?
• Here is a method called as “length”. Use it against the String you
need to find the length.

public class Sample_String{


public static void main(String[] args){
String str_Sample = "RockStar";
//Length of a String
System.out.println("Length of String: " + str_Sample.length());
}
}

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.

public class Sample_String{


public static void main(String[] args){
System.out.println("Character at position 5: " + str_Sample.charAt(5));
//Index of a given character
System.out.println("Index of character 'S': " + str_Sample.indexOf('S'));
}
}
• Output:
Character at position 5: t
Index of character 'S': 4
25
String "charAt" Method
• Similar to the above, given the index, how do I know the character
at that location?
• Simple one again!! Use the “charAt” method and provide the index
whose character you need to find.

public class Sample_String{


public static void main(String[] args){//Character at position
String str_Sample = "RockStar";
System.out.println("Character at position 5: " + str_Sample.charAt(5));
}
}

• 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.

• Use “compareToIgnoreCase” in case you don’t want the result to


be case sensitive.

• 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")) ;

//Compare to - Ignore case


System.out.println("Compare To 'ROCKSTAR' - Case Ignored: " +
str_Sample.compareToIgnoreCase("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.

public class Sample_String{


public static void main(String[] args){
//Check if String contains a sequence
String str_tes = "RockStar";
System.out.println("Contains sequence 'tar': " + str_tes.contains("tar"));
}
}
• Output:
29
• Contains sequence 'tar': true
String "endsWith" Method
• How do I confirm if a String ends with a particular suffix? Use the
“endsWith” method and specify the suffix in the arguments.

• It returns true if the character sequence represented by the


argument is a suffix of the character sequence represented by this
object.

public class Sample_String{


public static void main(String[] args){
//Check if ends with a particular sequence
String str_tes = "RockStar";
System.out.println("EndsWith character 'r': " + str_tes.endsWith("r"));
}}

• ​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.

public class Sample_String{


public static void main(String[] args){
//Replace Rock with the word Duke
String str_test = "RockStar";
System.out.println("Replace 'Rock' with 'Duke': " + str_test.replace("Rock",
"Duke"));}}

• ​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.

public class Sample_String{


public static void main(String[] args){
//Convert to LowerCase
String str_test = "RockStar";
System.out.println("Convert to LowerCase: " + str_test.toLowerCase());
//Convert to UpperCase
System.out.println("Convert to UpperCase: " + str_test.toUpperCase());}}

• 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:

• Assume integer variable A holds 10 and variable B holds 20, then

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.

* (Multiplication) Multiplies values on either side of A * B will give 200


the operator.
/ (Division) Divides left-hand operand by right- B / A will give 2
hand operand.
% (Modulus) Divides left-hand operand by right- B % A will give 0
hand operand and returns
remainder.
++ (Increment) Increases the value of operand by B++ gives 21
1.
-- (Decrement) Decreases the value of operand by B-- gives 19
1. 35
Arithmetic Operators Example
public class Test {
Output
public static void main(String args[]) {
int a = 10; a + b = 30
int b = 20; a - b = -10
int c = 25; a * b = 200
int d = 25;
b/a=2
b%a=0
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) ); c%a=5
System.out.println("a * b = " + (a * b) ); a++ = 10
System.out.println("b / a = " + (b / a) ); b-- = 11
System.out.println("b % a = " + (b % a) ); d++ = 25
System.out.println("c % a = " + (c % a) ); ++d = 27
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );

// Check the difference in d++ and ++d


System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
} 36
}
Relational Operators
• There are following relational operators supported by Java
language.
• Assume variable A holds 10 and variable B holds 20, then

Operator Description Example


== (equal to) Checks if the values of two operands (A == B) is not
are equal or not, if yes then condition true.
becomes true.
!= (not equal to) Checks if the values of two operands (A != B) is
are equal or not, if values are not equal true.
then condition becomes true.
> (greater than) Checks if the value of left operand is (A > B) is not
greater than the value of right operand, true.
if yes then condition becomes true.

37
Relational Operators

Operator Description Example


< (less than) Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= (greater than or Checks if the value of left operand is (A >= B) is not
equal to) greater than or equal to the value of true.
right operand, if yes then condition
becomes true.
<= (less than or Checks if the value of left operand is (A <= B) is
equal to) less than or equal to the value of right true
operand, if yes then condition becomes
true.

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

Operator Description Example


&& (logical and) Called Logical AND operator. If both the (A && B) is
operands are non-zero, then the false
condition becomes true.
|| (logical or) Called Logical OR Operator. If any of (A || B) is true
the two operands are non-zero, then the
condition becomes true.
! (logical not) Called Logical NOT Operator. Use to !(A && B) is
reverses the logical state of its operand. true
If a condition is true then Logical NOT
operator will make false.

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

You might also like