1 of 215

OOPS THROUGH JAVA

2 of 215

UNIT-I

2

3 of 215

3

4 of 215

4

5 of 215

5

OS/Hardware

machine code

C source code

myprog.c

gcc

myprog.exe

Platform Dependent

JVM

bytecode

Java source code

myprog.java

javac

myprog.class

OS/Hardware

Platform Independent

6 of 215

ISSUES:

    • Portability
    • Platform Independence
    • Security
    • Reliability
    • Reusability / Extensibility
    • Shareability( Networking)

6

7 of 215

DIFFERENT PROGRAMMING PARADIGMS

  • Functional/Procedural Programming/Procedure Oriented Programming) (POP)
    • Program is a list of instructions to the computer.
    • Procedural programming is about writing procedures or methods that perform operations on the data.
  • Object-oriented programming (OOP)
    • Program is composed of a collection objects that communicate with each other.
    • While object-oriented programming is about creating objects that contain both data and methods.

7

8 of 215

SOFTWARE DESIGN APPROACHES:TOP DOWN VS BOTTOM UP:

8

9 of 215

HIERARCHY OF PROGRAMMING PARADIGMS:

9

10 of 215

10

11 of 215

PROCEDURE ORIENTED PROGRAMMING

11

12 of 215

POP VS OOP:

12

13 of 215

POP : ADVANTAGES VS DISADVANTAGES

  • Advantages:
  • Its relative simplicity, and ease of implementation of compilers and interpreters
  • The ability to re-use the same code at different places in the program without copying it.
  • An easier way to keep track of program flow.
  • The ability to be strongly modular or structured.
  • Needs only less memory.

1313

  • Disadvantages:
  • Data is exposed to whole program, so no security for data.
  • Difficult to relate with real world objects.
  • Difficult to create new data types reduces extensibility.
  • Importance is given to the operation on data rather than the data.

14 of 215

14

15 of 215

OBJECT-ORIENTED PROGRAMMING - ADVANTAGES

  • Object-oriented programming has several advantages over procedural programming:
  • OOP is faster and easier to execute (w.r.t Program Development)
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time (WORA – Write Once Run Any where)

15

16 of 215

OBJECT-ORIENTED PROGRAMMING - ADVANTAGES

  • Simplicity: Software objects model real world objects, so the complexity is reduced and the program structure is very clear.
  • Modularity: Each object forms a separate entity whose internal workings are decoupled from other parts of the system.
  • Modifiability: It is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.
  • Extensibility: Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.
  • Maintainability: Objects can be maintained separately, making locating and fixing problems easier.
  • Reusability: Objects can be reused in different programs.

16

17 of 215

DISADVANTAGES OF OOP:

  • Designing a program in OOP concept is a little bit tricky.
  • The programmer should have a proper planning before designing a program using OOP approach.
  • Since everything is treated as objects in OOP, the programmers need proper skill such as design skills, programming skills, thinking in terms of objects etc.
  • The size of programmes developed with OOP is larger than the procedural approach.
  • Since larger in size, that means more instruction to be executed, which results in the slower execution of programmes.

17

18 of 215

OOP(S) - CONCEPTS

OOP stands for Object-Oriented Programming.

There are four main OOP concepts

18

19 of 215

ABSTRACTION

  • Abstraction is the process of hiding certain details and showing only essential information to the user. (What is to be done ? Rather than how it is done ?)
  • Abstraction means using simple things to represent complexity.
  • For eg:
  • 1) We all know how to turn the TV on, but we don’t need
  • to know how it works (Internal Circuit /Components ).
  • 2) Use ATM

19

20 of 215

WHAT ARE CLASSES AND OBJECTS?

  • Classes and objects are the two main aspects of object-oriented programming.
  • class is a template for objects (i.e., collection of objects of same type) and
  • an object is an instance of a class.

20

21 of 215

ENCAPSULATION

  • A way to achieve Abstraction & provides “data hiding”.
  • Encapsulation, is to make sure that "sensitive" data is hidden from users.
  • Encapsulation is the practice of keeping fields within a class private, then providing access to them via public methods.
  • It’s a protective barrier that keeps the data and code safe within the class itself.
  • This way, we can re-use objects like code components or variables without allowing open access to the data system-wide.

21

22 of 215

INHERITANCE

  • It  is a mechanism in which one object acquires all the properties and behaviours of a parent object.
  • It is an important part of OOPs (Object Oriented programming system).
  • The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
  • Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. 

22

23 of 215

POLYMORPHISM

  • The word polymorphism means having many forms. 
  • The word “poly” means many and “morphs” means forms, So it means many forms.
  • The same word to mean different things in different contexts.
  • One form of polymorphism in Java is method overloading. That’s when different meanings are implied by the code itself.
  • The other form is method overriding
  • Ex: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. 

23

24 of 215

IN REAL LIFE - OOPS

24

25 of 215

25

26 of 215

26

27 of 215

WHAT IS JAVA?

  • Java is a popular Internet programming language, created in 1995.
  • It is owned by Oracle (Previously owned by Sun Micro Systems) , and more than 3 billion devices run Java.
  • It is used for:
  • Mobile applications (specially Android apps)
  • Desktop applications
  • Web applications
  • Web servers and Application servers
  • Games
  • Database connection
  • And much, much more!

27

28 of 215

WHY JAVA ?

  • Java is one of the most popular and widely used programming language and platform.
  • A platform is an environment that helps to develop and run programs written in any programming language.�Java is fast, reliable and secure.
  • From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner.

28

29 of 215

HISTORY OF JAVA

  • James Arthur Gosling, (born May 19, 1955) is a Canadian computer scientist, best known as the founder and lead designer behind the Java programming language.
  • Java was started as a project called "Oak" by James Gosling in June 1991 at Sun at Microsystems of USA.
  • The language was initially called Oak after an oak tree that stood outside Gosling's office. Later the project went by the name Green and was finally renamed Java, from Java coffee. "Java" being used as slang for "coffee"
  • Gosling designed Java with a C/C++-style syntax that system and application programmers would find familiar.
  • The first public implementation was Java 1.0 in 1995.

29

30 of 215

JAVA VERSIONS

  • JDK Alpha and Beta (1995)
  • JDK 1.0 (23rd Jan 1996)
  • JDK 1.1 (19th Feb 1997)
  • J2SE 1.2 (8th Dec 1998)
  • J2SE 1.3 (8th May 2000)
  • J2SE 1.4 (6th Feb 2002)
  • J2SE 5.0 (30th Sep 2004)

