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

UNIT-1

Java is a widely-used programming language and platform, created in 1991 and publicly released in 1995, with applications ranging from desktop to web and enterprise systems. It features object-oriented programming principles such as inheritance, polymorphism, and encapsulation, and is known for its platform independence and security. Java programs are created using classes and objects, and can be executed in a variety of environments after compiling the source code.

Uploaded by

m.balakrishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

UNIT-1

Java is a widely-used programming language and platform, created in 1991 and publicly released in 1995, with applications ranging from desktop to web and enterprise systems. It features object-oriented programming principles such as inheritance, polymorphism, and encapsulation, and is known for its platform independence and security. Java programs are created using classes and objects, and can be executed in a variety of environments after compiling the source code.

Uploaded by

m.balakrishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 176

INTRODUCTION TO

JAVA
What is java

• Java is a programming language and a platform.


• It is a most popular programming language created in 1991,publicly
released by 1995.
Where it is used?
• According to sun,3 billion devices run java.There are many devices
where java is currently used. some of them are as follows.
• 1.Desktop Applications
• 2. Web Applications
• 3.Enterprise Applications
• 4.Robotics
• 5.Games
History of Java
• Currently java is used in internet programming ,mobile devices,games.
• James gosling,Mike Sheridan,and Patrick Naughton initiated the java
language project in June 1991.
• The small team of sun engineers called Green Team
• Originally designed for small,embedded systems in electronic
appliances like set-top boxes.
• Firstly it was called “greentalk” by james gosling and file extension
was .gt
• After that it was called oak and was developed as apart of the green
project
Why oak name for java language?

• Oak is a symbol of strength and choosen as a national tree of many


countries like U.S.A, France, Germany, Romania.
• In 1995 oak was renamed as java because it was already a trademark
by oak technologies.
Why java name for java language ?
• Java is an island of Indonesia where first coffee was produced(called
java coffee)
• Originally developed by james gosling at sun micro systems and
released in the year 1995.
• JDK 1.0 released in (jan 23 1996)
Features of java

• There are many features of java. They are also known as java buzz
words.
simple
• According to sun,java language is simple because:
• Syntax is based on c++
• Removed many confusing and rarely-used features ex:explicit
pointers,operator overloading.
Object oriented

• We organize our software as a combination of different types of


objects that incorporates both data and behaviour.
Platform independent

• A platform is the hardware or software environment in which a


program runs
secured
• Java is secured because:
• No explicit pointers
• Programs run inside virtual machine
Robust
• Robust means simply strong.
• It uses strong memory management
portable
• We may carry the java bytecode to any platform.
High performance
• Java is faster than other traditional programming languages
Distributed
• We can create distributed applications in java
• We may access files by calling the methods from any machine on the
internet
Multi-threaded
• A thread is a separate program, executing concurrently.
• We can write java programs that deal with many tasks at once by
defining multiple threads.
Oops concepts
object
• Any entity that has state and behavior is known as an
object. For example, a chair, pen, table, keyboard, bike,
etc
• An Object can be defined as an instance of a class.

• Example: A dog is an object because it has states like


color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.
Class
• Collection of objects is called class
• A class can also be defined as a blueprint from which
you can create an individual object.
Inheritance
• When one object acquires all the properties and
behaviors of a parent object, it is known as inheritance.
It provides code reusability.
• Inheritance is the process of acquiring properties and behaviors from one
object to another object or one class to another class. In inheritance, we
derive a new class from the existing class.
• Here, the new class acquires the properties and behaviors from the
existing class.
• In the inheritance concept, the class which provides properties is called as
parent class and the class which recieves the properties is called as child
class.
• The parent class is also known as base class or super class. The child class is
also known as derived class or sub class.
• In the inheritance, the properties and behaviors of base class extended to
its derived class, but the base class never receive properties or behaviors
from its derived class.
• In java programming language the keyword extends is used to implement
inheritance.
Polymorphism
• If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer
differently, to draw something, for example, shape,
triangle, rectangle, etc.
Abstraction

