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

Unit-1 Introduction To Java

java int6ruduction

Uploaded by

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

Unit-1 Introduction To Java

java int6ruduction

Uploaded by

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

SUMMARY OF SYLLABUS

• UNIT - I: Object Oriented Thinking and Java Basics

• UNIT - II: Inheritance, Packages and Interfaces

• UNIT - III: Exception Handling and Multithreading

• UNIT - IV: AWT Event Handling

• UNIT - V: Applets and swings

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 1


How to Start Java Programs Practically?
• Software Requirements to Run Java Program:
 Text Editor -- > Notepad.
 JDK (Java Development Kit) Latest version
 Command Prompt
• After Installation of JDK software, Java Class Path should set in following steps

• In Windows: steps are,

1. From the desktop, right click the Computer/ThisPC icon.

2. Choose Properties from the context menu.

3. Click the Advanced system settings link.

4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit.

5. If the PATH environment variable does not exist, click New.

6. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK.

7. Close all remaining windows by clicking OK.


10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 2
Steps to run Java Program

1. Open Notepad and Type Your Java Program


2. Save File with extension of .java Example: Sample.java in your folder
3. Folder should be create with Your Roll Number With Caps in D Drive Ex: 207Y1A0590
4. Then your files saved in D:/207Y1A0590>
5. Open command Prompt and Type Javac  to check java installed or not , similarly type java
6. Then list of command will display if java installed and given path properly.
7. By default Command Prompt Open as C:\Users\sathe> so here you have change control to your created
folder.
8. To Change from C directive to D , Type like this D: (D Colon)  Press Enter
9. D:> next Type  cd 207Y1A0590  Press Enter (cd means change directory)
10.D:/ 207Y1A0590> javac sample.java  to compile the java program
11. If your not getting any errors the run or execute program
12.Type  java Sample  press Enter  To run java program
13.Result or Output will display on Console

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 3


UNIT-I OBJECT ORIENTED THINKING AND JAVA BASICS
• Need for OOP Paradigm,
• Summary of OOP Concepts, Coping with Complexity,
• Abstraction Mechanisms,
• A Way of Viewing World – Agents, Responsibility,
• Messages, Methods,
• History of Java, Java Buzzwords,
• Data Types, Variables, Scope and Life Time of
• Variables, Arrays, Operators, Expressions,
• Control Statements,
• Type Conversion and Casting, Simple
• Java Program, Concepts of Classes,
• Objects, Constructors, Methods, Access Control, This Keyword,
• Garbage Collection, Overloading Methods and Constructors,
• Method Binding, Inheritance, Overriding and Exceptions, Parameter Passing, Recursion, Nested and Inner
Classes, Exploring String Class.
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 4
DIFFERENCES BETWEEN C, C++ AND
JAVA
S.N Basis C C++ Java
.
1 Origin The C language is based on BCPL. The C++ language is based on the C The Java programming language is based on
language. both C and C++.

2 Programming Pattern It is a procedural language. It is an object-oriented programming It is a pure object-oriented programming


language. language.

3 Approach It uses the top-down approach. It uses the bottom-up approach. It also uses the bottom-up approach.

4 Dynamic or Static It is a static programming language. It is also a static programming language. It is a dynamic programming language.

5 Code Execution The code is executed directly. The code is executed directly. The code is executed by the JVM.
6 Platform Dependency It is platform dependent. It is platform dependent. It is platform-independent because of byte
code.

7 Translator It uses a compiler only to translate the It also uses a compiler only to translate the Java uses both compiler and interpreter and
code into machine language. code into machine language. it is also known as an interpreted language.

8 File Generation It generates the .exe, and .bak, files. It generates .exe file. It generates .class file.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 5


9 Number of There are 32 keywords in the C There are 60 keywords in the C++ There are 52 keywords in the Java language.
Keyword language. language.
10 Source File The source file has a .c extension. The source file has a .cpp The source file has a .java extension.
Extension extension.
11 Pointer Concept It supports pointer. It also supports pointer. Java does not support the pointer concept because
of security.

12 Union and It supports union and structure data It also supports union and structure It does not support union and structure data types.
Structure types. data types.
Datatype
13 Pre-processor It uses pre-processor directives such as It uses pre-processor directives It does not use directives but uses packages.
Directives #include, #define, etc. such as #include, #define,
#header, etc.

14 Constructor/ It does not support constructor and It supports both constructor and It supports constructors only.
Destructor destructor. destructor.
15 Exception It does not support exception handling. It supports exception handling. It also supports exception handling.
Handling
16 Memory It uses the calloc(), malloc(), free(), It uses new and delete operator to It uses a garbage collector to manage the memory.
Management and realloc() methods to manage the manage the memory.
memory.