30

31 of 215

JAVA EDITIONS/PLATFORMS

31

32 of 215

FEATURES OF JAVA (BUZZ WORDS)

  • Simple
  • Secured
  • Object Oriented
  • Robust
  • Platform Independence

(Architecture Neutral

  • Portable
  • Compiled & Interpreted

32

  • Multithreaded
  • Dynamic
  • Distributed
  • High Performance(JIT)
  • Java is case-sensitive

33 of 215

JAVA ENVIRONMENT

  • The programming environment of Java consists of three components mainly:
  • JDK
  • JRE
  • JVM

33

34 of 215

JDK & JAVA API:

  • JDK = JAVA DEVELOPMENT KIT
  • JDK = JAVA TOOLS + JAVA API

34

35 of 215

JAVA TOOLS JAVA API

  1. javac
  2. java
  3. javadoc
  4. javah
  5. javap
  6. jdb
  7. appletviewer

35

  1. Packages
  2. Classes / Interfaces
  3. methods

36 of 215

JAVA API PACKAGES:

  • API : Application Programming Interface
  • Standalone Application Programming
    • java.lang
    • java.util
    • java.io
  • Applets / GUI & Network Programming
    • java.net
    • java.applet

36

37 of 215

JDK VS JRE VS JVM

  • JDK (Java Development Kit):
  • JDK contains everything that will be required to develop and run Java application.
  • JRE (Java Runtime Environment):
  • JRE contains everything required to run Java application which has already been compiled. It doesn’t contain the code library required to develop Java application.
  • JVM (Java Virtual Machine):
  • JVM is a virtual machine which works on top of your operating system to provide a recommended environment for your compiled Java code. JVM only works with bytecode.
  • Hence you need to compile your Java application(.java) so that it can be converted to bytecode format (also known as the .class file).
  • Which then will be used by JVM to run an application. JVM only provide the environment needed to executed Java Bytecode.

37

38 of 215

JAVA VIRTUAL MACHINE (JVM)

  • The Java Language is a language specification.
  • The Sun JVM is written in C, JVM run on your machine is a platform-dependent executable code.
  • The Java Virtual Machine by Oracle, i.e., Oracle JVM(HotSpot) on which Java Code is executed is written in C++.

38

39 of 215

JAVA VIRTUAL MACHINE

  • JVM is a engine that provides runtime environment to drive the Java Code or applications. It converts Java bytecode into machines language.
  • JVM is a part of JRE(Java Run Environment). It stands for Java Virtual Machine
  • In other programming languages, the compiler produces machine code for a particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual Machine.
  • First, Java code is complied into bytecode. This bytecode gets interpreted on different machines
  • Between host system and Java source, Bytecode is an intermediary language.
  • JVM is responsible for allocating memory space.

39

40 of 215

JAVA VIRTUAL MACHINE

40

41 of 215

JAVA IS BOTH COMPILED &INTERPRETED LANGUAGE

  • compiler is a program which converts a program from one level of language to another. Example conversion of C++ program into machine code.
  • The java compiler converts high-level java code into bytecode (which is also a type of machine code).
  • An interpreter is a program which converts a program at one level to another programming language at the same level. Example conversion of Java program into C++
  • In Java, the Just In Time Code generator converts the bytecode into the native machine code which are at the same programming levels.
  • Hence, Java is both compiled as well as interpreted language.
  • JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It is used to speed up the execution time
  • In comparison to other compiler machines, Java may be slow in execution.

41

42 of 215

JAVA PORTABILITY

  • Java Source Code (Written by Developer) (Machine Neutral)
  • Compiled Code / Byte Code (Machine Neutral)
  • Byte Code Interpreted & executed (Executed by JVM)

(Machine Specific)

c

42

43 of 215

WORA:

43

44 of 215

JAVA BYTECODE

  • Java bytecode is a compiled code of a Java program or we can say it is a set of instructions for JVM.
  • It can execute on any platform which has a Java installation.
  • After compilation, the Java code is converted into .class file which is also known as Bytecode/Intermediate Code.
  • Java code is machine independent because of the JVM(Java virtual machine) that runs the bytecode in the processor. (But JVM is Machine Dependent)
  • Also Java programmer doesn’t require knowledge about the specific OS and processors where the program will run because JVM takes care of those.

44

45 of 215

45

46 of 215

JAVA EXECUTION IS SLOWER ? ? ?

46

47 of 215

47

48 of 215

48

49 of 215

49

50 of 215

JAVA BASICS:

  • Where to download Java.
  • How to install Java.
  • Setting up the Environment Variables.
  • Our First Java Program.
  • How to compile a Java application.
  • How to run a Java Application.
  • Difference between important terms in Java (JDK vs JRE or J2SE vs J2EE..).

50

51 of 215

HOW TO DOWNLOAD JAVA

51

52 of 215

JAVA INSTALLATION

  • There are no special requirements when installing Java. 
  • Be sure that you have suitable permissions on your computer to install software.
  • It can be installed like any other software (.exe)

52

53 of 215

SETTING UP THE ENVIRONMENT VARIABLES

  • You need to set PATH to compile Java source code and create Java class files.  
  • JDK bin directory contains javac and java  commands to compile and run Java programs.
  • CLASSPATH is little different than Path and it's used by JVM rather than Operating System to load classes at runtime. �
  • JAVA_HOME: This environment variable will point to the location of the Java home directory. (C:\Program Files\Java\jdk1.6.0_02)�
  • Note: PATH/JAVA_HOME is for OS and CLASSPATH is for JVM
  • PATH/JAVA_HOME : C:\Program Files\Java\jdk1.8.0_51\bin (Tools)
  • CLASSPATH: C:\Program Files\Java\jdk1.8.0_51\lib ( Supporting files – jars)

53

54 of 215

SAMPLE JAVA PROGRAM (MYCLASS.JAVA)

import java.lang.*;

public class MyClass

{

public static void main(String[] args)

{

System.out.println("Welcome to Java World!");

}

}

54

55 of 215

JAVA MAIN() METHOD

55

56 of 215

STRUCTURE OF JAVA PROGRAM

  1. Documentation Section - Suggestion
  2. Package Section - Optional
  3. Import Section - Optional
  4. Interface Section - Optional
  5. Class Definition(s) - Required / optional
  6. Main method class - Essential

56

57 of 215

57

58 of 215

JAVA COMMENTS (DOCUMENTATION)

// Single-Line Comment

/*

* Multiple-Line comment

*/

/**

* JavaDoc comment

*/

58

59 of 215

JAVA TOOLS/IDE:

1) To compile a java program:

Use javac

Example:

C:\Users\Rollno>javac MyClass.java

  • 2) To run a java program:
  • Use java
  • Example:
  • C:\Users\Rollno>java MyClass

59

60 of 215

JAVA PROGRAMMING BASICS – DATA TYPES

  • Two categories:
  • Primitive (Fundamental)
    • List shown in next slide
  • Non-Primitive ( Referenced – Group of values / Advanced data types)
    • Class
    • Interface
    • String
    • Array etc.,

60

61 of 215

DATA TYPES:

61

62 of 215

JAVA KEYWORDS

62

abstract

boolean

break

byte

byvalue

case

cast *

catch

char

class

const *

continue

default

do

double

else

extends

false #

final

finally

float

for

future *

generic *

goto *

if

implements

import

inner *

instanceof

int

interface

long

native

new

null #

operator *

outer *

package

private

protected

public

rest *

return

short

static

super

switch

synchronized

this

threadsafe *

throw

throws

transient

true #

try

var *

void

volatile

while

Note: Total 60=33 (exists)+27 new keywords & some( *) are reserved for future purpose,

# - defined by java

63 of 215

JAVA PRIMITIVE DATA TYPES

63

Default Value

0

0

0

0

0.0

0.0

\u0000

false

64 of 215

JAVA CODING(NAMING) CONVENTIONS - STANDARDS:

  • For good maintenance and readability of code in java

64

65 of 215

JAVA CODING(NAMING) CONVENTIONS - STANDARDS:

65

For example : package java.lang;

package lbrce.cse;

package lbrce.ece;

For example : RED, YELLOW,GREEN

MAX_PRIORITY,

MAX_MARKS

RED, YELLOW, MAX_PRIORITY, MAX_STOCK_COUNT

66 of 215

VARIABLES – TYPES:

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

66

67 of 215

HOW TO DECLARE VARIABLES?

  • We can declare variables in java as follows:

67

68 of 215

TYPES OF VARIABLES IN JAVA:

  • There are three types of variables in Java:
  • Local Variables
  • Instance Variables
  • Static Variables

68

69 of 215

1) LOCAL VARIABLES

  • DEF: A variable defined within a block or method or constructor is called local variable.
  • These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
  • The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.
  • Initialization of Local Variable is Mandatory.

69

70 of 215

EXAMPLE:

  • public void StudentAge()
  • {
  • // local variable age
  • int age = 0;
  • age = age + 5;
  • }

70

71 of 215

2) INSTANCE VARIABLES

  • DEF: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
  • As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
  • Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
  • Initialization of Instance Variable is not Mandatory. Its default value is 0
  • Instance Variable can be accessed only by creating objects.

71

72 of 215

EXAMPLE:

  • class Marks
  • {
  • // These variables are instance variables.
  • // These variables are in a class
  • // and are not inside any function
  • int engMarks;
  • int mathsMarks;
  • int phyMarks;
  • }

72

73 of 215

3)STATIC VARIABLES

  • DEF: Static variables are also known as Class variables.
  • These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
  • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
  • Static variables are created at the start of program execution and destroyed automatically when execution ends.
  • Initialization of Static Variable is not Mandatory. Its default value is 0

73

74 of 215

EXAMPLE:

  • class Emp
  • {
  • // static variable salary
  • public static double salary;
  • }
  • For Accessing Static Variable:
  • Emp.salary

74

75 of 215

JAVA OPERATORS:

  • Operator in java is a symbol that is used to perform operations.
  • For example: +, -, *, / etc.

75

76 of 215

76

77 of 215

RELATIONAL OPERATORS:

77

Operator

Meaning

==

Is equal to

!=

Is not equal to

>

Greater than

<

Less than

>=

Greater than or equal to

<=

Less than or equal to

78 of 215

LOGICAL OPERATORS:

78

Operator

Meaning

Work

&&

Logical AND

If both operands are true then only "logical AND operator" evaluate true.

||

Logical OR

The logical OR operator is only evaluated as true when one of its operands evaluates true. If either or both expressions evaluate to true, then the result is true.

!

Logical Not

Logical NOT is a Unary Operator, it operates on single operands. It reverses the value of operands, if the value is true, then it gives false, and if it is false, then it gives true.

79 of 215

ASSIGNMENT OPERATORS:

  • The Java Assignment Operators are used when you want to assign a value to the expression. 
  • The assignment operator denoted by the single equal sign =
  • Example:
  • int a = 6;
  • float b = 6.8F;

79

80 of 215

JAVA COMPOUND ASSIGNMENT OPERATORS:

  • Java provides some special Compound Assignment Operators, also known as Shorthand Assignment Operators.
  • It's called shorthand because it provides a short way to assign an expression to a variable.
  • For example, you write a statement:
  • a = a+6;
  • In Java, you can also write the above statement like this:
  • a += 6;

80

81 of 215

UNARY ARITHMETIC OPERATORS:

  • In Java, unary arithmetic operators are used to increasing or decreasing the value of an operand. 
  • Increment operator adds 1 to the value of a variable, whereas the decrement operator decreases a value.

81

Example

Description

val = a++;

Store the value of "a" in "val" then increments.

val = a--;

Store the value of "a" in "val" then decrements.

val = ++a;

Increments "a" then store the new value of "a" in "val".

val = --a;

Decrements "a" then store the new value of "a" in "val".

82 of 215

BITWISE OPERATORS IN JAVA

  • Bitwise operators are used to perform manipulation of individual bits of a number.
  • Bitwise OR (|) 
  • Bitwise AND (&)
  • Bitwise XOR (^) 
  • Bitwise Complement (~)
  • Shift Operators:
  • Signed Right shift operator (>>) ,
  • Left shift operator (<<),
  • Unsigned Right shift operator (>>>) 

82

83 of 215

BITWISE OR (|) 

  • a = 5 = 0101 (In Binary)
  • b = 7 = 0111 (In Binary)

  • Bitwise OR Operation of 5 and 7
  • 0101
  • | 0111
  • ________
  • 0111 = 7 (In decimal)

83

84 of 215

BITWISE AND (&)

  • a = 5 = 0101 (In Binary)
  • b = 7 = 0111 (In Binary)

  • Bitwise AND Operation of 5 and 7
  • 0101
  • & 0111
  • ________
  • 0101 = 5 (In decimal)

84

85 of 215