• Hiding internal details and showing functionality is


known as abstraction. For example phone call, we don't
know the internal processing.
• Abstraction is hiding the internal details and showing
only essential functionality.
• In the abstraction concept, we do not show the actual
implementation to the end user, instead we provide
only essential things.
• For example, if we want to drive a car, we does not
need to know about the internal functionality like how
wheel system works? how brake system works? how
music system works? etc.
Encapsulation

• Binding (or wrapping) code and data together into a


single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines.
Simple program of java
• To create a simple java program you need to create a class that
contains main method.
• Lets understand the requirement first
Requirement for hello java example
• For any java program you need to install the JDK,If you don’t have
installed it ,download the JDK and install it.
• Set the path of the JDK/bin directory
• Create the java program
• Compile and run the java program
Creating hello java example
Class Simple
{
Public static void main(String args[])
{
System.out.println(“Hello java”);
}
}
• Save the file as Simple.java
• To compile: javac Simple.java
• To execute : java Simple
• Output: Hello java
Classes and objects in java
• Class: Class is a set of object which shares common
properties/ attributes.
• It is just a template or blueprint or prototype from which
objects are created.
• Class is a group of variables of different data types and
group of methods.
Syntax to declare a class:

access_modifier class<class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
class Student
{
int id;//data member
String name; //data member

public static void main(String args[])


{
Student s1=new Student();//creating an object of
Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
class Student
{
int id;//data member
String name; //data member
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();//creating an object of
Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
class Student
{
int id;//data member
String name; //data member
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();//creating an object
S1.id=101;
S1.name=“java”
System.out.println(s1.id + “ “ + s1.name);
}
}
object
• represents real life entities
• An object consists of :
1.State: It is represented by attributes of an object.
2.Behavior: It is represented by methods of an object.
3.Identity: It gives a unique name to an object and
enables one object to interact with other objects.
// creating object of
class
Test

Test t = new Test();


Methods
• A method is a block of code or collection of statements
or a set of code grouped together to perform a certain
task or operation.
• It is used to achieve the reusability of code.
• We write a method once and use it many times.
1. public class Addition
2.{
3.public static void main(String[] args)
4.{
5.int a = 19;
6.int b = 5;
7.//method calling
8.int c = add(a, b); //a and b are actual parameters
9.System.out.println("The sum of a and b is= " + c);
10.
}
11.
//user defined method
12.
public static int add(int n1, int n2) //n1 and n2 are formal parameters
13.
{
14.
int s;
15.
s=n1+n2;
16.
return s; //returning the sum
17.
}
18.
}
Constructor
• In Java, a constructor is a block of codes similar to the
method.
• It is called when an instance of the class is created.
• It is a special type of method which is used to initialize
the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• It calls a default constructor if there is no constructor
available in the class. In such case, Java compiler
provides a default constructor by default.
Types of Java constructors

• There are two types of constructors in Java:


1.Default constructor (no-arg constructor)
2.Parameterized constructor
Java Default Constructor

• A constructor is called "Default Constructor" when it


doesn't have any parameter.
• Syntax of default constructor:
<class_name>()
{

}
1./Java Program to create and call a default constructor
2.class Bike1
3.{
4.//creating a default constructor
5. Bike1()
6. {
7. System.out.println("Bike is created");
8. }
9.//main method
10. public static void main(String args[])
11. {
12. //calling a default constructor
13. Bike1 b=new Bike1();
14. }
15.}
java Parameterized Constructor

• A constructor which has a specific number of


parameters is called a parameterized constructor.
1.//
Java Program to demonstrate the use o
f the parameterized constructor.
2.class Student 1. public static void main(String args[]){
3.{ 2. //creating objects and passing values
3. Student s1 = new Student(111,"Karan");
4. int id;
4. Student s2 = new Student(222,"Aryan");
5. String name; 5. //
6. // calling method to display the values of object
creating a parameterized constructor 6. s1.display();
7. Student(int i,String n){ 7. s2.display();
8. id = i; 8. }
9.}
9. name = n;
10. }
11. //method to display the values
12. void display()
13.
{
14.
System.out.println(id+" "+name);
15.
}
16.
17.
this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
Usage of Java this keyword

• Here is given the usage of java this keyword.


1.this can be used to refer current class instance variable
.
2.this can be used to invoke current class method (implici
tly)
3.this() can be used to invoke current class constructor.
1) this: to refer current class
instance variable
• The this keyword can be used to refer current class
instance variable. If there is ambiguity between the
instance variables and parameters, this keyword
resolves the problem of ambiguity.
Understanding the problem without this keyword
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10.void display()
Out put:
11.{
12.System.out.println(rollno+" "+name+" "+fee);
0 null 0.0
13.} 0 null 0.0
14.}
15.class TestThis1{
16.public static void main(String args[]){
17.Student s1=new Student(111,"ankit",5000f);
18.Student s2=new Student(112,"sumit",6000f);
19.s1.display();
20.s2.display();
21.}
22.}
So, we are using this keyword to
distinguish local variable and
instance variable.
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee)
6. {
7. this.rollno=rollno; Out put:
8. this.name=name; 111 ankit 5000.0
9. this.fee=fee; 112 sumit 6000.0
10.}
11.void display()
{System.out.println(rollno+" "+name+" "+fee);}
12.}
13.class TestThis2{
14.public static void main(String args[]){
15.Student s1=new Student(111,"ankit",5000f);
16.Student s2=new Student(112,"sumit",6000f);
17.s1.display();
18.s2.display();
19.}
20.}
Program where this keyword is not
required
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. } Out put:
10.void display() 111 ankit
11. { 5000.0
12. System.out.println(rollno+" "+name+" "+fee); 112 sumit
13. }
6000.0
14. }
15.class TestThis3{
16.public static void main(String args[]){
17. Student s1=new Student(111,"ankit",5000f);
18. Student s2=new Student(112,"sumit",6000f);
19. s1.display();
20. s2.display();
21. }
22. }
2) this: to invoke current class
method
• You may invoke the method of the current class by using the this keyword. If you don't use the this keyword,
compiler automatically adds this keyword while invoking the method. Let's see the example
1.class A{
2.void m()
3. {
4. System.out.println("hello m");
5. }
6.void n()
7. {
Output:
8. System.out.println("hello n"); Hello n
9. //m();//same as this.m() Hello m
10.this.m();
11.}
12.}
13.class TestThis4{
14.public static void main(String args[])
15.{
16.A a=new A();
17.a.n();
18.}}
3) this() : to invoke current class
constructor
• The this() constructor call can be used to invoke the
current class constructor. It is used to reuse the
constructor.
Calling default constructor from parameterized constructor:
1.class A{
2.A()
3.{
4.System.out.println("hello a");
5.} Output:
6.A(int x) hello a
7.{ 10
8.this();
9.System.out.println(x);
}
10.
}
11.
12.class TestThis5{
13.public static void main(String args[]
)
{
14.
A a=new A(10);
15.
}
16.
}
17.
Calling parameterized constructor from default constructor:
1. class A
2. {
3. A()
4. {
5. this(5);
6. System.out.println("hello a"); Output:
7. } 5
hello a
8. A(int x)
9. {
10.System.out.println(x);
11.}
12.}
13.class TestThis6
14.{
15.public static void main(String args[])
16.{
17.A a=new A();
18.}
19.}
Java Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime
unused memory automatically.
• In other words, it is a way to destroy the unused
objects.
• An in-use object, or a referenced object, means that
some part of your program still maintains a pointer to
that object.
• An unused or unreferenced object is no longer
referenced by any part of your program. So the memory
used by an unreferenced object can be reclaimed.
By nulling a reference:

1.Employee e=new Employee();


2.e=null;
variable
• A variable is a storage location for some type of value.

data type variable [ = value][, variable [ = value] ...] ;

Valid: InValid:
• int a, b, c; int int =45;
• int a = 10, b = 10;
• byte B = 22;
• double pi = 3.14159;
• char a = 'a';
• There are three kinds of variables in Java -
• Local variables - Local variables are declared in
methods, constructors, or blocks.
• Instance variables - Instance variables are declared in
a class, but outside a method, constructor or any block.
• 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.
Datatype
• A datatype represents the type of value stored in a
variable

• In java there are two types of datatypes

• 1.Primitive datatypes
• 2.NonPrimitive datatypes
Integers
• long num1 = 0L;
• long num2 = 401L;
• long num3 = -3556L
Float
• It is a 32-bit, single-precision floating-point number.
• Float data type in Java stores a decimal value with 6-7
total digits of precision
• Default value- 0.0f
1.float height = 167.7f or
2.float height = 167.7F
Double
• The double data type is a double-precision floating-
point.
• Double data type stores decimal values with 15-16
digits of precision.
Default value:0.0d
1.double price = 987.90D or
2.double price = 987.90d or
3.double price = 987.90
Boolean
• Boolean data type represents only one bit of
information either true or false which is intended to
represent the two truth values of logic.
Syntax:

boolean booleanVar;
char
• The char data type is a 16-bit unsigned Java primitive data type.
• Note that char is an unsigned data type.
• Therefore, a char variable cannot have a negative value.
• The range of the char data type is 0 to 65535

Char grade=‘A’;
• System.out.println(grade);

• //Output: A
Type Casting/type conversion

• Converting one primitive datatype into another is known


as type casting (type conversion) in Java.
• You can cast the primitive datatypes in two ways
namely, Widening and, Narrowing.
Widening
− Converting a lower datatype to a higher datatype is
known as widening.
public class WideningExample
{
public static void Integer value of the given
character: 67
main(String args[])
{
char ch = 'C';
int i = (int)ch;
System.out.println(i);
}
}
Narrowing
• Converting a higher datatype to a lower datatype is
known as narrowing.
import java.util.Scanner;
public class NarrowingExample
{
public static void main(String args[]) Enter an integer value: 67
Character value of the given integer: C
{

Scanner sc = new Scanner(System.in);


System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given
integer: "+ch);
}
}
Arrays
• an array is a collection of similar type of elements which
has contiguous memory location.
• Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
Types of Array in java

• There are two types of array.


• Single Dimensional Array
• Multidimensional Array
Single Dimensional Array

Syntax to Declare an Array in Java


Int[] mark;
1.dataType[] arr; (or)
Byte[] age;
2.dataType []arr; (or)
Double[] height;
3.dataType arr[];
Instantiating an Array in Java

• When an array is declared, only a reference of an array


is created. To create or give memory to the array, you
create an array like this:

• var-name = new type [size];

• int intArray[]; //declaring array


• intArray = new int[20]; // allocating memory to array
• OR

• int[] intArray = new int[20]; // combining both statements in one


1.class Testarray{
2.public static void main(String args[]){
3.int a[]=new int[5];//declaration and instantiation
4.a[0]=10;//initialization
5.a[1]=20;
6.a[2]=70;
7.a[3]=40;
8.a[4]=50;
9.//traversing array
10.for(int i=0;i<a.length;i++)
11.System.out.println(a[i]);
12.}
13.}
• 10
• 20
• 70
• 40
• 50
1.class Testarray1{
2.public static void main(String args[]){
3.int a[]={33,3,4,5};//
declaration, instantiation and initialization
4.//printing array
5.for(int i=0;i<a.length;i++)
6.System.out.println(a[i]);
7.}}
2-D Array
• An array with more than one dimension is known as a
multi-dimensional array
Declaring 2-D array in Java:

• Any 2-dimensional array can be declared as follows:

Syntax:
data_type array_name[][]; (OR) data_type[][]
array_name;
Different approaches for Initialization of 2-D
array in Java:

• data_type[][] array_Name = new data_type[no_of_rows]


[no_of_columns];

• The total elements in any 2D array will be equal to (no_of_rows) * (no_of_columns).