17 Overloading It does not support the overloading Method and operator overloading Only method overloading can be achieved.
concept. can be achieved.
18 goto Statement It supports the goto statement. It also supports the goto It does not support the goto statements.
statement.
19 Used for It is widely used to develop drivers and It is widely used for system It is used to develop web applications, mobile
operating systems. programming. applications, and windows applications.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 6


NEED FOR OOPS PARADIGM
Need for object-oriented paradigm

• It produces reusable code/objects because of encapsulation and inheritance.


• The data is protected because it can be altered only by the encapsulated
methods.
• It is more efficient to write programs which use pre-defined objects.
• The storage structure and/or procedures within an object type could be
altered if required without affecting programs that make use of that object
type.
• New functions can easily be added to objects by using inheritance
• Less maintenance effort will be required by the developer because objects
can be reused
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 7
SUMMARY OF OOPS CONCEPTS
• CLASS –its blue print/ Template

• OBJECT – Instance of the class

• ABSTRACTION – only declaration but not


implemented

• INHERITANCE – acquires properties from parent class

• POLYMORPHISM – Performs in verity of Ways

• ENCAPSULATION - Wrapping/Hiding Data

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 8


COPING WITH COMPLEXITY
• Object-oriented programming helps, when done right, by creating

abstractions and hiding away complexity. An object of a class has a certain

defined behavior that we can reason from, without caring about the

complexity of the implementation.

• Inheritance : acquiring all the properties from the base class even it is not

useful to your current operation.

• Encapsulation : some conditions the required information can’t be


10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 9
ABSTRACTION MECHANISMS
• Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.

• Abstraction is only declaration but not implementation

Example :

Public abstract class ATM

{
public abstract withdraw();
public abstract balanceEnquiry();
public abstract deposit();
public abstract pinChange();
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 10
A WAY OF VIEWING WORLD
• Agents
• Responsibilities
• Messages
• Methods

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 11


HISTORY OF JAVA
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of
sun engineers called Green Team.

• Initially designed for small, embedded systems in electronic appliances like set-top boxes.

• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

• After that, it was called Oak and was developed as a part of the Green project.

• Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.

• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

• Java is an island of Indonesia where the first coffee was produced (called java coffee). It is a kind of espresso bean. Java name
was chosen by James Gosling while having coffee near his office.

• Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995.

• JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been many additional features added to the
language.

• Now Java is being used in Windows applications, Web applications, Enterprise applications, Mobile applications, cards, etc. Each
new version adds the new features in Java.
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 12
JAVA BUZZWORDS
Java is the most popular object-oriented programming language. Java has many advanced features, a list of

key features is known as Java Buzz Words. The java team has listed the following terms as java buzz words.
• SIMPLE
• SECURE
• PORTABLE
• OBJECT-ORIENTED
• ROBUST
• ARCHITECTURE-NEUTRAL (OR)
PLATFORM INDEPENDENT
• MULTI-THREADED
• INTERPRETED
• HIGH PERFORMANCE
• DISTRIBUTED
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 13
• DYNAMIC
DATA TYPES IN JAVA

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 14


PRIMITIVE DATA TYPES IN JAVA
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values


char 2 bytes Stores a single character/letter or ASCII values
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 15
There are two data types available in Java
 Primitive Data Types
 Non- Primitive Data types (Reference/Object Data Types)
Primitive Data Types
• There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the
language and named by a keyword. Let us now look into the eight primitive data types in detail.

byte
• Byte data type is an 8-bit signed two's complement integer
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four
times smaller than an integer.
• Example: byte a = 100, byte b = -50

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 16


short
• Short data type is a 16-bit signed two's complement integer
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an
integer
• Default value is 0.
• Example: short s = 10000, short r = -20000

int
• Int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648 (-2^31)
• Maximum value is 2,147,483,647(inclusive) (2^31 -1)
• Integer is generally used as the default data type for integral values unless there is a concern
about memory.
• The default value is 0
•10/06/2024
Example: int a = 100000, int b = -200000
R.SATHEESH , ASST.PROF, CSIT, MLRITM 17
long
• Long data type is a 64-bit signed two's complement integer
• Minimum value is -9,223,372,036,854,775,808(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
• This type is used when a wider range than int is needed
• Default value is 0L
• Example: long a = 100000L, long b = -200000L

float
• Float data type is a single-precision 32-bit IEEE 754 floating point
• Float is mainly used to save memory in large arrays of floating point numbers
• Default value is 0.0f
• Float data type is never used for precise values such as currency
• Example: float f1 = 234.5f

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 18


Double
• double data type is a double-precision 64-bit IEEE 754 floating point
• This data type is generally used as the default data type for decimal values, generally the default
choice
• Double data type should never be used for precise values such as currency
• Default value is 0.0d
• Example: double d1 = 123.4

Boolean
• boolean data type represents one bit of information
• There are only two possible values: true and false
• This data type is used for simple flags that track true/false conditions
• Default value is false
• Example: boolean one = true

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 19


char
• char data type is a single 16-bit Unicode character
• Minimum value is '\u0000' (or 0)
• Maximum value is '\uffff' (or 65,535 inclusive)
• Char data type is used to store any character
• Example: char letterA = 'A'

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 20


Example
public class Datatypes {
public static void main(String[] args) {
int age = 16; // integer
byte rollnumber=112; //byte
short sno=1; float average = 78.4f; // floating point number
double attendance=77.87d; // double point number
char gender = ‘M'; // character
boolean goodboy= true; // boolean
String name = “RRR"; // String
System.out.println(“ Student Serial number is :” + sno);
System.out.println(“Student roll number is : “ + rollnumber);
System.out.println(“ Student name is :” + name);
System.out.println(“ Student age is : ” + age);
System.out.println(“ Students marks :”+ average );
System.out.println(“ Student attendance % is :”+ attendance );
System.out.println(“ Student gender is : ” + gender );
System.out.println(“ The is good boy/girl :” + goodboy );
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 21
} }
JAVA VARIABLES

• A variable is a container which holds the value while the Java program is executed. A variable is assigned
with a data type.
• Variable is a name of memory location. There are three types of variables in java: local, instance and static.
• There are two types of data types in Java: primitive and non-primitive.

Int a = 10;
Int data type
a  variable
Variable 10  value

Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a

combination of "vary + able" that means its value can be changed.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 22


10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 23
• 1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the

other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

• 2) Instance /Global Variable


A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

• 3) Static/ Class variable