BITWISE XOR (^) 

  • a = 5 = 0101 (In Binary)
  • b = 7 = 0111 (In Binary)

  • Bitwise XOR Operation of 5 and 7
  • 0101
  • ^ 0111
  • ________
  • 0010 = 2 (In decimal)

85

86 of 215

BITWISE COMPLEMENT (~) 

  • a = 5 = 0101 (In Binary)
  • Bitwise Compliment Operation of 5
  • ~ 0101
  • _______
  • 1010 = 10 (In decimal)
  • Note:  Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.

86

87 of 215

SHIFT OPERATORS:

  • These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively.
  • They can be used when we have to multiply or divide a number by two. 

87

88 of 215

SIGNED RIGHT SHIFT OPERATOR (>>) 

  • Shifts the bits of the number to the right and fills 0 on left as a result.
  • The leftmost bit depends on the sign of initial number.
  • Example 1:
  • a = 10
  • a>>1 = 5

  • Example 2:
  • a = -10
  • a>>1 = -5
  • We preserve the sign bit.

88

89 of 215

LEFT SHIFT OPERATOR (<<)

  • Shifts the bits of the number to the left and fills 0 on left as a result.
  • Example :
  • a = 5 = 0000 0101
  • b = -10 = 1111 0110

  • a << 1 = 0000 1010 = 10
  • a << 2 = 0001 0100 = 20

  • b << 1 = 0000 1010 = - 20
  • b << 2 = 0001 0100 = - 40

89

90 of 215

UNSIGNED RIGHT SHIFT OPERATOR (>>>)

  • Shifts the bits of the number to the right and fills 0 on left as a result. The leftmost bit is set to 0.
  • (>>>) is unsigned-shift; it’ll insert 0.
  • But (>>) is signed, and will extend the sign bit.
  • Example 1:
  • a = 10
  • a>>>1 = 5
  • Example 2:
  • a = -10
  • a>>>1 = 2147483643
  • DOES NOT preserve the sign bit.

90

91 of 215

91

Operator

Meaning

+=

Increments then assigns

-=

Decrements then assigns

*=

Multiplies then assigns

/=

Divides then assigns

%=

Modulus then assigns

<<=

Binary Left Shift  and assigns

>>=

Binary Right Shift and assigns

>>>=

Shift right zero fill and assigns

&=

Binary AND assigns

^=

Binary exclusive OR and assigns

|=

Binary inclusive OR and assigns

92 of 215

JAVA INSTANCEOF OPERATOR:

  • The Java instanceof Operator is used to determining whether this object belongs to this particular (class or subclass or interface) or not.
  • Syntax:
  • object-reference instanceof type;

  • Example:
  • if (c instanceof Employee)
  • Note: Employee is class & c is an instance of that class

92

93 of 215

JAVA CONDITIONAL OPERATOR (TERNARY):

  • The Java Conditional Operator selects one of two expressions for evaluation, which is based on the value of the first operands.
  • It is also called ternary operator because it takes three arguments.
  • Syntax: expression1 ? expression2:expression3;
  • Example: c= a>b?a:b;

93

94 of 215

CONTROL STATEMENTS IN JAVA

  1. Sequential statements
  2. Control Statements (Decision Making & loops)

94

95 of 215

SEQUENTIAL STATEMENTS

  • Def:
  • These statements are executed by JVM one by one in a sequential manner.

95

96 of 215

CONTROL STATEMENTS

  • Def: Which alter the flow of execution and provide better control to the programmer on the flow of execution.

96

97 of 215

CONTROL STATEMENTS - TYPES

  1. if
  2. if….else
  3. switch

97

  1. while loop
  2. do….while loop
  3. for loop
  4. for-each loop
  5. break
  6. continue

98 of 215

SIMPLE IF & IF…ELSE & IF….ELSE…IF�(DECISION MAKING)

  • Syntax:
  • if(condition)
  • {
  • …….
  • }

98

  • Syntax:
  • if(condition)
  • {
  • …….
  • }
  • else
  • {
    • ………..
  • }

  • Syntax:
  • if(condition)
  • {
  • …….
  • }
  • else if(condition)
  • {
    • ………..
  • }
  • else
  • {
    • …..

}

99 of 215

SWITCH…CASE:

  • Syntax:
  • switch (expression)
  • {
  • case value1:
  • statement1;
  • break;
  • case value2:
  • statement2;
  • break;
  • .
  • .
  • case valueN:
  • statementN;
  • break;
  • default:
  • statementDefault;
  • }

99

100 of 215

LOOPS: WHILE & DO…WHILE

  • while loop: (Entry Controlled loop)
  • Syntax :
  • while (boolean condition)
  • {
  • loop statements...
  • }

100

  • do….while loop: (Exit Controlled loop)
  • Syntax :
  • do
  • {
  • statements..
  • }
  • while (condition);

101 of 215

LOOPS: FOR

  • Syntax:
  • for (initialization condition; testing condition; increment/decrement)
  • {
  • statement(s)
  • }

101

102 of 215

LOOPS: FOR…EACH

  • Syntax:
  • for (data_type variable: Collection/array)
  • {
  • statement(s)
  • }

102

  • Example:
  • int arr[]={10,20,30,40,50};
  • for(int i:arr)
  • {
  • System.out.println(i);
  • }

103 of 215

INPUT AND OUTPUT

  • Two Methods:
  • InputStreamReader class & BufferedReader class
  • Scanner class

103

104 of 215

1) INPUTSTREAMREADER CLASS & BUFFEREDREADER CLASS

104

105 of 215

1) INPUTSTREAMREADER CLASS & BUFFEREDREADER CLASS

105

106 of 215

1) INPUTSTREAMREADER CLASS & BUFFEREDREADER CLASS : METHODS

1) read() - java.io.BufferedReader.read() method reads a single character from this buffered reader.

2) readLine() -  java.io.BufferedReader.readline() method read a line of text. A line is considered to be terminated by any one of a line feed ('\n')

106

107 of 215

2) SCANNER CLASS

  • Scanner is a class in java.util package
  • Used for obtaining the input of the primitive types like int, double, etc. and strings. 

107

108 of 215

2) SCANNER CLASS

108

109 of 215

2) SCANNER CLASS : METHODS

  • next() - It is used to get the next complete token from the scanner which is in use.
  • nextInt() - It scans the next token of the input as an Int.
  • nextShort() - It scans the next token of the input as a short.
  • nextLong() - It scans the next token of the input as a long.
  • nextFloat() - It scans the next token of the input as a float.
  • nextDouble() - It scans the next token of the input as a double.