• no_of_rows: The number of rows in an array. e.g. no_of_rows = 3, then the array will have three
rows.
• no_of_columns: The number of columns in an array. e.g. no_of_columns = 4, then the array will
have four columns.
import java.io.*;
import java.util.*;

class Example {
public static void main(String[] args)
{
int[][] scores = new int[2][2];

scores[0][0] = 15;
Output:
scores[0][1] = 23; scores[0][0] = 15
scores[0][1] = 23
scores[1][0] = 30; scores[1][0] = 30
scores[1][1] = 21
scores[1][1] = 21;

// printing the array elements individually


System.out.println("scores[0][0] = "
+ scores[0][0]);
System.out.println("scores[0][1] = "
+ scores[0][1]);
System.out.println("scores[1][0] = "
+ scores[1][0]);
System.out.println("scores[1][1] = "
+ scores[1][1]);
}
class Example2 {
public static void main(String[] args)
OUTPUT:
{
arr[0][0] = 1
arr[0][1] = 2
int[][] arr = { { 1, 2 }, { 3, 4 } }; arr[1][0] = 3
arr[1][1] = 4
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "
+ arr[i][j]);
}
}
Operators
• It is a special symbols performing specific operations on one, two,
three operands and then returning a result.
• Java provides a rich set of operations
operands
• An operands are the values on which the operators act upon
Types of operators
• Unary Operator,
• Arithmetic Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
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
• Increment operator: ++
• Decrement operator: --
a=a+1; a++;
a=a-1; a--;
Arithmetic Operator
• They are used to perform simple arithmetic operations
on primitive data
Operator
types. Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division
1.public class OperatorExample
{
2.public static void main(String
OUTPUT
args[]){ 15
5
3.int a=10; 50
4.int b=5; 2
0
5.System.out.println(a+b);//15
6.System.out.println(a-b);//5
7.System.out.println(a*b);//50
8.System.out.println(a/b);//2
9.System.out.println(a%b);//0
10.}}
Relational Operator
• A relational operator compares two values and determines the
relationship between them.
Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand


>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand


Bitwise Operator
• Java defines several bitwise operators that can be applied to
the integer types long, int, short, char and byte
Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> left shift

<< right shift


A B a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0
Logical Operator
• Java supports following 3 logical operator, Suppose a=1 and b=0;

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


Ternary Operator
• Ternary operator is a shorthand version of the if-else
statement. It has three operands and hence the name
ternary.

The general format is:


condition ? if true : if false
Assignment Operator
• =’ Assignment operator is used to assigning a value to
any variable.

• int a,b;
• a=2;
• b=5;
Control statements
Selection statements
If Statements
Simple if
If else
If -else -if ladder
Nested if
Switch
Iteration statements
Do while
for
Jump statements
break
• This statement is used to jump out of a loop
• Break statement was previously used in switch-case statements
• The remaining statements which are after the break and within the
loop are skipped
break
Continue statement
The return statement
• the return statement is used for returning a value when
the execution of the block is completed.
Method overloading
• If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
Different ways to overload the
method

• There are three ways to overload the method in java


1.By changing number of arguments
2.By changing the data type
3.Changing the order of the parameters of methods
1) Method Overloading: changing no. of arguments

import java.io.*;

class Product {
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

public int multiply(int a, int b, int c)


OUTPUT:
{
int prod = a * b * c;
Product of the two integer value :2
return prod;
Product of the three integer value :6
}
}

class GFG {

public static void main(String[] args)


{

Product ob = new Product();


int prod1 = ob.multiply(1, 2);

System.out.println(
"Product of the two integer value :" + prod1);

int prod2 = ob.multiply(1, 2, 3);

System.out.println(
"Product of the three integer value :" + prod2);
}
}
2) Method Overloading: changing data type of arguments

import java.io.*;

