CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2
CORE JAVA FUNDAMENTALS
ARRAYS
Downloaded from Ktunotes.in
ARRAY
An array is a collection of similar data types.
• Java array is an object which contains elements of a similar data
type.
• The elements of an array are stored in a contiguous memory
location
• The size of an array is fixed and cannot increase to accommodate
more elements
• It is also known as static data structure because size of an array
must be specified at the time of its declaration.
• Array in Java is index-based, the first element of the array is
stored at the 0th index
Downloaded from Ktunotes.in
ARRAYS
Java provides the feature of anonymous arrays which is
not available in C/C++.
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve
or sort the data easily.
• Random access: We can get any data located at any index
position
Downloaded from Ktunotes.in
Disadvantage of Java Array
• Size Limit: We can store the only fixed size of elements in the
array. It doesn't grow its size at runtime. To solve this problem,
collection framework is used in java.
Features of Array
• It is always indexed. The index begins from 0.
• It is a collection of similar data types.
• It occupies a contiguous memory location.
Types of Java Array
• Single Dimensional Array
• Multidimensional Array
Downloaded from Ktunotes.in
Array in java
Array Declaration
Syntax: datatype[ ] arrayname;
Eg: int[ ] arr; //single dimensional array
char[ ] name;
short[ ] arr;
long[ ] arr;
In C program datatype arrayname[];
Downloaded from Ktunotes.in
Initialization of Array
new operator is used to initializing an array.
Eg 1: int[ ] arr = new int[10];
or
int[ ] arr = {10,20,30,40,50};
Eg2: double[] myList = new double[10];
Downloaded from Ktunotes.in
Accessing array element
Example: To access 4th element of a given array
int[ ] arr = {10,24,30,50};
System.out.println("Element at 4th place" + arr[3]);
To find the length of an array, we can use the following syntax:
array_name.length
Example: public class MyClass
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
} Output 4
Downloaded from Ktunotes.in
Loop Through an Array
public class MyClass
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}
}
}
Downloaded from Ktunotes.in
Loop Through an Array with For-Each
public class MyClass
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{
System.out.println(i);
}
}
}
Downloaded from Ktunotes.in
Two Dimensional array
Downloaded from Ktunotes.in
Multi-dimensional Array
Downloaded from Ktunotes.in
CST205 OBJECT
ORIENTED
PROGRAMMING USING
JAVA
MODULE 2- OBJECT ORIENTED
PROGRAMMING IN JAVA
Downloaded from Ktunotes.in
JAVA INNER CLASS
• In Java ,it is also possible to nest
classes (a class within a class).
• The purpose of nested classes is to
group classes that belong together ,
which makes your code more readable
and maintainable.
• To access the inner class, create an
object of the outer class, and then
create an object of the inner class.
• There are two types of nested classes
you can create in Java.
► Non-static nested class (inner class)
► Static nested class
Downloaded from Ktunotes.in
Non –Static Nested (inner)
• A non-static nested class is a class within another class and It is
commonly known as inner class.
► It has access to members of the enclosing class (outer class).
► Since the inner class exists within the outer class, you must
instantiate the outer class first, in order to instantiate the inner class.
► Members of the inner class are known only within the scope of the
inner class and may not be used by the outer class.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
ACCESS CONTROL
• How a member can be accessed is determined by the access modifier
attached to its declaration.
• Java’s access modifiers are public, private, and protected.
• The four access levels are −
► Visible to the package, the default. No modifiers are needed.
► Visible to the class only (private).
► Visible to the world (public).
► Visible to the package and all subclasses (protected).
• When no access modifier is used, then by default the member of a class is
public within its own package, but cannot be accessed outside of its
package.
Downloaded from Ktunotes.in
ACCESS CONTROL
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Static members
• The static keyword in java is
used for memory management
mainly.
• We can apply java static
keyword with variables,
methods, blocks and nested
class.
Downloaded from Ktunotes.in
NON-STATIC VARIABLES
Downloaded from Ktunotes.in
Java static variable
• Static variables are not
associated with objects
► It belongs to class
Syntax
► ClassName.variableName
► Eg: Student.collegeName;
Advantage :
► Makes you program
memory efficient
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Command Line Argument
Sometimes we want to pass information into a program when we run it.
► The information passed is stored in the string array passed to the
main() method and it is stored as a string.
► It is the information that directly follows the program’s name on the
command line when it is running.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Command-Line Arguments
This is accomplished by passing command-line arguments to main().
•The main method can receive string arguments from the command line
•To access the command-line arguments inside a Java program is quite
easy— they are stored as strings in a String array passed to the args
parameter of main().
•The first command-line argument is stored at args[0], the second at
args[1], and so on.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
CST205 OBJECT
ORIENTED
PROGRAMMING USING
JAVA
MODULE 2-OBJECT ORIENTED PROGRAMMING IN
JAVA
Downloaded from Ktunotes.in
CONSTRUCTORS
• A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be
used to set initial values for object attributes
• In the following example, we are creating the no-argument constructor
in the Bike class. It will be invoked at the time of object creation.
• Output:- Bike is created
Downloaded from Ktunotes.in
CONSTRUCTORS
• It can be tedious to initialize all of the variables in a class each time an instance is created.
• Even when you add convenience functions like setDim( )
• It would be simpler and more concise to have all of the setup done at the time the object is first created.
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar to a method.
• Once defined, the constructor is automatically called when the object is created, before the new operator
completes.
• Constructors look a little strange because they have no return type, not even void.
• This is because the implicit return type of a class’ constructor is the class type itself.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
TYPE OF CONSTRUCTOR IN JAVA
• Default Constructor( No-Args constructor)
• Parameterized constructor
Downloaded from Ktunotes.in
DEFAULT CONSTRUCTOR
• If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf.
• This constructor is known as default constructor.
• You would not find it in your source code(the java file) as it would be inserted into the code
during compilation and exists in .class file.
• The default constructor is used to provide the default values to the object like
0,null,etc.,depending on the type.
• Syntax of default constructor:
• <class_name>(){}
Downloaded from Ktunotes.in
DEFAULT CONSTRUCTOR
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
OVERLOADING
• Same name for different
methods/constructors in class as
long as their parameter declarations
are different.
❑ Constructor Overloading
❑ Method Overloading
Downloaded from Ktunotes.in
METHOD OVERLOADING
• •With method overloading, multiple methods can have
the same name with different parameters
• Two or more methods can have same name inside the
same class if they accept different arguments. This
feature is known as method overloading
• •Method overloading is one of the ways that Java
supports polymorphism. There are two ways to
overload the method in java
• By changing number of arguments
• By changing the datatype
Downloaded from Ktunotes.in
ADVANTAGE OF METHOD OVERLOADING
❑The main advantage of this is cleanliness of code.
❑Method overloading increases the readability of the program.
❑Flexibility
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
USING OBJECTS AS PARAMETERS
Although Java is strictly pass by value, the precise effect differs between whether a
primitive type or a reference type is passed.
► While creating a variable of a class type, we only create a reference to an object.
► Thus, when we pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
RECURSION
• Recursion is the technique of making a
method call itself. •
• This technique provides a way to break
complicated problems down into simple
problems which are easier to solve.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
THANK YOU
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
INHERITANCE
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
INHERITANCE
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2
CORE JAVA FUNDAMENTALS
CONTROL STATEMENTS –
ITERATION STATEMENTS,
JUMP STATEMENTS
Downloaded from Ktunotes.in
Iteration Statements (Loop)
• A loop can be used to tell a program to execute
statements repeatedly
• A loop repeatedly executes the same set of instructions
until a termination condition is met.
Downloaded from Ktunotes.in
While Loop
In while loop first checks the condition if the condition is
true then control goes inside the loop body otherwise
goes outside ofthe body.
Syntax
while (condition)
{
// code block to be executed
}
Downloaded from Ktunotes.in
While Loop
Downloaded from Ktunotes.in
While Loop
Downloaded from Ktunotes.in
do...while loop
A do while loop is a control flow statement that executes
a block of code at least once, and then repeatedly
executes the block, or not, depending on a given
condition at the end of the block (in while).
Syntax
do {
// code block to be executed
} while (condition);
Downloaded from Ktunotes.in
do...while loop
Downloaded from Ktunotes.in
Differences
Downloaded from Ktunotes.in
for loop
For Loop is used to execute set of statements repeatedly until
the condition is true.
Syntax
for (initialization; condition; increment/decrement)
{
// code block to be executed
}
Initialization : It executes at once.
Condition : This check until get true.
Increment/Decrement: This is for increment or decrement.
Downloaded from Ktunotes.in
for loop
Downloaded from Ktunotes.in
Enhanced For Loop
For-each or Enhanced For Loop
The for-each loop is used to traverse array or collection
in java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.
Syntax
for (type variableName : arrayName)
{
// code block to be executed
}
Downloaded from Ktunotes.in
Labeled for loop
According to nested loop, if we put break statement in inner loop,
compiler will jump out from inner loop and continue the outer loop
again.
What if we need to jump out from the outer loop using break
statement given inside inner loop? The answer is, we should
define label along with colon(:) sign before loop.
Syntax
labelname:
for(initialization; condition; increment/decrement)
{
//code to be executed
}
Downloaded from Ktunotes.in
Labeled for loop
Downloaded from Ktunotes.in
Jump Statements
Break Statement
The Java break statement is used to break loop or switch
statement
It breaks the current flow of the program at specified
condition
When a break statement is encountered inside a loop, the
loop is immediately terminated and the program control
resumes at the next statement following the loop.
In case of inner loop, it breaks only inner loop.
Downloaded from Ktunotes.in
Jump Statements
Downloaded from Ktunotes.in
Continue Statement
The Java continue statement is used to continue the loop
The continue statement is used in loop control structure
when you need to jump to the next iteration of the loop
immediately
It continues the current flow of the program and skips the
remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
Downloaded from Ktunotes.in
Java Continue Statement
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2-OBJECT ORIENTED
PROGRAMMING IN JAVA
Downloaded from Ktunotes.in
Java is an object-oriented programming language.
It is based on the concept of objects.
These objects share two characteristics:
► state (fields)
JAVA CLASS ► behavior (methods)
AND For example,
OBJECTS ► Lamp is an object
State: on or off
Behavior: turn on or turn off
Downloaded from Ktunotes.in
CLASS
❖A class is a blueprint for the object.
❖It is the logical construct upon which the entire Java
language is built
❖ It defines the shape and nature of an object.
❖ Any concept you wish to implement in a Java
program must be encapsulated within a class.
❖ Class is a template for an object, and an object is an
instance of a class.
Downloaded from Ktunotes.in
Create a Class
How to define a class in Java?
class ClassName { // variables // methods }
Example class Box { double width; double height; double depth};
•To create a class, use the keyword class
Create an Object
•To create an object of MyClass, specify the class name, followed by the
object name, and use the keyword new
The new operator dynamically allocates memory for an object. It has this
general form: class-var = new classname ( );
► Here, class-var is a variable of the class type being created.
► The class name is the name of the class that is being instantiated.
► The class name followed by parentheses specifies the constructor for the
class.
► A constructor defines what occurs and when an object of a class is created
Downloaded from Ktunotes.in
JAVA CLASS ATTRIBUTES
•Class attributes are variables within a class
Example
Create a class called "MyClass" with two attributes x and y
•Another term for class attributes is fields / Data members
Downloaded from Ktunotes.in
Accessing Attributes
•We can access attributes by creating an object of the class, and by using the dot syntax (.)
Example
Create an object called "myObj" and print the value of x
Downloaded from Ktunotes.in
Multiple Objects
•You can create multiple objects of one class
Downloaded from Ktunotes.in
Object Reference
Initialize the object through a reference variable
Downloaded from Ktunotes.in
Using Multiple Classes
•We can also create an object of a class and access it in another class.
•This is often used for better organization of classes
•One class has all the attributes and methods, while the other class holds the
main() method (code to be executed).
•Remember that the name of the java file should match the class name.
•In the following example, we have created two files in the same
directory/folder:
MyClass.java
OtherClass.java
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
ADDING A METHOD TO THE
CLASS
In object-oriented programming, the method is a jargon used
for function.
Methods are bound to a class and they define the behavior of
a class.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2
CORE JAVA FUNDAMENTALS
DATA TYPES, LITERALS &
VARIABLES
Downloaded from Ktunotes.in
DATA TYPES
Variables are reserved memory locations to store values.
Based on the data type of a variable, the Operating System
allocates memory and decides what can be stored in the reserved
memory.
Data type defines the values that a variable can take, for example if
a variable has int data type, it can only take integer values.
Data types specify the different sizes and values that can be stored
in the variable.
The Java Programming Language is strictly typed, which means all
variables must first be declared before they can be used.
There are two types of data types in Java:
Primitive data types
Non-primitive data types
Downloaded from Ktunotes.in
DATA TYPES
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Primitive Data Types-Integer
Downloaded from Ktunotes.in
Primitive Data Types-Integer
Downloaded from Ktunotes.in
Primitive Data Types-Integer
Downloaded from Ktunotes.in
Primitive Data Types-Floating Point
Downloaded from Ktunotes.in
Primitive Data Types-Characters
Downloaded from Ktunotes.in
Primitive Data Types
Downloaded from Ktunotes.in
Example Programs
Downloaded from Ktunotes.in
Example Programs
Downloaded from Ktunotes.in
Literals
Downloaded from Ktunotes.in
Integer Literals
Downloaded from Ktunotes.in
Floating – Point Literals
Downloaded from Ktunotes.in
Character and String Literals
Downloaded from Ktunotes.in
Using Underscore Characters in Numeric Literals
Downloaded from Ktunotes.in
Variables in Java
Variable in Java is a data container that stores the data values
during Java program execution.
Variable is a memory location name of the data.
variable="vary + able" that means its value can be changed.
A variable is defined by the combination of an identifier, type
and an optional initializer.
In order to use a variable in a program we need to perform 2
steps
1. Variable Declaration
2. Variable Initialization
Downloaded from Ktunotes.in
Variables in Java
1. Variable Declaration
Syntax: data_type variable_name ;
Eg: int a,b,c;
float pi;
double d;
2. Variable Initialization
Syntax : data_type variable_name = value;
Eg: int a=2,b=4,c=6;
float pi = 3.14f;
double val = 20.22d;
char a = ’v’;
Downloaded from Ktunotes.in
Variables in Java
Downloaded from Ktunotes.in
Variables in Java- Naming
Downloaded from Ktunotes.in
Types of Variables
1. Local variables - declared inside the method.
2. Instance Variable - declared inside the class but outside
the method.
3. Static variable - declared as with static keyword.
Downloaded from Ktunotes.in
THANK YOU
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2
CORE JAVA FUNDAMENTALS
CONTROL STATEMENTS –
SELECTION STATEMENTS
Downloaded from Ktunotes.in
SELECTION STATEMENTS
Selection statements allow your program to choose different
paths of execution based upon the outcome of an expression
or the state of a variable.
Also called decision making statements
Java supports various selection statements, like if, if-else and
switch
There are various types of if statement in java.
if statement
if-else statement
nested if statement
if-else-if ladder
Downloaded from Ktunotes.in
If statement
Use the if statement to specify a block of Java code to be
executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Downloaded from Ktunotes.in
If statement
Downloaded from Ktunotes.in
if-else Statement
If-else statement also tests the condition. It executes the if
block
if condition is true otherwise else block is executed.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Downloaded from Ktunotes.in
if-else Statement
Downloaded from Ktunotes.in
Nested if-else statement
Downloaded from Ktunotes.in
Nested if-else statement
Downloaded from Ktunotes.in
if else if ladder
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is true
}
Downloaded from Ktunotes.in
if else if ladder
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Switch case
The if statement in java, makes selections based on a
single true or false condition. But switch case have
multiple choice for selection of the statements
It is like if-else-if ladder statement
How Java switch works:
• Matching each expression with case
• Once it match, execute all case from where it matched.
• Use break to exit from switch
• Use default when expression does not match with any
case
Downloaded from Ktunotes.in
Switch case
Downloaded from Ktunotes.in
Switch case
Downloaded from Ktunotes.in
Switch case
Why break is necessary in switch statement ?
• The break statement is used inside the switch to
terminate a statement sequence.
• When a break statement is encountered, execution
branches to the first line of code that follows the entire
switch statement
• This has the effect of jumping out of the switch.
• The break statement is optional. If you omit the break,
execution will continue on into the next case.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
CST 205 OBJECT ORIENTED
PROGRAMMING USING
JAVA
MODULE 2- STRINGS AND VECTOR CLASS
Downloaded from Ktunotes.in
STRINGS
• An object storing a sequence of text characters.
• There are two ways to create a String in Java
• String literal
• String name=“text”;
• Using new keyword
• String str1= new String("Welcome");
Downloaded from Ktunotes.in
DIFFERENCE BETWEEN STRING LITERAL
AND STRING OBJECT
• //using new keyword
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2); //false
• //using literal
String s3 = "Java";
String s4 = "Java";
System.out.println(s3 == s4);//true
Downloaded from Ktunotes.in
STRING LENGTH
• The length of a string is the
number of characters that it
contains. To obtain this value,
call the length( ) method.
Downloaded from Ktunotes.in
STRING CONCATENATION
• + operator concatenates two strings, producing a String object as the
result.
• String Concatenation with Other Data Types
Downloaded from Ktunotes.in
charAt( )
► To extract a single character from a String,
you can refer directly to an individual character
via the charAt( )
► It has this general form: char charAt(intwhere)
CHARACTER ► Here, where is the index of the character that
EXTRACTION you want to obtain.
► The value of where must be nonnegative and
specify a location within the string.
Downloaded from Ktunotes.in
CHARACTER EXTRACTION
getChars( )
► If you need to extract more than one character at a time, you can use the getChars( )
method.
► void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
► sourceStart specifies the index of the beginning of the substring
► sourceEnd specifies an index that is one past the end of the desired substring
► Thus, the substring contains the characters from sourceStart through
sourceEnd–1.
► The array that will receive the characters is specified by target.
► The index within target at which the substring will be copied is passed in
targetStart.
Downloaded from Ktunotes.in
CHARACTER EXTRACTION
toCharArray( )
► If you want to convert all the characters in a String object into a
character array, the easiest way is to call toCharArray( )
► General form: char[ ] toCharArray( )
Downloaded from Ktunotes.in
STRING COMPARISON
equals( ) and equalsIgnoreCase( )
► To compare two strings for equality, use equals( ).
► It has this general form: boolean equals(Object str)
String s1 = "Hello"; String s2 = "Hello"; s1.equals(s2) // true
String s1 = "Hello"; String s2 = “HELLO"; s1.equals(s2) // false
s1.equalsIgnoreCase(s2) // true
Downloaded from Ktunotes.in
startsWith( ) and endsWith( )
► The startsWith( ) method determines whether a given String
STRING begins with a specified string.
COMPARISON ► endsWith( ) determines whether the String in question ends
with a specified string.
► They have the following general forms:
• boolean startsWith(String str)
• boolean endsWith(String str)
• String s1="java string split method”;
System.out.println(s1.startsWith("ja")); // true
System.out.println(s1.startsWith("java string")); // true
String s1="java string split method”;
System.out.println(s1. endsWith(“d")); // true
System.out.println(s1.endsWith("method "));// true
Downloaded from Ktunotes.in
equals() versus ==
• equals( ) method compares the characters inside a String object.
• == operator compares two object references to see whether they refer
to the same instance.
Downloaded from Ktunotes.in
compareTo()
• less than, equal to, or greater than
► A string
► is less than another if it comes before the
other in dictionary order.
► A string is greater than another if it comes
after the other in dictionary order.
Downloaded from Ktunotes.in
SEARCHING STRINGS
• The String class provides two methods that allow you to search a string for a
specified character or substring:
► indexOf( ) Searches for the first occurrence of a character or substring.
► lastIndexOf( ) Searches for the last occurrence of a character or substring.
String s1="this is index of example"; //passing substring int
index1=s1.indexOf("is");//returns the index of is substring int
index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2);
Downloaded from Ktunotes.in
substring()Method
• Used to get the substring of a given string based on the passed indexes.
► String substring(int beginIndex)
► Returns the substring starting from the specified index i.e beginIndex and
extends to the character present at the end of the string.
► String substring(int beginIndex, int endIndex)
► The substring begins at the specified beginIndex and extends to the
character at index endIndex – 1.
► Thus the length of the substring is endIndex-beginIndex.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
VECTOR CLASS IN JAVA
• The Vector class implements a growable array of objects.
► Like an array, it contains components that can be accessed using an
integer index.
► The size of a Vector can grow or shrink as needed to accommodate
adding and removing items after the Vector has been created.
► It is found in the java.util package and implements the List interface,
so we can use all the methods of List interface.
Downloaded from Ktunotes.in
CREATING A VECTOR
• Here is how we can create vectors in Java
Vector<Type> vector = new Vector<>();
• For example // create Integer type linked list
Vector<Integer> vector= new Vector<>();
• // create String type linked list
Vector<String> vector= new Vector<>();
Downloaded from Ktunotes.in
ADD ELEMEMTS
TO VECTOR
❖ add(element) -adds an element to vectors
❖ add(index, element) adds an element to the
specified position
❖ addAll(vector) -adds all elements of a
vector to another vector
• Output
• Vector: [Dog, Horse, Cat]
• New Vector: [Crocodile, Dog, Horse, Cat]
Downloaded from Ktunotes.in
ACCESS VECTOR
ELEMENTS
• get(index) - returns an
element specified by the
index
• iterator() - returns an
iterator object to
sequentially access vector
elements
• Output
• Element at index 2: Cat
Vector: Dog, Horse, Cat,
Downloaded from Ktunotes.in
REMOVE VECTOR
ELEMENTS
• remove(index) - removes an element
from specified position
• removeAll() - removes all the elements
• clear() - removes all elements. It is more
efficient than removeAll()
• Output
• Initial Vector: [Dog, Horse, Cat]
• Removed Element: Horse
• New Vector: [Dog, Cat]
• Vector after clear(): []
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
THANK
YOU
Downloaded from Ktunotes.in
CST205 OBJECT ORIENTED
PROGRAMMING USING JAVA
MODULE 2
CORE JAVA FUNDAMENTALS
TYPE CONVERSION
&
TYPE CASTING,
OPERATORS
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Type casting is when you assign a value of one primitive
data type to another type.
In Java, there are two types of casting:
Implicit conversion
Explicit conversion
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Downloaded from Ktunotes.in
Truncation
When a floating-point value is assigned to an integer type:
truncation takes place, As you know, integers do not have
fractional components
Thus, when a floating-point value is assigned to an integer
type,the fractional component is lost.
For example, if the value 45.12 is assigned to an integer, the
resulting value will simply be 45. The 0.12 will have been
truncated.
No automatic conversions from the numeric types to char or
boolean. Also, char and boolean are not compatible with each
other.
Downloaded from Ktunotes.in
Java Type Casting or Type Conversion
Downloaded from Ktunotes.in
OPERATORS
An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulation.
Java operators can be divided into following categories:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• conditional operator (Ternary)
Unary Operators
Downloaded from Ktunotes.in
Arithmetic Operators
Downloaded from Ktunotes.in
Arithmetic Operators
Downloaded from Ktunotes.in
Arithmetic Operators
Downloaded from Ktunotes.in
Relational Operators
Downloaded from Ktunotes.in
Relational Operators
Downloaded from Ktunotes.in
Unary Operator
Downloaded from Ktunotes.in
Bitwise Operators
Downloaded from Ktunotes.in
Bitwise Operators
Downloaded from Ktunotes.in
Logical Operators
Downloaded from Ktunotes.in
Logical Operators
Downloaded from Ktunotes.in
Assignment Operator
Downloaded from Ktunotes.in
Conditional Operator
Downloaded from Ktunotes.in
Operator Precedence
Downloaded from Ktunotes.in
Operator Precedence
Downloaded from Ktunotes.in
Operator Precedence
Downloaded from Ktunotes.in
Operator Precedence
Downloaded from Ktunotes.in