109

110 of 215

COMMAND LINE ARGUMENTS: (I/O)

  • java command-line argument is an argument, that is
  • passed at the time of running the java program.
  • The arguments passed from the console can be received in the java program via main(String args[ ]) method and it can be used as an input.

110

111 of 215

EXAMPLE OF COMMAND-LINE ARGUMENTS

  • import java.lang.*;
  • class Carg
  • {
  • public static void main(String args[])
  • {
  • for(int i=0;i<args.length;i++)
  • System.out.println(args[i]);
  • }
  • }

111

  • Compile by
  • D:\> javac  Carg.java  
  • Run by
  • D:\> java  Carg  ECE sri 3 2
  • Output:
  • ECE - args[0]
  • sri - args[1]
  • 3 - args[2]
  • 2   - args[3]

112 of 215

TYPE CONVERSION IN JAVA

  • Issue:
  • When you assign value of one data type to another, the two types might not be compatible with each other. 
  • Solution:
  • 1) Widening or Automatic Type Conversion (Lower order to Higher order)
  • If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion.
  • 2) Narrowing or Explicit Conversion (Higher order to lower order)
  • If the data types are NOT compatible, they need to be casted or converted explicitly.

112

113 of 215

TYPE CONVERSION IN JAVA

  • 1) Widening or Automatic Type Conversion (Lower order to Higher order)
  • This happens when:
  • The two data types are compatible.
  • When we assign value of a smaller data type to a bigger data type.
  • But no automatic conversion is supported from numeric type to char or boolean.
  • Also, char and boolean are not compatible with each other.

113

114 of 215

AUTOMATIC TYPE CONVERSION : EXAMPLE

  • class Test
  • {
  • public static void main(String[] args)
  • {
  • int i = 100;
  • // automatic type conversion
  • long l = i;
  • // automatic type conversion
  • float f = l;
  • System.out.println("Int value "+i);
  • System.out.println("Long value "+l);
  • System.out.println("Float value "+f);
  • }
  • }

114

  • OUTPUT:
  • Int value 100
  • Long value 100
  • Float value 100.0

115 of 215

TYPE CONVERSION IN JAVA

  • 2) Narrowing or Explicit Conversion (Higher order to lower order)
  • If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.
  • This is useful for incompatible data types where automatic conversion cannot be done.

115

116 of 215

TYPE CONVERSION IN JAVA

  • Example: char and number are not compatible with each other. (Do explicit conversion)

116

117 of 215

JAVA ARRAYS:

  • Types:
  • 1) Single Dimensional (1-D)
  • 2) Multi Dimensional (2-D, 3-D, ….)

117

118 of 215

JAVA ARRAYS: 1-DIMENSIONAL

  • DEF: Normally, an array is a collection of similar type of elements (Homogeneous)
  • Java array is an object which contains elements of a similar data type.
  • Additionally, The elements of an array are stored in a contiguous memory location.
  • It is a data structure where we store similar elements.
  • We can store only a fixed set of elements in a Java array.
  • 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.

118

119 of 215

JAVA ARRAYS:

  • Advantages:
  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.
  • Disadvantages:
  • Size Limit: We can store only the fixed size of elements in the array.
  • It doesn't grow its size at runtime.
  • To solve this problem, collection framework is used in Java which grows automatically.

119

120 of 215

ARRAY VARIABLES: 3 STEP PROCESS

  • 1) Array Declaration
  • 2)  Array Construction
  • 3)  Array Initialization/Assignment

120

121 of 215

1) ARRAY DECLARATION

  • Syntax:
  • dataType[ ] array_variable;
  • (or)
  • dataType array_variable[ ];

121

  • Example:
  • int[ ] A;
  • (or)
  • int A[ ];

122 of 215

2)  ARRAY CONSTRUCTION

  • Syntax:
  • array_variable= new dataType[size];
  • Example-1:
  • A= new int[10];
  • Example-2:
  • Declaration and Construction combined:
  • int A[ ] = new int[10];

122

123 of 215

3) ARRAY INITIALIZATION / ASSIGNMENT

  • Syntax:
  • // Assigns an integer value 1 to the first element 0 of the array
  • A[0]=1;

  • // Assigns an integer value 2 to the second element 1 of the array
  • A[1]=2;

123

124 of 215

3) ARRAY INITIALIZATION / ASSIGNMENT

  • Declaring and initialize an Array
  • // Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.
  • int A[ ] = {1, 2, 3, 4};

124

125 of 215

JAVA ARRAY INDEX 

  • Example :
  • int[ ] age = new int[5];

125

126 of 215

JAVA ARRAYS: 2-DIMENSIONAL�(MULTI DIMENSIONAL)

  • Multidimensional arrays are array of arrays 
  • Each element of the array holding the reference of other array. 

126

127 of 215

JAVA ARRAYS: 2-DIMENSIONAL�(MULTI DIMENSIONAL)

  • Syntax:
  • dataType[ ][ ] array_variable;
  • (or)
  • dataType array_variable[ ][ ];

127

  • Example:
  • Int[ ][ ] A;
  • (or)
  • int A[ ][ ];

128 of 215

JAVA ARRAYS: 2-DIMENSIONAL�(MULTI DIMENSIONAL)

  • //2D array or matrix - Declaration
  • int A[ ][ ] = new int[10][20];
  • //2D array Initialization�int A[ ][ ] = { {2,7,9}, {3,6,1}, {7,4,2} };

128

129 of 215

JAVA ARRAYS: 2-DIMENSIONAL

129

int[ ][ ] A = new int[3][4];

130 of 215

EXAMPLE TO INITIALIZE A 2D ARRAY (JAGGED ARRAY)�(DIFFERENT SIZE -ROWS)

  • int[ ][ ] A = {
  • {1, 2, 3},
  • {4, 5, 6, 9},
  • {7},
  • };

130

131 of 215

2D ARRAY: REFERENCES

131

int Marks[ ][ ]=new int[4][3];

132 of 215

JAVA ARRAYS: 3-DIMENSIONAL�(MULTI DIMENSIONAL)

  • Syntax:
  • dataType[ ][ ][ ] array_variable;
  • (or)
  • dataType array_variable[ ][ ][ ];

132

  • Example:
  • int[ ][ ][ ] A;
  • (or)
  • int A[ ][ ][ ];

133 of 215