class Product {
public int Prod(int a, int b, int c)
{

int prod1 = a * b * c;
return prod1;
}
OUTPUT:

public double Prod(double a, double b, double c) Product of the three integer value :6
{ Product of the three double value :6.0

double prod2 = a * b * c;
return prod2;
}
}

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

Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println("Product of the three integer value :"
+ prod1);
double prod2 = obj.Prod(1.0, 2.0, 3.0);
System.out.println("Product of the three double value :" +
prod2);
}
}
import java.io.*;
3. Changing the Order of the Parameters of Methods

class Student {

// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " " + "Roll-No :" +
roll_no);
}
// Method 2
public void StudentId(int roll_no, String name)
{ OUTPUT:
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " " + "Name :" + Name :karan Roll-No :1
name); Roll-No :2 Name :Kamlesh
}
}

// Class 2
// Main class
class GFG {

public static void main(String[] args)


{

// Creating object of above class


Student obj = new Student();

// Passing name and id


// Note: Reversing order
obj.StudentId(“karan", 1);
obj.StudentId(2, "Kamlesh");
}
}
Constructor overloading

• In Java, we can overload constructors like methods.


• The constructor overloading can be defined as the
concept of having more than one constructor with
different parameters so that every constructor can
perform a different task.
•Rules for creating java constructor

• Constructor name must be same as its class name


• Constructor must have no explicit return type
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5. Output:
6. Student(){ this a default constructor
7. System.out.println("this a default constructor");
8. } Default Constructor values:
9.
Student Id : 0
10. Student(int i, String n){
Student Name : null
11. id = i;
12. name = n;
13. }
14. Parameterized Constructor
15. public static void main(String[] args) { values: Student Id : 10
16. //object creation Student Name : David
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\
nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \
n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\
nStudent Name : "+student.name);
24. }
Parameter passing
• Important methods of Parameter Passing
• 1.pass by value
• 2.pass by reference
Important methods of
Parameter Passing
• 1. Pass By Value:
• Changes made to formal parameter do not get transmitted back to
the caller. Any modifications to the formal parameter variable inside
the called function or method affect only the separate storage
location and will not be reflected in the actual parameter in the
calling environment. This method is also called as call by value.
class CallByValue {

// Function to change the value


// of the parameters
public static void example(int x, int y)
{
x++;
y++;
}
}

// Caller Value of a: 10 & b: 20


public class Main { Value of a: 10 & b: 20
public static void main(String[] args)
{

int a = 10;
int b = 20;

// Instance of class is created


CallByValue object = new
CallByValue();

System.out.println("Value of a: " + a
+ " & b: " + b);

// Passing variables in the class


function
object.example(a, b);

// Displaying values after


// calling the function
System.out.println("Value of a: "
+ a + " & b: " +
b);
}
Call by reference
• Changes made to formal parameter do get transmitted
back to the caller through parameter passing. This
method is also called as call by reference
class CallByReference {
int a, b;
CallByReference(int x, int y)
{
a = x;
b = y;
}

// Changing the values of class variables


void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20;
} OUTPUT:
} Value of a: 10 & b: 20
Value of a: 20 & b: 40
public class Main {

public static void main(String[] args)


{
CallByReference obj
= new CallByReference(10, 20);

System.out.println("Value of a: " +
obj.a
+ " & b: " +
obj.b);

// Changing values in class function


obj.ChangeValue(obj);

// Displaying values
// after calling the function
System.out.println("Value of a: " +
obj.a
+ " & b: " +
obj.b);
}
Recursion
• Recursion in java is a process in which a method calls
itself continuously. A method in java that calls itself is
called recursive method.
Syntax:

1.returntype methodname
()
2.{
3.//code to be executed
4.methodname();//
calling same method
5.}
• class Factorial
• {
• // this is a recursive function
• int fact(int n)
• {
• int result;
• if(n==1)
• return 1;
• result = n * fact(n-1);
• return result;
• } OUTPUT:
• } Factorial of 3 is 6
• class Recursion Factorial of 4 is 24
• { Factorial of 5 is 120
• public static void main(String args[])
• {
• Factorial f = new Factorial();
• System.out.println("Factorial of 3 is " + f.fact(3));
• System.out.println("Factorial of 4 is " + f.fact(4));
• System.out.println("Factorial of 5 is " + f.fact(5));
• }
• }
String class
• string is basically an object that represents sequence of
char values. An array of characters works same as Java
string.
• For example:
• char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
String class
String is a sequence of characters. In java, objects of String are immutable which means a constant
and cannot be changed
once created.
Creating a String
There are two ways to create string in Java:

•String literal
String s = “java”;
•Using new keyword
String s = new String (“java”);
String Handling methods
• String toUpperCase() and toLowerCase() method
• The Java String toUpperCase() method converts this String into uppercase letter and
String toLowerCase() method into lowercase letter.

• public class Stringoperation1


• {
• public static void main(String ar[])
• {
• String s="Sachin";
• System.out.println(s.toUpperCase());//SACHIN
• System.out.println(s.toLowerCase());//sachin
• System.out.println(s);//Sachin(no change in original)
• }
• }

String equals() method

• The equals method can be used to compare whether two strings are having the same
content or not. If An example of using equals method is given below:

• String str1 = "hello";


• String str2 = new String("hello");
• System.out.println(str1.equals(str2));
• The above code prints true. the strings are same, this method returns true, otherwise,
false.
String startsWith() and endsWith() method

• The method startsWith() checks whether the String starts with the
letters passed as arguments and endsWith() method checks whether
the String ends with the letters passed as arguments.
• public class Stringoperation3
• {
• public static void main(String ar[])
• {
• String s="Sachin";
• System.out.println(s.startsWith("Sa"));//true
• System.out.println(s.endsWith("n"));//true
• }
• }

Output:
True
true
String charAt() Method

• The String class charAt() method returns a character at specified index.

•public class Stringoperation4


• {
• public static void main(String ar[])
• {
• String s="Sachin";
• System.out.println(s.charAt(0));//S
• System.out.println(s.charAt(3));//h
• }
• }

String length() Method

•The String class length() method returns length of the specified String.
• public class Stringoperation5
• {
• public static void main(String ar[])
• {
• String s="Sachin";
• System.out.println(s.length());//6
• }
• }
valueOf()
• The overloaded valueOf method can be used to convert primitive type
values like int, float, double etc to a String.
Syntax:
static String valueOf(int value)
• An example of valueOf method is given below:
• int x = 10;
• String str = String.valueOf(x);
• System.out.println(str);
• Above example prints 10.
indexOf()
• The indexOf method is used to find the position (number) of a
specified character in the invoking string.
• Syntax:
int indexOf(char c)
• An example of using indexOf method is given below:
String str1 = "hello world";
System.out.println(str1.indexOf('o'));
• Above example prints 4 which the index of first ‘o’ in the string “hello
world”.
• The overloaded indexOf method is used to find the position (number)
of a specified string in the invoking string.
• Syntax:
int indexOf(String str)

• An example of using indexOf method is given below:


String str1 = "hello world";
System.out.println(str1.indexOf("wor"));
• Above example prints 6.
lastIndexOf()
• The lastIndexOf method is used to find the position (number) of a
specified character from the end of the invoking string.
• Syntax:
int lastIndexOf(char c)
• An example of using lastIndexOf method is given below:
String str1 = "hello world";
System.out.println(str1.lastIndexOf('o'));
Above example prints 7 which is the position of ‘o’ from the end of the
invoking string “hello world”.
• The overloaded lastIndexOf method is used to find the position
(number) of a specified string from the end of the invoking string.
• Syntax:
int lastIndexOf(String str)
• An example of using lastIndexOf method is given below:
String str1 = "I am a good and I am bad";
System.out.println(str1.lastIndexOf("am"));
• Above example prints 18.
substring()
• The substring method can be used to extract a sub string from the
invoking string from a specified position to the end of the string.
• Syntax:
String substring(int index)
• An example of substring method is given below:
String str1 = "hello world";
System.out.println(str1.substring(2));
Above example prints “llo world”. The starting index specified in the
above example is 2.
Java StringBuffer Class

• Java StringBuffer class is used to create mutable


(modifiable) String objects. The StringBuffer class in
Java is the same as String class except it is mutable i.e.
it can be changed.
• Creating Strings using StringBuffer Class
• We can use the overloaded StringBuffer constructors as shown below:

StringBuffer sb1 = new StringBuffer();


StringBuffer sb2 = new StringBuffer(30);
StringBuffer sb3 = new StringBuffer("hello");
StringBuffer Methods
• StringBuffer Class append() Method: The append()
method concatenates the given argument with this
String.
1.class StringBufferExample{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello ");
4.sb.append("Java");//now original string is changed
5.System.out.println(sb);//prints Hello Java
6.}
7.}
Output:
Hello Java
StringBuffer insert() Method
• The insert() method inserts the given String with this
string at the given position.
1.class StringBufferExample2{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello ");
4.sb.insert(1,"Java");//now original string is changed
5.System.out.println(sb);//prints HJavaello
6.}
7.}
Output:
HJavaello
StringBuffer replace() Method