A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and

share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the

memory.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 24


• Example to understand the types of variables in java

1.class Student{
2.int marks=50;//instance variable
3.static int total=100;//static variable
4.void method(){
5.int java=90;//local variable
6.}
7.}//end of class

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 25


SCOPE AND LIFE TIME OF
VARIABLES
• Scope of a variable refers to in which areas or sections of a program
can the variable be accessed or visible

• lifetime of a variable refers to how long the variable stays alive in


memory.

• General convention for a variable’s scope is, it is accessible only within the block
in which it is declared. A block begins with a left curly brace { and ends with a
right curly brace }.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 26


10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 27
CLASS VARIABLE SCOPE

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 28


INSTANCE VARIABLE SCOPE

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 29


LOCAL VARIABLE SCOPE

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 30


ARRAYS IN JAVA
• Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.

• Declaring Single Dimensional Array:


Syntax:
dataType[] varName; or
dataType varName[];
Example:
int a[]; or int[] a;
• The declaration and instantiating of an 1-D array is, as follows
Example:
int[] a=new int[5];
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 31
DIFFERENT WAYS TO DECLARE ARRAYS
// declare an array // allocate memory
double[] data; data = new Double[10];

• double[] data = new double[10]; //declare and initialize and array


• int[] age = {12, 4, 5, 2, 5};
• int[] data = new int[20];
• String[] cars = {"Volvo", "BMW",
• int[] myNum = {10, 20, 30, 40}; "Ford", "Mazda"};

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 32