JAVA ARRAYS: 3-DIMENSIONAL�(MULTI DIMENSIONAL)

  • //3D array or matrix - Declaration
  • int A[ ][ ][ ] = new int[3][10][10 ];
  • //3D array Initialization�int A[ ][ ][ ] = { {2,7,9}, {3,6,1}, {7,4,2} };

133

134 of 215

JAVA ARRAYS: 3-DIMENSIONAL�(MULTI DIMENSIONAL)

  • //3D Array Declaration
  • int A[ ][ ][ ]= new A[3][4][2];

134

135 of 215

JAVA ARRAYS: 3-DIMENSIONAL�(MULTI DIMENSIONAL) INITIALIZAION

135

  • int A[ ][ ][ ] = {
  • {
  • {1, 2, 3} ,
  • {4, 5, 6}
  • } ,
  • {
  • {7,8,9},
  • {10,11,12}
  • }
  • } ;

136 of 215

ACCESS SPECIFIERS/MODIFIERS:

  • An access specifier is a keyword that indicates how a field/variable or method can be accessed.
  • (i.e., scope/visibility)

136

137 of 215

137

138 of 215

ACCESS SPECIFIERS:

138

139 of 215

139

140 of 215

ACCESS SPECIFIERS:

140

141 of 215

CLASSES AND OBJECTS IN JAVA

  • Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.
  • class is a group of objects which have common properties.
  • It is a template or blueprint from which objects are created.
  • It is a logical entity. It can't be physical.

141

142 of 215

CLASSES:

  • A class is a user defined blueprint or prototype from which objects are created.  
  • It represents the set of properties or methods that are common to all objects of one type.
  • In general, class declarations can include these components, in order:
  • Modifiers : A class can be public or has default access
  • Class name: The name should begin with a initial letter (capitalized by convention).
  • Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  • Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  • Body: The class body surrounded by braces, { }.

142

143 of 215

CLASS:

  • A class in Java can contain:
  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

143

144 of 215

CLASS:

  • Constructors are used for initializing new objects.
  • Fields are variables that provides the state of the class and its objects, and
  • methods are used to implement the behavior of the class and its objects.

144

145 of 215

OBJECT:

  • Definitions:
  • An object is a real-world entity.
  • An object is a runtime entity.
  • The object is an entity which has state and behaviour.
  • The object is an instance of a class.

145

146 of 215

OBJECT:

146

It is a basic unit of Object Oriented Programming and represents the real life entities.  

A typical Java program creates many objects, which as you know, interact by invoking methods.

characteristics of an object:

State: represents the data (value) of an object.

Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

147 of 215

147

148 of 215

148

149 of 215

CLASS & OBJECT:

  • Syntax to declare a class:
  • class class_name
  • {  
  •     Access specifier field(s) (or) Instance Variables;  

constructor;

  •     Access specifier method(s);  
  • }  

149

150 of 215

CLASS & OBJECT:

  • Instance variable in Java:
  • A variable which is created inside the class but outside the method is known as an instance variable.
  • Instance variable doesn't get memory at compile time.
  • It gets memory at runtime when an object or instance is created.
  • That is why it is known as an instance variable.

150

151 of 215

CLASS & OBJECT:

  • Method in Java:
  • In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method

  • Code Reusability
  • Code Optimization

151

152 of 215

CLASS & OBJECT: SYNTAX

  • class Student
  • {

private int rno;

private String name;

private float cgpa;

public void input()

{

-----

}

public void display()

{

------

}

  • }

152

  • //object(s) creation - Instance of class
  • Student s1=new Student();
  • Student s2=new Student();
  • Student s3=new Student();

153 of 215

HOW TO INITIALIZE OBJECT: 3 WAYS

Initializing an object means storing data into the object.

  1. By reference variable
  2. By method
  3. By constructor

153

154 of 215

1)BY REFERENCE VARIABLE

  • Syntax:
  • object . Instance_variable = value;
  • Example:
  • s1.id=101;  
  • s1.name=“sri”;  
  • NOTE: Example TestStudent3.java

154

155 of 215

2)BY METHOD

  • We are creating the two objects of Student class and initializing the value to these objects by invoking the insert method. 
  • NOTE: Example TestStudent5.java

155

156 of 215

3)BY CONSTRUCTOR : CONSTRUCTORS IN JAVA

  • DEF: A constructor is a block of code similar to the method.
  • It is called when an instance of the class is created.
  • At the time of calling constructor, memory for the object is allocated in the memory.
  • 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.

156

157 of 215

RULES FOR CREATING JAVA CONSTRUCTOR:

  1. Constructor name must be the same as its class name
  2. A Constructor must have no return type (not even void)
  3. A Java constructor cannot be abstract, static, final, and synchronized

NOTE:

  • We can use access modifiers while declaring a constructor.It controls the object creation.
  • In other words, we can have private, protected, public or default constructor in Java.

157

158 of 215

TYPES OF CONSTRUCTORS:

  • There are two types of constructors in Java:
  • Default constructor (no-arguments constructor)
  • Parameterized constructor

158

159 of 215

A) DEFAULT CONSTRUCTOR �(NO-ARGUMENTS CONSTRUCTOR)

  • A constructor is called "Default Constructor" when it doesn't have any parameter.
  • Syntax of default constructor:
  • class_name()
  • {
  • ….
  • }  
  • Example : College.java
  • Note: The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

159

160 of 215

B) PARAMETERIZED CONSTRUCTOR

  • A constructor which has a specific number of parameters is called a parameterized constructor.
  • Why use the parameterized constructor?
  • The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

  • Example:
  • Student4.java
  • Estudent.java

160

161 of 215

CONSTRUCTOR OVERLOADING IN JAVA

  • Constructor overloading is a technique of having more than one constructor with different parameter lists.
  • They are arranged in a way that each constructor performs a different task.
  • They are differentiated by the compiler by the number of parameters in the list and their types.

161

162 of 215

CONSTRUCTOR VS METHOD IN JAVA

162

Java Constructor

Java Method

A constructor is used to initialize the state of an object.

A method is used to expose the behavior of an object.

A constructor must not have a return type.

A method must have a return type.

The constructor is invoked implicitly.

The method is invoked explicitly.

The Java compiler provides a default constructor if you don't have any constructor in a class.

The method is not provided by the compiler in any case.

The constructor name must be same as the class name.

The method name may or may not be same as the class name.

163 of 215

COPY OF OBJECT 🡪 OBJECT:�(JAVA COPY CONSTRUCTOR)

  • There is no copy constructor in Java.
  • However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java.

  1. By constructor
  2. By assigning the values of one object into another
  3. By clone() method of Object class