• The replace() method replaces the given String from the


specified beginIndex and endIndex.

1.class StringBufferExample3{
2.public static void main(String args[]){
3.StringBuffer sb=new StringBuffer("Hello");
4.sb.replace(1,3,"Java");
5.System.out.println(sb);//prints HJavalo
6.}
7.}
Output:
HJavalo
StringBuffer delete() Method
• The delete() method of the StringBuffer
class deletes the String from the
specified beginIndex to endIndex.
1.class StringBufferExample4{ Output:
2.public static void main(String args[]) Hlo
{
3.StringBuffer sb=new StringBuffer("Hel
lo");
4.sb.delete(1,3);
5.System.out.println(sb);//prints Hlo
6.}
7.}
Replace()

• The replace method can be used to replace a set of characters with a


specified string. The sub string is
• specified with starting index and ending index plus one.
Syntax:
StringBuffer replace(int startIndex, int endIndex, String str)
• An example of using replace method is given below:
StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.replace(1, 3, "a"));
• Above example prints “halo”.
length()

• The length method can be used to find the size of a StringBuffer


object.
• Syntax:
int length()
• An example of using length method is given below:
StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.length());
• Above example prints 5 which is the number of characters (size) in the
buffer.
capacity()
• The capacity method can be used to find the capacity of a StringBuffer
object.