1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3.class Testarray{
OUTPUT
4.public static void main(String args[]){
5.int a[]=new int[5];//declaration and instantiation
6.a[0]=10;//initialization
10
7.a[1]=20; 20
8.a[2]=70;
9.a[3]=40;
70
10.a[4]=50; 40
11.//traversing array
50
12.for(int i=0;i<a.length;i++)//length is the property of array
13.System.out.println(a[i]);
}}
14.10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 33
Another way of declaring arrays
1.class Testarray{ • Output:
2.public static void main(String args[]){
3.int a[]={10,20,30,40,50,60}; • 10
4.//declaration and instantiation • 20
5.//traversing array • 30
6.for(int i=0;i<a.length;i++)// • 40
length is the property of array • 50
7.System.out.println(a[i]); • 60
8.}
9.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 34
MULTIDIMENSIONAL ARRAY IN JAVA

Syntax to Declare Multidimensional Array in Java


1.dataType[][] arrayRefVar; (or)
2.dataType [][]arrayRefVar; (or)
3.dataType arrayRefVar[][]; (or)
4.dataType []arrayRefVar[];

• Example to instantiate Multidimensional array

int[][] arr=new int[3][3];//3 row and 3 column

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 35


Multi Dimentional Array

1.class Testarray3{
2.public static void main(String args[]){
3.//declaring and initializing 2D array
4.int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
5.//printing 2D array
6.for(int i=0;i<3;i++){
7. for(int j=0;j<3;j++){
8. System.out.print(arr[i][j]+" ");
9. }
10. System.out.println();
11.}
12.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 36
13.}
OPERATORS IN JAVA

ARITHMETIC OPERATORS

RELATIONAL OPERATORS

BITWISE OPERATORS

LOGICAL OPERATORS

ASSIGNMENT OPERATORS
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 37
ARITHMETIC OPERATORS
Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

- (Subtraction) Subtracts right-hand operand from left-hand A - B will give -10


operand.

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

/ (Division) Divides left-hand operand by right-hand operand. B / A will give 2

% (Modulus) Divides left-hand operand by right-hand operand B % A will give 0


and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19


10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 38
Example
Class ArithmeticOperators
{ public static void main(String[] args) {
int a = 12, b = 5; // declare variables
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 39
RELATIONAL OPERATORS
Operator Description Example
== (equal to) Checks if the values of two operands are equal or not, if yes (A == B) is not true.
then condition becomes true.
Checks if the values of two operands are equal or not, if
!= (not equal to) values are not equal then condition becomes true. (A != B) is true.

Checks if the value of left operand is greater than the value


> (greater than) of right operand, if yes then condition becomes true. (A > B) is not true.

Checks if the value of left operand is less than the value of


< (less than) right operand, if yes then condition becomes true. (A < B) is true.

>= (greater than or Checks if the value of left operand is greater than or equal to (A >= B) is not true.
equal to) the value of right operand, if yes then condition becomes
true.
<= (less than or equal to) Checks if the value of left operand is less than or equal to
the value of right operand, if yes then condition becomes (A <= B) is true.
true.
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 40
class RelationalOperators
{
public static void main(String[] args) {
int a = 7, b = 11; // create variables // value of a and b
System.out.println("a is “ + a + " and b is " + b);
System.out.println(a == b); // == operator // false
System.out.println(a != b); // != operator // true
System.out.println(a > b); // > operator // false
System.out.println(a < b); // < operator // true
System.out.println(a >= b); // >= operator // false
System.out.println(a <= b); // <= operator // true
} }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 41
BITWISE OPERATORS
Operator Description Example
& (bitwise and) Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is
exists in both operands. 0000 1100
| (bitwise or) Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is 0011
operand. 1101
^ (bitwise XOR) Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
operand but not both. 0001
(~A ) will give -61 which is 1100
~ (bitwise Binary Ones Complement Operator is unary and has the 0011 in 2's complement form due
compliment) effect of 'flipping' bits. to a signed binary number.
Binary Left Shift Operator. The left operands value
is moved left by the number of bits specified by the A << 2 will give 240
<< (left shift)
right operand. which is 1111 0000
Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by the A >> 2 will give 15 which is 1111
>> (right shift)
right operand.
Shift right zero fill operator. The left operands value
is moved right by the number of bits specified by the
>>> (zero fill right A >>>2 will give 15
right operand and shifted values are filled up with
shift)
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM which is 0000 1111 42
zeros.
LOGICAL OPERATORS
Operator Description Example

&& (logical Called Logical AND operator. If both the operands are non-zero, (A && B) is false
and) then the condition becomes true.

|| (logical or) Called Logical OR Operator. If any of the two operands are non- (A || B) is true
zero, then the condition becomes true.

! (logical Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is true
not) its operand. If a condition is true then Logical NOT operator will
make false.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 43


ASSIGNMENT OPERATORS
Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side C = A + B will assign value of A + B into
operand. C
Add AND assignment operator. It adds right operand to the left operand and assign C += A is equivalent to C = C + A
the result to left operand.
+=
Subtract AND assignment operator. It subtracts right operand from the left operand C -= A is equivalent to C = C – A
and assign the result to left operand.
-=
Multiply AND assignment operator. It multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.
*=
Divide AND assignment operator. It divides left operand with the right operand and C /= A is equivalent to C = C / A
assign the result to left operand.
/=
Modulus AND assignment operator. It takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand.
%=
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|=
10/06/2024 bitwise inclusive OR and assignment operator.
R.SATHEESH , ASST.PROF, CSIT, MLRITM C |= 2 is same as C = C 44
|2
JAVA EXPRESSIONS

A Java expression consists of variables, operators, literals, and method calls. To know more about method calls,
visit Java methods.
For example,
int score;
score = 90; Here, score = 90 is an statement that returns an int
Consider another example,
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4; // here, a + b - 3.4 is an expression
Expression statements
We can convert an expression into a statement by terminating the expression with a ;. These are known as expression
statements. For example,
// expression
int num=a*b-c/d;
Or int num=10+20-5/2;
// statement
number = 10;
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 45
CONTROL STATEMENTS

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 46


IF STATEMENT
This is the most basic statement among all control Example:
flow statements in java. It evaluates a Boolean
expression and enables the program to enter a block 1. //
of code if the expression evaluates to true. Java Program to demonstate the use of if stateme
nt.
SYNTAX: 2.public class IfExample {
1. if(condition){
3.public static void main(String[] args) {
2. //code to be executed
3. }
4. //defining an 'age' variable
5. int age=20;
6. //checking the age
7. if(age>18){
8. System.out.print("Age is greater than 18");
9. }
10.}
11.}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 47


IF-ELSE STATEMENT

• Example:
The Java if-else statement 1. //A Java Program to demonstrate the use of if-
also tests the condition. It else statement.
2. //It is a program of odd and even number.
executes the if block if 3. public class IfElseExample {

condition is true otherwise 4. public static void main(String[] args) {


5. //defining a variable
else block is executed. 6.
7.
int number=13;
//
SYNTAX: 8.
Check if the number is divisible by 2 or not
if(number%2==0){
1. if(condition){ 9. System.out.println("even number");
10. }else{
2. //code if condition is true 11. System.out.println("odd number");
3. }else{ 12. }
13.}
4. //code if condition is false 14.}

5. }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 48
IF-ELSE-IF LADDER STATEMENT

The if-else-if ladder statement executes one


condition from multiple statements.
SYNTAX:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 49


EXAMPLE- IF-ELSE-IF LADER
1. //Java Program to demonstrate the use of If else- 13. System.out.println("C grade");
if ladder. 14. }
2. // 15. else if(marks>=70 && marks<80){
It is a program of grading system for fail, D grad
e, C grade, B grade, A grade and A+. 16. System.out.println("B grade");
17. }
3. public class IfElseIfExample { 18. else if(marks>=80 && marks<90){
4. public static void main(String[] args) { 19. System.out.println("A grade");
5. int marks=65; 20. }else if(marks>=90 && marks<100){
6. if(marks<50){ 21. System.out.println("A+ grade");
7. System.out.println("fail"); 22. }else{
8. } 23. System.out.println("Invalid!");
9. else if(marks>=50 && marks<60){ 24. }
10. System.out.println("D grade"); 25.}
11. } 26.}
12. else if(marks>=60 && marks<70){
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 50
NESTED IF STATEMENT

• The nested if statement represents the if block Example:


within another if block. Here, the inner if block 1. //
condition executes only when outer if block Java Program to demonstrate the use of Nested If State
condition is true. ment.

SYNTAX: 2. public class JavaNestedIfExample {

1. if(condition){ 3. public static void main(String[] args) {


2. //code to be executed 4. //Creating two variables for age and weight
3. if(condition){ 5. int age=20;
4. //code to be executed 6. int weight=80;
5. } } 7. //applying condition on age and weight
8. if(age>=18){
9. if(weight>50){
10. System.out.println("You are eligible to donate bl
ood");
11. }
12. }
13.}}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 51


SWITCH STATEMENT Example:

The Java switch statement executes one statement public class SwitchExample {
from multiple conditions. It is like if-else-if ladder public static void main(String[] args) {
statement. //Declaring a variable for switch expression
SYNTAX: int number=20;
switch(expression){ //Switch expression
case value1: switch(number){
//code to be executed; //Case statements
case 10: System.out.println("10");
break; //optional
break;
case value2: case 20: System.out.println("20");
//code to be executed; break;
break; //optional case 30: System.out.println("30");
...... break;
//Default case statement
default:System.out.println("Not in
default: 10, 20 or 30");
code to be executed }
if all cases are }
}
not matched;
}10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 52
WHILE LOOP

• The Java while loop is used to iterate a part of the • Example


program several times. If the number of iteration is 1.public class WhileExample {
not fixed, it is recommended to use while loop.
2.public static void main(String[] args) {
SYNTAX: 3. int i=1;
4. while(i<=10){
while(condition){

//code to be executed 5. System.out.println(i);


}
6. i++;
7. }
8.}
9.}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 53


DO-WHILE LOOP

• The Java do-while loop is used to iterate a part of the


program several times. If the number of iteration is not
• Example
fixed and you must have to execute the loop at least once, it
is recommended to use do-while loop.
• The Java do-while loop is executed at least once because 1. public class DoWhileExample {
condition is checked after loop body. 2. public static void main(String[] args)
• Syntax: {
1. do{
3. int i=1;
2. //code to be executed
3. }while(condition);
4. do{
5. System.out.println(i);
6. i++;
7. }while(i<=10);
8. }
9. }

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 54


FOR LOOP

1. Initialization: It is the initial condition which is


executed once when the loop starts. Here, we can • Syntax:
initialize the variable, or we can use an already
initialized variable. It is an optional condition. for(initialization;condition;incr/decr)
{
2. Condition: It is the second condition which is
executed each time to test the condition of the loop.
//statement or code to be executed
It continues execution until the condition is false. It
must return boolean value either true or false. It is
}
an optional condition. • Example:
3. Statement: The statement of the loop is executed
each time until the second condition is false.
for(int a=0; a<=n; a++)
4. Increment/Decrement: It increments or {
decrements the variable value. It is an optional //code
condition.
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 55
EXAMPLE
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 56
JUMP STATEMENTS- BREAK,CONTINUE & RETURN
• BREAK STATEMENT:

The Java break statement is used to public class BreakExample {


public static void main(String[] args) {
break loop or switch statement. It breaks
//using for loop
the current flow of the program at
for(int i=1;i<=10;i++){
specified condition. In case of inner
if(i==5){
loop, it breaks only inner loop.
//breaking the loop
Syntax:
break;
jump-statement;
}
break;
System.out.println(i);
}
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM Output : 1 2 3 4 57
CONTINUE STATEMENT

The Java continue statement is used to continue the • Example:


loop. It continues the current flow of the program and 1. public class ContinueExample {
skips the remaining code at the specified condition. In 2. public static void main(String[] args) {
case of an inner loop, it continues the inner loop only.
3. //for loop
Syntax:
jump-statement; 4. for(int i=1;i<=10;i++){
continue; 5. if(i==5){
Output: 6. //using continue statement
1
2
7. continue;//
3 it will skip the rest statement
4
6
8. }
7 9. System.out.println(i);
8
9 10. }
10
11.} }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 58
RETURN KEYWORD

Java return keyword is used to complete the Example:


execution of a method. The return followed by the public class ReturnTypeTest2 {
appropriate value that is returned to the caller. This public int add(int x, int y) { // with arguments
value depends on the method return type like int int z = x+y;
method always return an integer value . return z;
}
Points to remember
public static void main(String args[]) {
• It is used to exit from the method.
ReturnTypeTest2 test = new
• It is not allowed to use return keyword in ReturnTypeTest2();
void method. int add = test.add(10, 20);
• The value passed with return keyword System.out.println("The sum of x and y is:
" + add);
must match with return type of the
}
method.
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 59
TYPE CASTING / CONVERSION JAVA 1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The 4. {
automatic conversion is done by the compiler and manual conversion 5. int x = 7;
performed by the programmer.
6. //
automatically converts the integer type into long
type
7. long y = x;
Widening Type Casting 8. //
Converting a lower data type into a higher one is called widening type casting. automatically converts the long type into float ty
also known as implicit conversion or casting down. It is done automatically. pe
byte -> short -> char -> int -> long -> float -> double
9. float z = y;
Narrowing Type Casting
10.System.out.println("Before conversion, int valu
Converting a higher data type into a lower one is called narrowing type casting. e "+x);
It is also known as explicit conversion or casting up
11.System.out.println("After conversion, long valu
double -> float -> long -> int -> char -> short -> byte
e "+y);
12.System.out.println("After conversion, float valu
Output : Before conversion, the value is: 7
e "+z);
After conversion, the long value is: 7
After conversion, the float value is: 7.0 13.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 60
14.}
Narrow Casting Program
• Example:
class NarrowCast
• Output:
{
Public static void main(String args[]) Before narrow cast :
{ 10.80
float amount=10.80f;
//assume that 10.80 lack of amount
System.out.println(“Before narrow cast :”+amount); After narrow cast : 10
Int return_balance= (int) amount;
System.out.println(“After narrow cast “ + return_balance);
// it gives the result in int only like 10 (with loss of data)
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 61
SIMPLE JAVA PROGRAM
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
} }
• Class: keyword is used to declare a class
• Public: keyword is an access modifier which represents visibility. It means it is visible to all.
• Static: there is no need to create an object to invoke the static method
• Void: is the return type of the method. It means it doesn't return any value
• Main: represents the starting point of the program execution
• String[] args: is used for command line arguments
• System.out.println(): is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 62


OBJECTS AND CLASSES IN JAVA

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 63


Java Program to illustrate how to define a class and fields

class Student{ //Defining a Student class.


//defining fields
int id=101; //field or data member or instance variable
String name=“Ankith”;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 64
CONSTRUCTOR IN JAVA
A constructor is a block of codes similar to the class Bike{
method. It is called when an instance of the class is
created. At the time of calling constructor, memory //creating a default constructor
for the object is allocated in the memory.
Rules for creating Java constructor
Bike(){
• Constructor name must be the same as its class name System.out.println("Bike is created");}
• A Constructor must have no explicit return type
//main method
• A Java constructor cannot be abstract, static, final, and
synchronized public static void main(String args[]){
There are two types of constructors in Java: //calling a default constructor
Default constructor (no-arg constructor)
Bike b=new Bike();
Parameterized constructor
Syntax:
}

class_name(){} }

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 65


Example of default constructor that displays the default values

//Let us see another example of default constructor


//which displays the default values
class Student{
int id=102;
String name=“ Mallanna” ;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects
Student s1=new Student();
Student s2=new Student();
//displaying values of the object
s1.display();
s2.display();
} }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 66
Example of parameterized constructor

//Java Program to demonstrate the use of the parameterized constructor.


class Studentinfo{
int id;
String name; //creating a parameterized constructor
Studentinfo(int i,String n){
id = i;
name = n;
} //method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){ //creating objects and passing values
Studentinfo s1 = new Studentinfo(101,"Karan");
Studentinfo s2 = new Studentinfo(102,“Raman"); //calling method to display the values of object
s1.display();
s2.display();
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 67
}
Constructor Overloading in Java

//Java program to overload constructors name = n;


class Student5{ age=a;
int id; }
String name; void display()
int age; {System.out.println(id+" "+name+" "+age);}

//creating two arg constructor


Student5(int i,String n){ public static void main(String args[]){

id = i; Student5 s1 = new Student5(111,"Karan");


Student5 s2 = new Student5(222,"Aryan",25);
name = n;
} s1.display();
s2.display();
//creating three arg constructor
Student5(int i,String n,int a){ }

id = i; }

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 68


METHOD IN JAVA

A method is a block of code or collection of statements or a class Main { // create a method


set of code grouped together to perform a certain task or
operation. It is used to achieve the reusability of code. We public int addNumbers(int a, int b) {
write a method once and use it many times. We do not
require to write code again and again.
int sum = a + b;
Syntax return sum; // return value
modifier return-Type nameOfMethod (Parameter List) { }
// method body public static void main(String[] args) {
} int num1 = 25;
int num2 = 15;
Types of Method: Main obj = new Main(); // create an object of Main
int result = obj.addNumbers(num1, num2); // calling
• Predefined Method – println(), sqrt(),comparTo()..etc method
• User-defined Method – withdraw(), deposit(), pinchange() etc System.out.println("Sum is: " + result);
}
}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 69


ACCESS MODIFIERS

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class,
within the package and outside the package.

Access Modifier within class within package outside package by outside package
subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public
10/06/2024 Y Y
R.SATHEESH Y
, ASST.PROF, CSIT, MLRITM Y 70
Example
class Ece_rocks{
private int data=40;
private void msg(){
System.out.println("Hello EEC Guys lets play with Java");}
}
public class Simple{
public static void main(String args[]){
Ece_rocks obj=new Ece_rocks();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 71
THIS KEYWORD

This is a reference variable that refers to the current object.


• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 72


class Student{
int rollno;
class A{
String name;
float fee; void m(){System.out.println("hello m");}
Student(int rollno,String name,float fee){ void n(){
this.rollno=rollno; System.out.println("hello n");
this.name=name; //m();//same as this.m()
this.fee=fee; }
this.m();
void display(){
System.out.println(rollno+" "+name+" "+fee);}
}
} }
class TestThis2{ class TestThis4{
public static void main(String args[]){ public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
A a=new A();
Student s2=new Student(112,"sumit",6000f);
a.n();
s1.display();
s2.display();
}
}} }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 73
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.
• To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
• It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
• It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts

How can an object be unreferenced?


• There are many ways:
• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 74


METHOD OVERLOADING

• If a class has multiple methods having same class OverloadingCalculation1{


name but different in parameters, it is known
as Method Overloading. void sum(int a,long b){
• If we have to perform only one operation, System.out.println(a+b);}
having same name of the methods increases
void sum(int a,int b,int c){
the readability of the program.
System.out.println(a+b+c);}
There are two ways to overload the method in public static void main(String args[]){
java OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//
1. By changing number of arguments now second int literal will be promoted to long
2. By changing the data type obj.sum(20,20,20);
}
}

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 75


class Dog{ // Static Binding
METHOD BINDING private void eat(){System.out.println("dog is eating...");}

• Connecting a method call to the public static void main(String args[]){

method body is known as binding. Dog d1=new Dog();


d1.eat();
There are two types of binding }

• Static Binding (also known as Early Binding). }


………………………………………………………………………….
• Dynamic Binding (also known as Late
class Animal{ // Dynamic Binding
Binding).
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 76
INHERITANCE IN JAVA

Inheritance in Java is a mechanism in which one object acquires all the 1. class Animal{
properties and behaviors of a parent object.
Terms used in Inheritance: 2. void eat(){System.out.println("eating...");}
• Class: A class is a group of objects which have common properties. It is 3. }
a template or blueprint from which objects are created. 4. class Dog extends Animal{
• Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
5. void bark()
{System.out.println("barking...");}
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class. 6. }
• Reusability: As the name specifies, reusability is a mechanism which 7. class TestInheritance{
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
8. public static void main(String args[]){
defined in the previous class. 9. Dog d=new Dog();
• Syntax: 10.d.bark();
class Subclass-name extends Superclass-name
11.d.eat();
{
//methods and fields 12.}}
}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 77
OVERRIDING IN JAVA

If subclass (child class) has the same method as 1. class Vehicle{


2. //defining a method
declared in the parent class, it is known as method
3. void run()
overriding in Java. {System.out.println("Vehicle is running");}
Usage of Java Method Overriding 4. }
• Method overriding is used to provide the specific 5. //Creating a child class
implementation of a method which is already 6. class Bike2 extends Vehicle{
provided by its superclass. 7. //
defining the same method as in the parent class
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding 8. void run()
{System.out.println("Bike is running safely");}
1. The method must have the same name as in the
9.
parent class
10. public static void main(String args[]){
2. The method must have the same parameter as in the 11. Bike2 obj = new Bike2();//creating object
parent class. 12. obj.run();//calling method
3. There must be an IS-A relationship (inheritance). 13. }
14.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 78
EXCEPTIONS IN JAVA
• The Exception Handling in Java is one of the • Example
powerful mechanism to handle the runtime
1.public class JavaExceptionExample{
errors so that normal flow of the application
can be maintained. 2. public static void main(String args[])
• an exception is an event that disrupts the {
normal flow of the program 3. try{
• Types of Java Exceptions: 4. //code that may raise exception
1. Checked Exception 5. int data=100/0;
2. Unchecked Exception 6. }catch(ArithmeticException e)
3. Error {System.out.println(e);}
7. //rest code of the program
• Java Exception handling mechanism: 8. System.out.println("rest of the code...")
;
 { try, catch, throw, throws, finally }
9. }
10/06/2024 10.
R.SATHEESH , ASST.PROF, } MLRITM
CSIT, 79
PARAMETER PASSING
Example 1: Example 2:
1. class Operation{ 1. class Operation2{
2. int data=50; 2. int data=50;
3. void change(int data){ 3. void change(Operation2 op){
4. data=data+100;// 4. op.data=op.data+100;//
changes will be in the local variable only changes will be in the instance variable }
5. } 5. public static void main(String args[]){
6. public static void main(String args[]){ 6. Operation2 op=new Operation2();
7. Operation op=new Operation(); 7. System.out.println("before change "+op.data)
8. System.out.println("before change "+op.data); ;
8. op.change(op);//passing object
9. op.change(500);
9. System.out.println("after change "+op.data);
10. System.out.println("after change "+op.data);
10.}
11.}
11.}
12.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 80
RECURSION IN JAVA
1.public class RecursionExample3 {
• Recursion in java is a process in which
2. static int factorial(int n){
a method calls itself continuously. A
3. if (n == 1)
method in java that calls itself is called
recursive method. 4. return 1;
5. else
• It makes the code compact but
complex to understand. 6. return(n * factorial(n-1));
Syntax: 7. }
returntype methodname(){ 8.public static void main(String[] args)
{
//code to be executed
9.System.out.println("Factorial of 5 is: "
methodname();//calling same method +factorial(5));
} 10.} }
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 81
INNAER CLASS
• Java inner class or nested class is a class Example:
which is declared inside the class or 1. class TestMemberOuter1{
interface.
2. private int data=30;
• We use inner classes to logically group 3. class Inner{
classes and interfaces in one place so that
it can be more readable and maintainable. 4. void msg()
{System.out.println("data is "+data);}
• Syntax:
5. }
1. class Java_Outer_class{
6. public static void main(String args[]){
2. //code 7. TestMemberOuter1 obj=new TestMemberOut
3. class Java_Inner_class{ er1();
4. //code 8. TestMemberOuter1.Inner in=obj.new Inner();
5. }
6. } 9. in.msg();
10. }
11.}
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 82
STRING CLASS

• The java.lang.String class provides a lot of methods to work on string.


By the help of these methods, we can perform operations on string
such as trimming, concatenating, converting, comparing, replacing
strings etc.
• Java String is a powerful concept because everything is treated as a
string if you submit any form in window based, web based or mobile
application.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 83


 char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if
index<0||>= length of String.
 boolean equals(Object obj): Compares the string with the specified string and returns true if both
matches else false.
 boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
 int compareTo(String string): This method compares the two strings based on the Unicode value
of each character in the strings.
 int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the
case during comparison.
 boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the
specified offset index) is having the specified prefix or not.
 boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes
then it returns true else false.
 boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.

10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 84


 String concat(String str): Concatenates the specified string “str” at the end of the string.
 String replace(char oldChar, char newChar): It returns the new updated string after changing all the
occurrences of oldChar with the newChar.
 boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char
values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
 String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by
specified locale.
 String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
 public static String format(): This method returns a formatted java String
 String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
 String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
 char[] toCharArray(): Converts the string to a character array.
 static String copyValueOf(char[] data): It returns a string that contains the characters of the specified
character array.
 static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra
arguments – initial offset of subarray and length of subarray.
 void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to
the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting
fromdestBegin).
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 85
 static String valueOf(): This method returns a string representation of passed arguments such as int, long,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}}
Output:
Strings first and second are equal: true
10/06/2024 R.SATHEESH , ASST.PROF, CSIT, MLRITM 86
Strings first and third are equal: false

You might also like