163

164 of 215

1)BY CONSTRUCTOR:

  • copy constructor implementation should perform deep copy for any referenced objects in the class by creating new objects and copy the values
  • It usually accepts only one parameter that is just another instance of the same class.

164

165 of 215

3) BY ASSIGNING THE VALUES OF ONE OBJECT INTO ANOTHER:

  • We can copy the contents of one object into another object by assigning the values of one object into another individually field by field.

165

166 of 215

3) BY CLONE() METHOD OF OBJECT CLASS

  • The object cloning is a way to create exact copy of an object.
  • The clone() method of Object class is used to clone an object.
  • The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning.

166

167 of 215

  • -----Some Programs-----

167

168 of 215

WRAPPER CLASSES:

  • Wrapper class is a class whose object wraps or contains a primitive data types.
  • The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

168

169 of 215

USE OF WRAPPER CLASSES IN JAVA

  • Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc.
  • Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
  • Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
  • Synchronization: Java synchronization works with objects in Multithreading.
  • java.util package: The java.util package provides the utility classes to deal with objects.
  • Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

169

170 of 215

AUTO BOXING & UNBOXING:�(PACKING) (UNPACKING)

  • Primitive object

170

Auto Boxing

Un Boxing

171 of 215

AUTO BOXING:

  • Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing.
  • For example – conversion of int to Integer, long to Long, double to Double etc.

171

172 of 215

UNBOXING:

  • It is just the reverse process of autoboxing.
  • Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing.
  • For example – conversion of Integer to int, Long to long, Double to double etc.

172

173 of 215

PRIMITIVE DATA TYPES AND CORRESPONDING WRAPPER CLASS

173

Eight classes of the java.lang package are known as wrapper classes in Java.

174 of 215

PRIMITIVE TO WRAPPER : EXAMPLE (AUTOBOXING)

  • See example,
  • WrapperExample1.java

174

175 of 215

WRAPPER TO PRIMITIVE:EXAMPLE (AUTOBOXING)

  • See example,
  • WrapperExample2.java

175

176 of 215

JAVA WRAPPER CLASSES EXAMPLE

  • See example,
  • WrapperExample3.java

176

177 of 215

1) CONVERSION OF PRIMITIVE DATA TYPES TO OBJECTS:

  • Integer ival = new Integer(i);
  • Float fval = new Float(f);
  • Double dval = new Double(d);
  • Long lval = new Long(l);
  • Note: Parameter is primitive value

177

178 of 215

2) CONVERSION OF OBJECTS TO PRIMITIVE DATA TYPES :

  • int i = ival.intValue();
  • float f = fval.floatValue();
  • long l = lval.longValue();
  • double d = dval.doubleValue();

178

179 of 215

3) CONVERSION OF NUMBERS(PRIMITIVE) TO STRINGS:

String s1=Integer.toString(i);

String s2=Float.toString(f);

String s3=Double.toString(d);

String s4=Long.toString(l);

179

180 of 215

4) CONVERSION OF STRING OBJECTS TO NUMERIC OBJECTS:

Integer ival=Integer.valueOf(s1);

Float fval=Float.valueOf(s2);

Double dval=Double.valueOf(s3);

Long lval=Long.valueOf(s4);

180

181 of 215

5) CONVERSION OF NUMERIC STRINGS(OBJECTS) TO PRIMITIVE TYPES(NUMBERS):

int i=Integer.parseInt(s1);

long l=Long.parseLong(s2);

float f=Float.parseFloat(s3);

double d=Double.parseDouble(s4);

181

182 of 215

JAVA STRING CLASS

  • Java String class implements three interfaces, namely – Serializable, Comparable and CharSequence.

182

183 of 215

STRINGS:

  • Def:
  • String is a class, it is used often in the form of data type
  • ( java.lang package)
  • Note: In java all classes are considered as data type(user-defined). So, we consider this String as data type. (It is not character array- but object)
  • Example:
  • String s1=“Hello”;

183

184 of 215

CREATE A STRING:

  • There are 3 ways to create strings in java:

1) Assign a group of characters (i.e., String literal) to variable

Example-1: String s1;

s1=“hello”;

Example-2: String s1=“hello”;

2) Using ‘new’ operator (new keyword)

Example:

String s1=new String(“hello”);

3) By converting a character array into strings. (char array 🡪 String)

Example-1: Example-2: (specified characters only)

char s1[]={‘h’,’e’,’l’,’l’,’o’}; char s1[]={‘c’,’h’,’a’,’i’,’r’};

String s2= new String(s1); String s2= new String(s1,2,3); 🡪 air

184

185 of 215

STRING LITERAL:

  • String s1="Welcome";  

  • //It doesn't create a new instance  
  • String s2="Welcome";

  • Note:
  • String objects are stored in a special memory area known as the "string constant pool".
  • To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

185

186 of 215

BY NEW KEYWORD:

  • //creates two objects and one reference variable  
  • String s=new String("Welcome");
  • In such case, JVM will create a new string object in normal (non-pool) heap memory.

186

187 of 215

187

Note: references are stored in stack memory and objects are stored in heap memory

188 of 215

STRING CLASS METHODS:

1) String concatenation:

Syntax:

String concat(String s);

Example:

String s1;

s1="Hello";

String s2="World";

String s3=s1.concat(s2);

String s4=s1+s2;

188

Output:

S3- HelloWorld

S4- HelloWorld

189 of 215

STRING CLASS METHODS:

2) String length:

Syntax:

int length();

Example:

String s1;

s1="Hello";

int n=s1.length();

189

Output:

S1- 5

190 of 215

STRING CLASS METHODS:

3) Specific character:

Syntax:

char charAt(int i); // index-start with 0

Example:

String s1;

s1="Hello";

char ch=s1.charAt(1);

190

Output:

S1- e

191 of 215

STRING CLASS METHODS:

4) String comparison

Syntax:

int compareTo(String s1);

Example:

String s1="Hello";

String s2=“hello”;

int n=s1.compareTo(s2);

191

Output:

String comparison: -32

Note-1:

s1==s2 🡪 0

s1<s2 🡪 -ve

s1>s2 🡪 +ve

Note-2: (Ignore case)

int compareToIgnoreCase(String)

192 of 215

STRING CLASS METHODS:

5) String comparison - true/false

Syntax:

boolean equals(String s1);

Example:

String s1="Hello";

String s2=“hello”;

boolean b=s1.equals(s2);

192

Output:

String comparison: false