• An example of using capacity method is given below:


sb1 = new StringBuffer("hello");
System.out.println(sb1.capacity());
• Above example prints 21 which is the capacity (size + 16) of the buffer.
charAt()
• The charAt method can be used to retrieve a single character from a
specified position. Syntax of this method is given below:
char charAt(int pos)
• An example of using charAt method is given below:
StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.charAt(1));
• Above example prints the character ‘e’ which is available at the
specified position 1.
setCharAt()
• The setCharAt method can be used to set (change) a character at a
specific location in the buffer.
• Syntax:
void setCharAt(int pos, char ch)
• An example of using setCharAt method is given below:
StringBuffer sb1 = new StringBuffer("hello");
sb1.setCharAt(1, 'a’);
System.out.println(sb1);
• Above example prints “hallo”.
getChars():
• The getChars method can be used to extract a sub string from the
buffer to a character array.
• Syntax:
void getChars(int startIndex, int endIndex, char target[], int targetStart)
An example of getChars method is given below:
char[] target = new char[10];
StringBuffer sb1 = new StringBuffer("hello");
sb1.getChars(0, 3, target, 0);
System.out.println(target);
Above example prints “hel”.
reverse()
• The reverse method can be used to reverse the content of a buffer.
• Syntax:
StringBuffer reverse()
• An example of using reverse method is given below:
StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.reverse());
• Above example prints “olleh”.
deleteCharAt()
• The deleteCharAt method can be used to delete a character at
specified location in the buffer.
• Syntax:
StringBuffer deleteCharAt(int pos)
• An example of using deleteCharAt method is given below:
StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.deleteCharAt(1));
Above example prints “hllo”.

You might also like