Note:

Boolean equalsIgnoreCase(String s)

193 of 215

STRING CLASS METHODS:

6) String Starts with- true/false

Syntax:

boolean startsWith(String s1);

Example:

String s1=“ramkumar";

String s2=“ram”;

boolean b=s1.startsWith(s2);

193

Output:

String starts with: true

Note:

boolean endsWith(String s1);

194 of 215

STRING CLASS METHODS:

7) Index of substring

Syntax:

int indexOf(String s1);

Example:

String s1=“ramkumar";

String s2=“kumar”;

int n=s1.indexOf(s2);

194

Output:

Index of substring:3

Note:

If doesn’t exist 🡪 -ve

195 of 215

STRING CLASS METHODS:

8) Last Index of substring

Syntax:

int lastIndexOf(String s1);

Example:

String s1=“This is book,is it?";

String s2=“is”;

int n=s1.lastIndexOf(s2);

195

Output:

Last Index of substring:13

Note:

If doesn’t exist 🡪 -ve

196 of 215

STRING CLASS METHODS:

9) String substring

Syntax:

String substring(int);

String substring(int,int);

Example:

String s1=“Welcome to java";

String s2=s1.substring(2);

196

Output:

Substring: lcome to java

Note:

String substring(2,6);

( from, to-1)

Substring: lcom

197 of 215

STRING CLASS METHODS:

10) String conversion : lower 🡪 upper

Syntax:

String toLowerCase();

Example:

String s1=“Welcome to java";

String s2 =s1.toUpperCase();

197

Output:

Lower to Upper:WELCOME TO JAVA

Note:

s1 =s2.toLowerCase();

Upper to Lower:welcome to java

198 of 215

STRING CLASS METHODS:

11) String Trim : remove spaces (begin & end)

Syntax:

String trim();

Example:

String s1=“ hello ";

String s2 =s1.trim();

198

Output:

After Trim:hello

199 of 215

STRING CLASS METHODS:

12) String Split: (using delimiter)

Syntax:

String split(String); //parameter is delimiter

Example:

String s1=“Hello, this is java program";

String sarr[]=s1.split(" ");

for(String i:sarr)

System.out.println(i);

199

Output:

Hello,

this

is

java

program

200 of 215

STRING CLASS METHODS:

13) String - character(occurrence) Replace

Syntax:

String replace(char, char)

Example:

String s1=“Hello";

s1=s1.replace(‘e’,’a’);

200

Output:

After replaceing:Hallo

201 of 215

JAVA STRING COMPARE

  • We can compare string in java on the basis of content and reference.
  • There are three ways to compare string in java:
  • By equals() method
  • By = = operator
  • By compareTo() method

201

202 of 215

1) BY EQUALS() METHOD

  • The method is : equals() method & equalsIgnoreCase()
  • It is used in authentication. (To Check content equality)
  • Syntax:
  • public boolean equals(String);
  • public boolean equalsIgnoreCase(String);

202

203 of 215

2) BY = = OPERATOR

  • Uses == operator
  • Used for Reference matching (i.e., whether both belong to same class type or not)
  • Used for objects.

203

204 of 215

  •  String s1 = new String("HELLO");
  •         String s2 = new String("HELLO");
  •   
  •         System.out.println(s1 == s2); // false
  •  

204

205 of 215

3) BY COMPARETO() METHOD

  • compareTo() method
  • Used while sorting (i.e., equality checking)
  • Checks the order of occurrence - as per dictionary order)

Syntax:

int compareTo(String s1);

205

Output:

String comparison: -32

Note-1:

s1==s2 🡪 0

s1<s2 🡪 -ve

s1>s2 🡪 +ve

Note-2: (Ignore case)

int compareToIgnoreCase(String)

206 of 215

IMMUTABILITY OF STRINGS:

  • Objects are divided into
  • 1) Mutable & 2) Immutable
  • Mutable objects are objects whose contents can be modified.
  • Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created.
  • String objects are immutable.

206

207 of 215

MUTABLE VS IMMUTABLE:

  • Java String is immutable and final
  • A new String is created whenever we do String manipulation.
  • As String manipulations are resource consuming, Java provides two utility classes: StringBuffer and StringBuilder.�
  • Let us understand the difference between these two utility classes:
  • StringBuffer and StringBuilder are mutable classes.

207

208 of 215

STRINGBUFFER CLASS

  • Java StringBuffer class is used to create mutable (modifiable) string.
  • The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
  • Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

208

209 of 215

CONSTRUCTORS OF STRINGBUFFER CLASS

209

Constructor

Description

StringBuffer()

creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str)

creates a string buffer with the specified string.

StringBuffer(int capacity)

creates an empty string buffer with the specified capacity as length.

210 of 215

METHODS OF STRINGBUFFER CLASS:

  • Refer DOCUMENT…..

210

211 of 215

STRINGBUILDER CLASS

  • Java StringBuilder class is used to create mutable (modifiable) string.
  • The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
  • It is available since JDK 1.5.

211

212 of 215

CONSTRUCTORS OF STRINGBUILDER CLASS

212

Constructor

Description

StringBuilder()

creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str)

creates a string Builder with the specified string.

StringBuilder(int length)

creates an empty string Builder with the specified capacity as length.

213 of 215

213

String

StringBuffer

StringBuilder:

Immutable

Strings are read only. String once assigned can not be changed.

Mutable

Mutable

Storage area is SCP

(String Constant Pool)

Heap Memoy

Heap Memory

A new String is created whenever we do String manipulation.

On the same string object

On the same string object

Consumes more memory, when we concatenate

Consumes less memory, when we concatenate

Consumes less memory, when we concatenate

thread-safe

thread-safe

not thread-safe.

Synchronized. String can not be

used by two  threads simultaneously. 

Synchronized. It means two threads can't call the methods simultaneously.

Non-synchronized.  It means two threads can call the methods of StringBuilder simultaneously.

Can safely shared between multiple threads.

To be used when multiple threads are working on same String

in the single threaded environment

More efficient when we don’t alter the value , frequent usage is there.

Less efficient than StringBuilder

More efficient than StringBuffer

Somewhat slower

StringBuffer is faster than String when performing simple concatenations.

StringBuilder is more faster than StringBuffer.

214 of 215

STRING CONCATENATION OPERATOR ( + ):

  • NOTE:
  • The "+" operator is overloaded for String and used to concatenated two string.
  • Internally "+" operation is implemented using either StringBuffer or StringBuilder.

214

215 of 215

215