0% found this document useful (0 votes)
13 views177 pages

Unit 1 - 24 Batch Notes - PPSX

The syllabus outlines the curriculum for the B. Tech II Year I semester course on Object Oriented Programming through Java, covering topics such as Java basics, inheritance, packages, exception handling, GUI, applets, and networking. It includes practical applications like banking operations, string searching, and chat applications, along with recommended textbooks and references. The document also details Java's history, features, and programming concepts essential for understanding object-oriented programming.

Uploaded by

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

Unit 1 - 24 Batch Notes - PPSX

The syllabus outlines the curriculum for the B. Tech II Year I semester course on Object Oriented Programming through Java, covering topics such as Java basics, inheritance, packages, exception handling, GUI, applets, and networking. It includes practical applications like banking operations, string searching, and chat applications, along with recommended textbooks and references. The document also details Java's history, features, and programming concepts essential for understanding object-oriented programming.

Uploaded by

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

Syllabus for B.

Tech II Year I semester


Information Technology
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
(Common to CSE, IT and ECM)
Code: 9EC02 (24 Batch- Regulation – A22) AY 2025-26
UNIT I
History of Java, Java buzzwords, datatypes, variables, simple java program, scope and life time of
variables, operators, expressions, control statements, type conversion and casting, arrays,, classes
and objects – concepts of classes, objects, constructors, methods, access control, this keyword,
garbage collection, overloading methods and constructors, recursion, string handling,
StringTokenizer.
Applications: Basic operations on the bank account of a customer.
UNIT II
Inheritance –Definition, single inheritance, benefits of inheritance, Member access rules, super
class, polymorphism- method overriding, Dynamic method dispatch, using final with inheritance,
abstract classes, Base class object.
Interfaces: definition, variables and methods in interfaces, differences between classes and
interfaces, usage of implements and extends keyword, interfaces, uses of interfaces, packages
Applications: Extending the banking operations to the loan applicants.
UUNIT III
Packages: Definition, types of packages, Creating and importing a user defined package.
Introduction to I/O programming: DataInputStream, DataOutputStream, FileInputStream,
FileOutputStream, BufferedReader.
Collections: interfaces, Implementation classes, and Algorithms (such as sorting and searching).
Applications: Searching for a string in the text. PNR status check, students’ result sorting.
UNIT IV

Exception handling -exception definition, benefits of exception handling, exception


hierarchy, usage of try, catch, throw, throws and finally, built in exceptions, creating own
exception sub classes.
Multi-Threading: Thread definition, types of multitasking, uses of multitasking, thread life
cycle, creating threads using Thread class and Runnable interface, synchronizing threads,
daemon thread.
Applications: Illegal entry handling in the registration form. (Example: entering incorrect
intermediate hall-ticket number in EAMCET Registration form)

UNIT V
Advantages of GUI over CUI ,The AWT class hierarchy, Introduction to Swings, Swings
Elements:- JComponent, JFrame, user interface components- JLabels, JButton, JScrollbars,
text components, check box, check box groups, choices, lists panels – scrollpane, menubar,
graphics, layout, managers –border, grid, flow, card and grid bag.
Event handling: Delegation event model, closing a Frame, mouse and keyboard events,
Adapter classes.
Applications: developing calculator, developing feedback form, developing bio data.
UNIT VI
Applets – Concepts of Applets, differences between applets and applications, life
cycle of an applet, types of applets, creating applets, passing parameters to applets.
Applications: Developing of simple advertisements.
Networking – Basics of network programming, addresses, ports, sockets, simple
client server program, multiple clients, sending file from server to client.
Applications: One to one Chat application

Text books:

• Java; the complete reference, 6th edition, Herbert Schildt,TMH.


• Introduction to Java programming 6th edition, Y. Daniel Liang, Pearsoneducation.

References:

• Core Java 2, Vol 1, Fundamentals, Cay. S. Horstmann and Gary Cornell, seventh
Edition, PearsonEducation.
• Core Java 2, Vol 2, Advanced Features, Cay. S. Horstmann and Gary Cornell,
Seventh Edition, PearsonEducation
UNIT-1

4
UNIT-I
 JAVA BASICS
 History of Java
 Java buzzwords
 Data types
 Variables
 Simple java program
 scope and life time of variables
 Operators, expressions, control statements
 Type conversion and casting
 Arrays
 Classes and objects – concepts of classes, objects
 Constructors, methods
 Access control
 This keyword
 Garbage collection
 Overloading methods and constructors
 Parameter passing
 Recursion
 String handling .
5  String Tokenizer
History of Java
Java started out as a research project.

Research began in 1991 as the Green Project at Sun


Microsystems, Inc.

Research efforts birthed a new language, OAK. ( A tree outside


of the window of James Gosling’s office at Sun).

It was developed as an embedded


programming language, which would enable
embedded system application.
It was not really created as web programming
language.
6
History of Java (contd…)
Language was created with 5 main goals:
 It should be object oriented.
 A single representation of a program could be executed on

multiple operating systems. (i.e. write once, run anywhere)


 It should fully support network programming.
 It should execute code from remote sources securely.
 It should be easy to use.

 Oak was renamed Java in 1994.

Now Sun Microsystems is a subsidiary of Oracle


7 Corporation.
James Gosling

8
Green Team

9
Java Logo

10
Versions of Java
Version Codename Year Features Added

JDK 1.0 Oak Jan23,1996 -

JDK 1.1 Rebirth of


Java Feb19,1997 Inner classes JavaBeans, JDBC, RMI, Reflection, AWT.

J2SE 1.2 Playground Dec8, 1998 JIT compiler, Collections, IDL & CORBA, strictfp, Java
Plug-in.

J2SE 1.3 Kestrel May8, 2000 HotSpot JVM, JavaSound, Java Naming and Directory
Interface, Java Platform Debugger Architecture.

J2SE 1.4 Merlin Feb6, 2002 Preferences API, Logging API, assert, image I/O API,
security and cryptography extensions.

J2SE 5.0 Tiger Sep30, 2004 Generics, annotations, Autoboxing, Enumerations, Varargs,
Enhanced for each.

JAVA SE 6 Mustang Dec11, 2006 JDBC 4.0, JVM improvements, Improved JAXB, Improved
web services, Support for older Win9x versions dropped.
Major updates to Java
JAVA SE 7 Dolphin July28, 2011
11
JAVA SE 8 - 2012 -
Java Platforms
There are three main platforms for Java:

Java SE (Java Platform, Standard Edition) – runs on desktops


and laptops.

Java ME (Java Platform, Micro Edition) – runs on mobile


devices such as cell phones.

Java EE (Java Platform, Enterprise Edition) – runs on


servers.

12
Java Terminology
Java Development Kit:
It contains one (or more) JRE's along with the various
development tools like the Java source compilers, bundling and
deployment tools, debuggers, development libraries, etc.

Java Virtual Machine:


An abstract machine architecture specified by the Java Virtual
Machine Specification.

It interprets the byte code into the machine code depending


upon the underlying OS and hardware combination. JVM is
platform dependent. (It uses the class libraries, and other
supporting files provided in JRE)
13
Java Terminology (contd…)
Java Runtime Environment:
A runtime environment which implements Java Virtual
Machine, and provides all class libraries and other
facilities necessary to execute Java programs. This is the
software on your computer that actually runs Java
programs.

JRE = JVM + Java Packages Classes (like util, math,


lang, awt, swing etc) +runtime libraries.

14
15
Java Development Kit (JDK)

 Comes with all tools necessary to compile and run Java


programs, including a complete Java Runtime
Environment (JRE) (located in the jdk/jre directory).
 Get the most recent version from:
http://java.sun.com/javase/downloads/index.jsp
 To set the path, class path, use My computer, right click
on properties, click on advanced system settings, go to
environment variables and set the variable as path and
value as c:/program files/ java/jdk1.5/bin; and set class
path as c:/program files/java/jdk1.5/lib;

16
classpath and path

 The PATH is an environment variable that tells the


command processor where to look for javac.exe and
java.exe
 set path=”c:/Programfiles/java/jdk1.5/bin;.; in the
command prompt, to set the path from command prompt

 The CLASSPATH is an environment variable that tells


the Java compiler javac.exe where to look for class files
to import
 set class path=”c:/Programfiles/java/jdk1.5/lib“;.; in the
command prompt.

17
17
18
19
20
21 21
22 22
Java Execution Procedure
Class Loader Java Class
Java Byte Code
Libraries
Source Verifier

Java
Byte
codes Java Just-in-time
Java
move Interpreter Compiler
Compiler
locally
or
through Run Time System
n/w
Java Java OS W32
Win Solaris
Byte codes

MAC Others

23 Hardware
Java Virtual Machine
Class loader subsystem: A mechanism for loading
types (classes and interfaces) given fully qualified
names.

The Java virtual machine organizes the memory it


needs to execute a program into several runtime data
areas.

Each Java virtual machine also has an execution


engine: a mechanism responsible for executing the
instructions contained in the methods of loaded
classes.
25
When the virtual machine loads a class file, it parses information
about a type from the binary data contained in the class file.
It places this type information into the method area.

As the program runs, the virtual machine places all objects the
program instantiates onto the heap.

As each new thread comes into existence, it gets its own pc register
(program counter) and Java stack.

Byte code is a highly optimized set of instructions designed to be


executed by the Java run-time system, which is called the Java
Virtual Machine (JVM).The JVM is an interpreter for byte code.

27
Java program Compilation & Execution steps

28
Binary form of a .class file(partial)
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
0000: cafe babe 0000 002e 001a 0a00 0600 0c09 ................
0010: 000d 000e 0800 0f0a 0010 0011 0700 1207 ................
0020: 0013 0100 063c 696e 6974 3e01 0003 2829 .....<init>...()
0030: 5601 0004 436f 6465 0100 046d 6169 6e01 V...Code...main.
0040: 0016 285b 4c6a 6176 612f 6c61 6e67 2f53 ..([Ljava/lang/S
0050: 7472 696e 673b 2956 0c00 0700 0807 0014 tring;)V........
0060: 0c00 1500 1601 000d 4865 6c6c 6f2c 2057 ........Hello, W
0070: 6f72 6c64 2107 0017 0c00 1800 1901 0005 orld!...........
0080: 4865 6c6c 6f01 0010 6a61 7661 2f6c 616e Hello...java/lan
0090: 672f 4f62 6a65 6374 0100 106a 6176 612f g/Object...java/
00a0: 6c61 6e67 2f53 7973 7465 6d01 0003 6f75 lang/System...ou ...
29
Object Oriented Programming Concepts
Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding

30
A class is collection of objects of similar type or it is a template.
Ex: fruit mango;

class object
Objects are instances of the type class.

The wrapping up of data and functions into a single unit ( called class) is
known
as encapsulation. Data encapsulation is the most striking features of a class.

Abstraction refers to the act of representing essential features without


including
the background details or explanations

Inheritance is the process by which objects of one class acquire the properties
of another class. The concept of inheritance provides the reusability.
31
Polymorphism:
It allows the single method to perform different actions based on the
parameters.

Dynamic Binding: When a method is called within a program, it is


associated with the program at run time rather than at compile time is
called dynamic binding.

32
Object-Oriented Languages Types
1.Object-based programming language: It supports
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
Disadvantage : They do not support inheritance and dynamic binding
Ex: Ada

2.Object-oriented programming languages:

OOP = Object-based + inheritance + dynamic


binding

Ex: C++, Java, Smalltalk, Object Pascal

33
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use
of existing classes.

The principle of data hiding helps the programmer to build secure programs.

It is easy to partition the work in a project based on objects.

Object oriented system easily upgraded from small to large systems.

Software complexity can be easily managed.

34
Applications of oop

 Real-time systems

 Object-oriented databases

 Neural networks and parallel programming

 Decision support and office automation systems

 CAD/CAM systems

35
What is the Difference b/w OO and OB Languages?
In Object based languages inheritance is not supported so
that dynamic polymorphism also not supported.
E.g. VB,VC++.

Is C++ partial OOP?


Yes, C++ is a partial OOP because without using class also
we can be able to write the program.

Is Java total OOP or partial OOP?


Java is a total oop language because with out object
orientation we can’t be able to write any program.

36
Java is a pure oop or not ?

By default java is not pure object oriented language.

Java is called as Hybrid language.

Pure oop languages are “small talk”, ”ruby”, “Eiffel”.

37
Differences b/w C++ and Java
C++ Java

1. Global variable are 1. No Global variables.


supported. Everything must be inside
the class only.

2.Multiple inheritance 2. No direct multiple


is supported. Inheritance.

38
C++ Java

3.Constructors and 3.Java supporting constructors


Destructors supported. only & instead of destructors
garbage collection is
supported.

4.In c++ pointers are 4.No pointer arithmetic in Java.


supported.

5.C++ supporting ASCII 5. Java supports Uni code


character set. Character set.

39
Features of Java (Java Buzz Words)
Simple
Object Oriented
Compile, Interpreted and High Performance
Portable
Robust
Secure
Multithreaded
Dynamic
Distributed
Architecture-Neutral

40
Java Features
Simple
No pointers
No Operator Overloading
Automatic garbage collection
Rich pre-defined class library

Object Oriented
Focus on the data (objects) and methods manipulating the data
All methods are associated with objects
Potentially better code organization and reuse

41
Java Features
Compile, Interpreted and High Performance
Java compiler generates byte-code, not native machine
code
The compiled byte-codes are platform-independent
Java byte codes are translated on the fly to machine
readable instructions in runtime (Java Virtual Machine)
Easy to translate directly into native machine code by
using a just-in-time compiler.
Portable
Same application runs on all platforms
The sizes of the primitive data types are always the same
42 The libraries define portable interfaces
Java Features
Robust/Reliable
Extensive compile-time and runtime error checking
No pointers but real arrays. Memory corruptions or
unauthorized memory accesses are impossible
Automatic garbage collection tracks objects usage over
time
Secure
Java’s robustness features makes java secure.
Access restrictions are forced (private, public)

43
Java Features
Multithreaded
It supports multithreaded programming.
Need not wait for the application to finish one task
before beginning another one.
We can write Java programs that deal with many tasks at
once by defining multiple threads.
Dynamic
Libraries can freely add new methods and instance
variables without any effect on their clients
Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
44
Java Features
Distributed
Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols.
 Allows objects on two different computers to execute
procedures remotely by using package called Remote
Method Invocation (RMI).

Architecture-Neutral
Goal of java designers is “write once; run anywhere,
any time, forever.”
There is no implementation dependent features e.g. size
of primitive types is fixed.
45
Keywords
abstract continue for new
switch

assert default goto


package synchronized

boolean do if private
this

break double import


protected throw

byte else implements public


throws

case enum instanceof return


transient

catch extends int short


46 try
Data Types

Simple Type Derived Type User Defined


Type
E.g: Array, String…

Numeric Type Non-Numeric class interfa


ce

Boolean
Integer Float Character
char
boolean
float double

byte short int long 47


Data Types
Java Is a Strongly Typed Language
Every variable has a type, every
expression has a type, and every type
is strictly defined.
All assignments, whether explicit or
via parameter passing in method calls,
are checked for type compatibility.
There are no automatic conversions of
conflicting types as in some languages.
For example, in C/C++ you can assign a
floating-point value to an integer. In
48
Java, you cannot.
Integer Data Types
Java does not support unsigned, positive-only
integers.
All are signed, positive and negative
values.
Byte Data Type
 The smallest integer type is byte.
 Variables of type byte are especially useful while working
with a stream of data from a network or file.
 Byte variables are declared by use of the byte keyword.
Ex: byte b, c;
Floating Point Types
There are two kinds of floating-point types. long and
double
All math functions, such as sin( ), cos( ), and sqrt( ),
return double values.
Boolean Data Type
49 It can have only one of two possible values, true or
Character Data Type

char in Java is not the same as char in C or


C++.
Java uses Unicode to represent characters.
Unicode defines a fully international
character set that can represent all of the
characters found in all human languages.
It is a unification of dozens of character sets,
such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more.
Hence it requires 16 bits.
The range of a char in java is 0 to 65,536.
There are no negative chars.
50
Data Types

Name Width in bits Range


long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536.

51
public class IntDemo{
public static void main(String args[]){
System.out.println(" For an Short");
System.out.println(" For an Integer "); System.out.println("Size is :
System.out.println("Size is : "+Integer.SIZE); "+Short.SIZE);

int i1 = Integer.MAX_VALUE; short s1 = Short.MAX_VALUE;


int i2 = Integer.MIN_VALUE ; short s2 = Short.MIN_VALUE ;

System.out.println("Max value is : "+s1);


System.out.println("Max value is : "+i1); System.out.println("Min Value is : "+s2);
System.out.println("Min Value is : "+i2);

System.out.println(" For an Byte"); System.out.println(" For an Long");


System.out.println("Size is : "+Byte.SIZE); System.out.println("Size is : "+Long.SIZE);

long l1 = Long.MAX_VALUE;
byte b1 = Byte.MAX_VALUE; long l2 = Long.MIN_VALUE ;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Max value is : "+b1); System.out.println("Min Value is : "+l2);
System.out.println("Min Value is : "+b2);
}
}
52
public class FloatDemo{
public static void main(String args[]){

System.out.println(" For an Float");


System.out.println("Size is : "+Float.SIZE);

float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;

System.out.println("Max value is : "+f1);


System.out.println("Min Value is : "+f2);

System.out.println(" For a Double");


System.out.println("Size is : "+Double.SIZE);

double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;

System.out.println("Max value is : "+d1);


System.out.println("Min Value is : "+d2);
}
}

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

System.out.println(" For a Char");


System.out.println("Size is :
"+Character.SIZE);

int f1 = Character.MAX_VALUE;
long f2 = Character.MIN_VALUE ;

System.out.println("Max value is : "+f1);


System.out.println("Min Value is : "+f2);
}
}
54
Variables
 The variable is the basic unit of storage in a Java program.
 A variable is defined by the combination of an identifier, a type, and an
optional initializer.
Declaring a Variable
 In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;

Types
 Instance Variable
 Class Variable
 Local Variable
 Parameters
55
Local variables :
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block
is entered and the variable will be destroyed once it exits the
method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method,
constructor or block.
• There is no default value for local variables so local variables
should be declared and an initial value should be assigned before
the first use.

56
Instance variables :
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name
inside the class.
• However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName

57
Class/Static variables :
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when
the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName

58
class Variables{
int i;
System.out.println("i value is: "+v1.i);
public int j;
System.out.println("i value is: "+v2.i);
static long l=10; System.out.println("i value is: "+v3.i);
public static float f; System.out.println(“J value is: "+v1.j);
char c; v1.l=20;
boolean b; v2.l=30;
void display(int a){ v3.l=40;
System.out.println("l value is: "+v1.l);
i=a;
System.out.println("l value is: "+v2.l);
System.out.println("i value in display: "+i);
System.out.println("l value is: "+v3.l);
}
public static void main(String args[]){ System.out.println("f value is: "+f);
double d=0.0; System.out.println("c value is: "+v1.c);
//public double d=0.0; invalid System.out.println("b value is: "+v1.b);
Variables v1=new Variables();
System.out.println("d value is: "+d);
Variables v2=new Variables();
}
Variables v3=new Variables(); }
v1.display(100);
v1.i=2;
v2.i=3;
59 v3.i=4;
class Variables{
int i;//instance variable System.out.println("i value is:
public int j ;//instance variable "+v1.i);
static long l=10;//class variable System.out.println("i value is:
public static float f;//class variable "+v2.i);
char c;//instance variable System.out.println("i value is:
"+v3.i);
boolean b;//instance variable
System.out.println(“j value is:
void display(int a){
"+v1.j);
i=a; v1.l=20;
System.out.println("i value in display: v2.l=30;
"+i); v3.l=40;
} System.out.println("l value is:
public static void main(String args[]){ "+v1.l);
double d=0.0;//local variable System.out.println("l value is:
//public double d=0.0; invalid
"+v2.l);
System.out.println("l value is:
Variables v1=new Variables();
"+v3.l);
Variables v2=new Variables();
Variables v3=new Variables(); System.out.println("f value is:
v1.display(100); "+f);
v1.i=2; System.out.println("c value is:
60 v2.i=3; "+v1.c);
System.out.println("b value is:
v3.i=4;
Sample Program
class HelloWorld {
public static void main (String args []) {
System.out.println (“Welcome to Java
Programming…..”);
}
}

public allows the program to control the


visibility of class
members. When a class member is preceded by
public, then that
member may be accessed by code outside the
61 class in which it is
static allows main( ) to be called without having
to instantiate a
particular instance of the class. This is
necessary since main ( ) is
called by the Java interpreter before any objects
are made.

void states that the main method will not return


any value.

main() is called when a Java application begins.


In order to run
a class, the class must have a main method.
62
System is a class which is present in java.lang
package.

out is a static field present in system class


which returns a
PrintStream object. As out is a static field it can
call directly with
classname.

println() is a method which is present in


PrintStream class which
can call through the PrintStream object return
by static field out
63
present in System class to print a line to
class sample{
public static void main(String args[]){
System.out.println("sample:main");
sample s=new sample();
s.display();

}
void display(){
System.out.println("display:main");
}
}

64
The Scope and Lifetime of Variables
Scope
The scope of a declared element is the portion of the program where the
element is visible.

Lifetime
The lifetime of a declared element is the period of time during which it is
alive.

The lifetime of the variable can be determined by looking at the context in


which they're defined.

 Java allows variables to be declared within any block.

 A block begins with an opening curly brace and ends by a closing curly
brace.

65
Variables declared inside a scope are not accessible to code
outside.
Scopes can be nested. The outer scope encloses the inner
scope.
Variables declared in the outer scope are visible to the inner
scope.
Variables declared in the inner scope are not visible to the
outside scope.

66
public class Scope
{
public static void main(String args[]){
int x; //know to all code within main
x=10;
if(x==10){ // starts new scope
int y=20; //Known only to this block
//x and y both known here
System.out.println("x and y: "+x+" "+y);
x=y+2;
}
// y=100; // error ! y not known here
//x is still known here
System.out.println("x is "+x);
}
}

67
Operators

Arithmetic Operators
Bitwise Operators
Relational Operators
Boolean Logical Operators

68
Arithmetic Operators(1)

Operator Result

+ Addition

– Subtraction

* Multiplication

/ Division

% Modulus

69
Arithmetic Operators(2)

Operator Result
++ Increment

+= Addition
assignment

–= Subtraction
assignment

*= Multiplication
assignment

/= Division
assignment

%=
70
Modulus assignment
Example:

class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
71
class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

72
Bitwise Operators(1)
 bitwise operators can be applied to the integer
types, long, int, short, byte and char.
 These operators act upon the individual bits of
their operands.

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left

73
Bitwise Operators(2)

Operator Result

&= Bitwise AND


assignment

|= Bitwise OR
assignment

^= Bitwise exclusive
OR assignment

>>= Shift right


assignment

>>>= Shift right zero fill


74 assignment
00101010 42 00101010 42
&00001111 15 ^00001111 15
-------------- -------------
00001010 10 00100101 37

int a = 64; int a = 32;


a = a << 2; 256 a = a >>2;
8
11111000 –8 11111111 11111111 11111111 11111111 –1
>>1 >>>24
11111100 –4 00000000 00000000 00000000 11111111 255
75
class BitwiseOperatorsDemo
{
public static void main(String args[])
{
int a=32;
a= a>>2;//output is 8
System.out.println("a after right shift " + a);
int b=64;
b= b<<2;//Output is 256
System.out.println("b after left shift " + b);
}
}

76
Relational Operators
 The relational operators determine the relationship
that one operand has to the other.
 They determine equality and ordering.

Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or
equal to
<= Less than or equal to
77
Example:

public class RelationalOperatorsDemo


{
public static void main(String args[])
{
int x=10,y=5;
System.out.println(“x>y:”+(x>y));
System.out.println(“x<y:”+(x<y));
System.out.println(“x>=y:”+(x>=y));
System.out.println(“x<=y:”+(x<=y));
System.out.println(“x==y:”+(x==y));
System.out.println(“x!=y:”+(x!=y));
}
}

78
Boolean Logical Operators(1)

 The Boolean logical operators operate only on boolean operands.


 All of the binary logical operators combine two boolean values to
form a resultant boolean value.

Operator Result

& Logical AND


| Logical OR
^ Logical XOR
(exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary
NOT
79
& //executes both left and right side operands

&& // Java will not bother to evaluate the right-hand


operand when the outcome of the expression can be
determined by the left operand alone.

class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
else
System.out.println(“left parameter
failed");
80
}
Boolean Logical Operators(2)

Operator Result
&= AND assignment

|= OR assignment

^= XOR assignment

== Equal to

!= Not equal to

?: Ternary if-
then-else

81
82
public class TernaryOperatorDemo
{
public static void main(String args[])
{
int x=10,y=12;
int z;
z= x > y ? x : y;
System.out.println(“Z=“+z);
}

83
Operator Precedence

84
Expressions

An expression is a combination of


constants (like 10), operators ( like +),
variables(section of memory) and
parentheses ( like “(” and “)” ) used to
calculate a value.

Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)

85
Control Statements

Selection Statements: if & switch

Iteration Statements: for, while and


do-while

Jump Statements: break, continue


and return

86
Selection Statements

if (condition) if(condition) switch (expression)


statement1; statement 1; {
else else if(condition) case value1:
statement 2; // statement sequence
statement2;
break;
else if(condition)
case value2:
statement 3;
// statement sequence
... break;
else …
statement n; case valueN:
// statement sequence
break;
default:
// default statement sequence
}
87
The condition is any expression that returns a boolean value.

The expression must be of type byte, short, int, or char;


Each of the values specified in the case statements must be of a type
compatible with the expression.

88
Iteration Statements

while(condition) do
{ {
// body of
loop // body of loop
}
}while (condition);

for(initialization; condition; iteration)


{
// body
}
89
Jump Statements

continue; //bypass the followed instructions

break; //exit from the loop

label:
----
----
break label; //it’s like goto
statement

return; //control returns to the


90
caller
class BreakLoop
{
public static void main(String The break statement has 3
args[])
{ uses:
for (int i=0; i<100;i++) 1.It terminates a statement
{
if (i==10) sequence in Switch
break;// terminate loop if i statement.
is 10
System.out.println(“i : “ + 2.It can be used to exit a
i); loop.
}
System.out.println(“ Loop 3.It can be used as a
Complete”); civilized form of “goto”.
}
91}
Using Continue
 Sometimes we want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.
 The continue statement performs such an action.

public class ContinueExample {


public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest of the statements
}
System.out.println(i);
}
}
}
92
Class Return
{
public static void main(String args[])
{ boolean t= true;
System.out.println(“Before the return”);
if(t) return; // return to caller
System.out.println(“This won’t Execute”);
}
}

1. The return statement is used to explicitly return from a method.


2. It causes program control to transfer back to the caller of the
method.
3. The return statement immediately terminates the method in
which it is executed.
4. return causes execution to return to the java run-time system,
since it is the run-time system that calls main().

93
Type Conversion and Casting

Type conversion, typecasting, refers to


different ways of, implicitly or explicitly,
changing an entity of one data type into
another.

Types of Conversions:
1.Widening conversion
2.Narrowing conversion

94
Widening Conversion

The widening conversion is permitted in the


following cases:
 byte to short, int, long, float, or
double
 short to int, long, float, or double
 char to int, long, float, or double
 int to long, float, or double
 long to float or double
 float to double
95
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:

 The two types are compatible.


 The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes


place.

Ex: char and boolean are not compatible with each other.

96
class Widening{
public static void main(String args[]){
short s;
int i1,i2;
byte b1=10,b2=20;
s=b1; //byte to short
i1=b2; //byte to int
System.out.println("byte to short conversion");
System.out.println(b1+ " " + s);
System.out.println("byte to int conversion");
System.out.println(b2+" "+i1);
char c='a';
i2=c; //char to int
System.out.println("char to int conversion");
System.out.println(c+" "+i2);
}
}
97
Narrowing Conversion
 In general, the narrowing primitive conversion can occur in
these cases:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float

 Narrowing conversion is used to cast the above incompatible types.


(target-type) value

98
public class Narrowing{
public static void main(String args[]){
byte b=2;
int i=257;
double d=323.142;
System.out.println("int to byte conversion");
b= (byte)i; //int to byte
System.out.println("i and b values: "+i+" "+b);
System.out.println("double to int conversion");
i=(int)d; //double to int
System.out.println("d and i values: "+d+" "+i);
System.out.println("double to byte conversion");
b=(byte)d; //double to byte
System.out.println("d and b values: "+d+" "+b);
}
}
99
Arrays
An array is a group of like-typed variables that are
referred to by a common name.
The operator new is used for dynamic memory
allocation.
One-Dimensional Arrays:
type varname[];
varname = new type[size];
type varname[]=new type[size];
Ex: int month[];
Ex: month= new int[12];
Ex: int varname[]=new int[size];

10
0
Multidimensional Arrays
int twoD[][]=new int[4][5];

10
1
If month is a reference to an array, month. length will
give you the length of the array.

Initialization:
int x[] = {1, 2, 3, 4};
char []c = {‘a’, ‘b’, ‘c’};
double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
Jagged Array:

 int [][] x = new int[3][];

10
2
import java.util.Scanner;
class ArrayEx{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int a[]={10,20,30,40,50};
char []c={'a','b','c','d','e'};
int b[]=new int[5];
for(int i=0;i<5;i++){
System.out.print(a[i]+" ");
System.out.println(c[i]+" ");
}
System.out.println("Enter the Integer elements into array :")
for(int i=0;i<5;i++){
b[i]=input.nextInt();
}
System.out.println("The Integer elements in array are :");
for(int i=0;i<5;i++){
System.out.print(b[i]+" ");
10 }
3
foreach syntax
for(data_type variable : array | collection)

{}
class ForEachExample
{
public static void main(String args[])
{
int arr[]={1,2,3,4,5};
for(int i:arr) {
System.out.println(i);
}
}
}
Concepts of Classes, Objects

10
5
General Form of Class
class classname {
type instance-variable1;
//...
type instance-variableN;
static type variable1;
type methodname1(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list){
// body of method
}
}

10
6
class Box{ Declaring an Object
double width;
double height;
double depth;
}
Representation 1:
Box mybox;
mybox=new Box();

Representation 2:
Box mybox=new
Box();

Representation 3: Assigning Object Reference Variables


Box b1 = new Box();
107 Box b2 = b1;
package import java.util.Scanner;
packagename; class Demon{
import statement; int i;
class classname{ static double d;
//instance variables; public static void main(String args[]){
//class or static char c=‘a’;
variables; Demon obj=new Demon();
/ Scanner s=new Scanner(System.in);
*methods(parameter
s){ System.out.println(“Enter double
value”);
//local
variables; d=s.nextDouble();
System.out.println(obj.i);
//object
System.out.println(d);
creation
System.out.println(c);
//statements;
108 }
}*/
class classname{ class Test{
//instance variables; char c='a';
//class or static variables; static float f;
/*methods(parameters){ void display(){
//local variables; int i=10;
//statements; System.out.println("Test:display()");
}*/ System.out.println(“c value: “+c);
} System.out.println(“i value: “+i);
class MainCLass{ System.out.println(“f value: “+f);
public static void main(String args[]) }
{ }
//object creation class Demo{
//invoking methods public static void main(String args[]){
//statements Test t=new Test();
} t.display();
} System.out.println("Demo:main()");
}
}
109
Constructors and Methods

110
A constructor is a special member function whose task is to initialize an
object immediately upon creation.

The constructor is automatically called immediately after the object is


created.

A constructor has the same name as the class in which it resides and is
syntactically similar to a method.

If there is no constructor in a program , System provides its own constructor


called as default constructor.

Constructors doesn’t have any return type.

A constructor which accepts parameters is called as parameterized


constructor.

Constructors can be overloaded. 111


Default Constructor:
A constructor that accepts no parameters is called Default constructor.
If not defined, provided by the compiler.
The default constructor is called whenever an object is created without
specifying initial values.

Ex: class Box {


double width;
double height;
double depth;
Box() {
width = 10;
height = 10;
depth = 10;
}
}
// declare, allocate, and initialize Box objects

Box mybox1 = new Box();


112
// Non parameterized Default Constructor //Parameterized Constructor
class Test{ class Test{
char c='a'; int x,y;
static float f; Test(int a, int b){
Test(){ x=a;
int i=10; y=b;
System.out.println("Test:Test()"); System.out.println(“x value: “+x);
System.out.println(“c value: “+c); System.out.println(“y value: “+y);
System.out.println(“i value: “+i); }
System.out.println(“f value: “+f); }
} class PConDemo{
} public static void main(String args[]){
class ConDemo{ Test t=new Test(10,20);
public static void main(String args[]){ System.out.println(“PConDemo:main()");
Test t=new Test(); }
//t.Test(); }
System.out.println(“ConDemo:main()");
}
}
113
Methods
General Form:
type name(parameter-list) {
// body of method
}
The type of data returned by a method must
be compatible with the return type specified
by the method.
 The variable receiving the value returned by
a method must also be compatible with the
return type specified for the method.
return value; //Here, value is the value returned.
Ex:
double volume(double w, double h, double d) {
114
return w*h*d;
Non parameterized or default Constructor

class Box{ class BoxDemo6{


public static void main(String args[]){
double width;
double height; Box mybox1=new Box();
double depth; Box mybox2=new Box();

Box(){ double vol;


width=10; vol=mybox1.volume();
height=10; System.out.println("Volume is: "+vol);
depth=10;
} vol=mybox2.volume();
double volume(){ System.out.println("Volume is: "+vol);
}
return width*height*depth; }
}
}
11
5
Parameterized Constructor
class Box{ class BoxDemo7{
double width; public static void main(String args[]){
double height;
double depth; Box mybox1=new Box(10,20,15);
Box mybox2=new Box(3,6,9);
Box(double w,double h,double d){ double vol;
width=w;
height=h; vol=mybox1.volume();
depth=d;
} System.out.println("Volume is: "+vol);
double volume(){
return width*height*depth; vol=mybox2.volume();
}
System.out.println("Volume is: "+vol);
}
}
}
116
Access Control

default :
 When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.

private:
 A private member is accessible only to the class in which it is
defined.
 Use private keyword to create private members.

117
public:
 Any class, in any package has access to a class's public
members.
 To declare a public member, use the keyword public.

protected:
 Allows the class itself, subclasses, and all classes in the same
package to access the members.
 To declare a protected member, use the keyword protected.

118
//Example for access control
class AccessTest {
class Test {
int a; // default public static void main(String args[]) {
access
public int b; // public Test ob = new Test();
access
// These are OK, a and b may be accessed directly
private int c; // private ob.a = 10;
access ob.b = 20;
/*protected applies only
when inheritance is involved*/ // This is not OK and will cause an error
//ob.c = 100; // Error!

// methods to access c // You must access c through its methods


ob.setc(100); // OK
void setc(int i){ c = i;
// set c's value System.out.println(ob.a + " " +ob.b + " " + ob.getc());
}
}
}
int getc() {
119
return c; // get c's
Method & Constructor Overloading
 Defining two or more methods within the same class that share the
same name is called method overloading.

 Java uses the type and/or number of arguments to determine


which version of the overloaded method to call.

 Constructors can also be overloaded in the same way as method


overloading.

120
class OverloadDemo { //method overloading
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a; class Overload {
} public static void main(String args[]) {
} OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
121 System.out.println("Result of ob.test(123.25): " + result);
} }
//Constructor Overloading
class CDemo{ public static void main(String args[]){
int value1; CDemo d1 = new CDemo();
CDemo d2 = new CDemo(30);
int value2;
CDemo d3 = new CDemo(30,40);
CDemo(){
d1.display();
value1 = 10;
d2.display();
value2 = 20; d3.display();
System.out.println("Inside 1st }
Constructor"); }
}
CDemo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
CDemo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
122
}
import java.util.Scanner;
import java.util.Scanner;
class ScannerTest{
class ScannerTest{
public static void main(String args[]){

public static void main(String args[]){


Scanner sc=new Scanner(System.in);

Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


System.out.println("Enter your rollno");

int rollno=sc.nextInt();
int rollno=sc.nextInt();
System.out.println("Enter your name");
System.out.println("Enter your name");
String name=sc.next();

String name=sc.next();
System.out.println("Enter your fee");

System.out.println("Enter your fee");


double fee=sc.nextDouble();

double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);

sc.close();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
sc.close();
}

} }
Method

public String next() it returns the next token from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the value as a string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.


this
In java, it is illegal to declare two local variables with the same name inside
the same or enclosing scopes.

But you can have formal parameters to methods, which overlap with the
names of the class’ instance variables.

this keyword is used to refer to the current object.

this can be used to resolve any name collisions that might occur between
instance variables and formal variables.

When a formal variable has the same name as an instance variable, the formal
variable hides the instance variable.(when this is used)

Also used in method chaining and constructor chaining.


125
// instance and formal variables are different
class Box{
double w=5,h=5,d=5;
Box(double w1,double h1,double d1){
w=w1;
h=h1;
d=d1;
}
double volume(){
return w*h*d;
} Output:
} Volume is:6.0
class BoxTest1{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is:
"+b.volume());
126}
// instance and formal variables are same
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
w=w;
h=h;
d=d;
}
double volume(){
return w*h*d;
} Output:
} Volume is:125.0
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is:
"+b.volume());
127}
//’this’ hides the instance variables
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
this.w=w;
this.h=h;
this.d=d;
}
double volume(){
return w*h*d;
} Output:
} Volume is:6.0
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is:
"+b.volume());
128}
Parameter Passing
The call-by-value copies the value of an actual parameter into
the formal parameter of the method.

In this method, changes made to the formal parameter of the


method have no effect on the actual parameter.

In call-by-reference, a reference to an actual parameter (not the


value of the argument) is passed to the formal parameter.

In this method, changes made to the actual parameter will affect
the actual parameter used to call the method.
131
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
Output:
class CallByValue {
a and b before call: 15 20
public static void main(String args[]) { a and b after call: 15 20
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
132
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void meth(Test o) { // pass an object
o.a *= 2;
Output:
a and b before call: 15 20
a and b after call: 30 10
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob); 133
class Box{ //call by reference class OverloadCons2 {
double width,height,depth; public static void main(String args[]) {
Box(Box ob) { Box mybox1 = new Box(10, 20, 15);
width = ob.width; Box mybox2 = new Box();
height = ob.height; Box mycube = new Box(7);
depth = ob.depth; Box myclone = new Box(mybox1);
} double vol;
Box(double w, double h, double d){
width = w; vol = mybox1.volume();
height = h; System.out.println("Volume of mybox1 is " + vol);
depth = d;
} vol = mybox2.volume();
Box(){ System.out.println("Volume of mybox2 is " + vol);
width = -1;
height = -1; vol = mycube.volume();
depth = -1; System.out.println("Volume of cube is " + vol);
}
Box(double len) { vol = myclone.volume();
width = height = depth = System.out.println("Volume of clone is " + vol);
len; }
} }
double volume() {
134 return width * height *
depth;
Recursion
Recursion is the process of defining
something in terms of itself.

A method that calls itself is said to be


recursive.

13
5
class Factorial{
int fact(int n){
int result;
if(n==1)
return 1;
else
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
136
}
Garbage Collection
Garbage collection is done automatically in java.

When no reference to an object exist, that object is assumed to


be no longer needed, and the memory occupied by the object can
be reclaimed.

Garbage collection only occurs at regular intervals during the


execution of your program.

We can run garbage collection on demand by calling the gc()


method.
public static void gc(): Initiates the garbage collection.
137 System.gc();
public class GarbageCollector{
public class protected void finalize()throws Throwable
GarbageCollector{ {
public static void System.out.println("Garbage Collection started explicitly
main(String[] args) { }
int SIZE = 10; public static void main(String[] args) {
StringBuffer s; int SIZE = 10;
for (int i = 0; i < //StringBuffer s=new StringBuffer();
SIZE; i++) { GarbageCollector g=new
GarbageCollector();
System.out.println("Garbage
Collection started //g=null;
implicitly."); for (int i = 0; i < SIZE; i++) {
} System.out.println("Garbage Collection implicitly.");
}
try{
System.out.println("Garbag
e Collection started g.finalize(); }
explicitly."); catch(Throwable e)
System.gc(); {
e.printStackTrace();
}
}
} 138 System.gc();
}}
public class GarbageCollector{
protected void finalize()throws Throwable
{
System.out.println("Garbage Collection started explicitly.");
}
public static void main(String[] args) {
int SIZE = 10;
//StringBuffer s=new StringBuffer();
GarbageCollector g=new GarbageCollector();
//g=null;
for (int i = 0; i < SIZE; i++) {
System.out.println("Garbage Collection started implicitly.");
}
try{
g.finalize();
}
catch(Throwable e)
{
e.printStackTrace();
}
System.gc();
}
}
finalize( ) method

Sometimes an object will need to perform some action when it is


destroyed.
Ex:
If an object is holding some non-java resource such as a file, then you
might want to make sure these resources are freed before an object is
destroyed.

To handle such situations, Java provides a mechanism called


finalization.

The finalize( ) method has this general form:


protected void finalize( ){
// finalization code here
}
140
String Handling
Types of string handling classes:

String
Once an object is created, no modifications can be done on that.

StringBuffer
Modifications can be allowed on created object.

StringTokenizer
Used to divide the string into substrings based on tokens.

String and SringBuffer classes are available in java.lang package where as


StringTokenizer class is available in java.util package.

141
String
In java a string is a sequence of characters. They are objects of type String.

Once a String object has been created, we can not change the characters that
comprise in the string.

Strings are unchangeable once they are created so they are called as
immutable.

You can still perform all types of string operations. But, a new String object
is created that contains the modifications. The original string is left
unchanged.

To get changeable strings use the class called StringBuffer.

String and StringBuffer classes are declared final, so there cannot be


subclasses of these classes.

String class is defined in java.lang package, so these are available to all


programmers automatically.
142
String Constructors
String s= new String();

String(char chars[])

String(char chars[], int startIndex, int numChars)

String(String strobj)

String str=new String(“SNIST”);

String str[]=new String[size];

143
String Constructors
 String s= new String(); //To create an empty String call the default constructor.

 String(char chars[]) //To create a string initialized by an array of characters.


String str = "abcd"; is equivalent to
char chars[]={‘a’,’b’,’c’,’d’};
String s=new String(chars);

 String( char chars[], int startIndex, int numChars) //To create a string by specifying
positions from an array of characters
char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String s=new String(chars,2,3); //This initializes s with characters
“cde”.

 String(String str); //Construct a string object by passing another string object.


String str = "abcd";
String str2 = new String(str);

 String(byte asciiChars[ ]) // Construct a string from subset of byte


144 array.

// Construct one String from another. // Construct string from subset of char array.

class MakeString { class SubStringCons {


public static void main(String args[]) public static void main(String args[])
{ {
char c[] = {'J', 'a', 'v', 'a'}; byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(c); String s1 = new
String s2 = new String(s1); String(ascii);
System.out.println(s1); System.out.println(s1);
System.out.println(s2); String s2 = new String(ascii, 2, 3);
} System.out.println(s2);
} }
}
Output:
Output:
Java
Java ABCDEF
CDE
145
String Length

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
System.out.println(s.length()); //it
returns 3.

14
6
 Special String Operations
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
 Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
 String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( ), startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
 Searching Strings
 Modifying a String
substring( )
concat( )
replace( )
trim( )
 Changing the Case of Characters Within a String
147
Special String Operations
String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s); // He is 9 years old.

String Concatenation with Other Data Types


int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s); // He is 9 years old.

String s = "four: " + 2 + 2;


System.out.println(s);
//This fragment displays four: 22 rather than the four: 4

String s = "four: " + (2 + 2);


//Now s contains the string “four: 4”.
148
Special String Operations
Box’s toString() method is automatically invoked when a Box object is used in a
concatenation expression or in a call to println( ).

String Conversion using toString( )


// Override toString() for Box class. class toStringDemo {
class Box { public static void main(String args[]) {
double width; Box b = new Box(10, 12, 14);
double height; String s = "Box b: " + b;
double depth; // concatenate Box object
Box(double w, double h, double d) { System.out.println(b);
width = w; // convert Box to string
height = h; System.out.println(s);
depth = d; }
} }
public String toString() {
return "Dimensions are " + width + " by " The output of this program is shown here:
+depth + " by " + height + ".";
} Dimensions are 10.0 by 14.0 by 12.0
}
Box b: Dimensions are 10.0 by 14.0 by 12.0
14
9
Character Extraction
char charAt(int where)
//To extract a single character from a String class getCharsDemo {
char ch; public static void main(String args[]) {
ch = "abc".charAt(1); String s = "This is a demo of the
//assigns the value “b” to ch. getChars method.";
void getChars(int sourceStart, int sourceEnd, char
int start = 10;
int end = 14;
target[ ], int targetStart)
char buf[] = new char[end - start];
//to extract more than one character at a time. s.getChars(start, end, buf, 0);
byte[ ] getBytes( ) System.out.println (buf);
//to store the characters in an array of bytes and it }
uses the default character-to-byte conversions }
provided by the platform.
Here is the output of this program: demo
//String source=“hi”+”how”+”are”+”you.”
//byte buf[] = source.getBytes();
char[ ] toCharArray( )
//to convert all the characters in a String object into a
character array. It returns an array of characters for
the entire string.
150
class GetBytesDemo{
public static void main(String[] args){
String str = "abc“ + ”ABC”;
byte[] b = str.getBytes();
//char[] c=str.toCharArray();
System.out.println(str);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+" ");
//System.out.print(c[i]+" ");
}
}
}
Output: abcABC
97 98 99 65 66 67

151
String Comparison
 boolean equals(Object str)
//To compare two strings for equality. It returns true if the strings contain the same
characters in the same order, and false otherwise.
 boolean equalsIgnoreCase(String str)
//To perform a comparison that ignores case differences.

// Demonstrate equals() and equalsIgnoreCase(). System.out.println(s1.equals(s4));


class equalsDemo {
public static void main(String args[]) { System.out.println(s1.equalsIgnoreCase(s4));
String s1 = "Hello"; }
String s2 = "Hello"; }
String s3 = "Good-bye";
String s4 = "HELLO"; The output from the program is shown here:
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3)); true
false
false
true

15
2
String Comparison
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
numChars)

boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int


str2StartIndex, int numChars)

//The regionMatches( ) method compares a specific region inside a string


with another specific region in another string.
//startIndex specifies the index at which the region begins within the
invoking String object.
//The String being compared is specified by str2. The index at which the
comparison will start within str2 is specified by str2StartIndex.
//The length of the substring being compared is passed in numChars.

153
String Comparison
class RegionTest{
public static void main(String args[]){
String str1 = "This is Test";
String str2 = "THIS IS TEST";
if(str1.regionMatches(5,str2,5,3)) {
// Case: pos1,secdString,pos1,len
System.out.println("Strings are Equal");
}
else{
System.out.println("Strings are NOT Equal");
}
}
}
Output:
Strings are NOT Equal
154
String Comparison
boolean startsWith(String str) //to determine whether a given String
begins with a specified string.

boolean endsWith(String str) // to determine whether the String in


question ends with a specified string.

Ex: "Football".endsWith("ball") and "Football".startsWith("Foot") are both true.

boolean startsWith(String str, int startIndex) //to specifies the index


into
the invoking string at which point the search will begin.

Ex: "Football".startsWith("ball", 4) returns true.

equals( ) Versus ==
// It compares the characters inside a String object
//To compare two object references to see whether they refer to the same155
String Comparison
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
//String s2 = s1;
System.out.println(s1.equals(s2));
System.out.println( s1 == s2);
}
}
Output:

true
false
156
String Comparison
int compareTo(String str)
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than
str.
Zero The two strings are equal.

int compareToIgnoreCase(String str)

157
String Comparison
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now aid all come country for good is men
of
the the their time to to
158
Searching Strings
indexOf( ) //Searches for the first occurrence of a character or
substring.
lastIndexOf( ) //Searches for the last occurrence of a character or
substring.
int indexOf(int ch) //To search for the first occurrence of a character.
int lastIndexOf(int ch) //To search for the last occurrence of a character.
int indexOf(String str) //To search for the first or last occurrence of a substring.

int lastIndexOf(String str)


int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

In all cases, the methods return the index at which the character or substring
159
was found, or –1 on failure.
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo { Here is the output of this program:
public static void main(String args[]) { Now is the time for all good men
String s = "Now is the time for all good men " +"to to come to the aid of their country.
come to the aid of their country."; indexOf(t) = 7
System.out.println(s); lastIndexOf(t) = 65
indexOf(the) = 7
System.out.println("indexOf(t) = " +s.indexOf('t')); lastIndexOf(the) = 55
System.out.println("lastIndexOf(t) = " indexOf(t, 10) = 11
+s.lastIndexOf('t')); lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
System.out.println("indexOf(the) = " +s.indexOf("the")); lastIndexOf(the, 60) = 55
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));

System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));


System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));

System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));


System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));
}
}

160
Modifying a String
String substring(int startIndex)
//To extract a substring, startIndex specifies the beginning index
String substring(int startIndex, int endIndex)
// Here endIndex specifies the stopping point.
//endIndex-1
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String result = org.substring(0, 2);
System.out.println(result);
}
}

Output:
Th
161
String concat(String str)
//To concatenate two strings, concat( ) performs the same function as +.
String s1 = "one";
String s2 = s1.concat("two");
String s1 = "one";
String s2 = s1 + "two";

String replace(char original, char replacement) //To replace all


occurrences of one character in the invoking string with another character
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.

String trim( ) //Removes leading and trailing whitespaces.


Here is an example:
String s = " Hello World ".trim();
//This puts the string “Hello World” into s.
162
Data Conversion Using valueOf( )

static String valueOf(double num)


// converts data from its internal format into a human-readable form.
static String valueOf(long num)
//each type can be converted properly into a string
static String valueOf(Object ob)
static String valueOf(char chars[ ])

163
import java.io.*;
public class valueOfDemo {

public static void main(String args[]) {


double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };

System.out.println("Return Value : " + String.valueOf(d) );


System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) );
}
}
Changing the Case of Characters Within a String
String toLowerCase( )
//converts all the characters in a string from uppercase to
lowercase.
String toUpperCase( )
//converts all the characters in a string from lowercase to uppercase
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[]){
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Output:
Original: This is a test.
Uppercase: THIS IS A TEST.
165 Lowercase: this is a test.
StringBuffer

A StringBuffer is like a String, but can be modified.

StringBuffer represents growable and writeable character


sequences.

StringBuffer may have characters and substrings inserted


in the middle or appended to the end.

166
StringBuffer Constructors
StringBuffer( )
// The default constructor (the one with no parameters)
reserves room for 16 characters without reallocation.

StringBuffer(int size)
// accepts an integer argument that explicitly sets the size
of the buffer.

StringBuffer(String str)
// str + reserves room for 16 more characters without
reallocation.

167
Methods
length( ) and capacity( )
setLength( )
charAt( ) and setCharAt( )
getChars( )
append( )
insert( )
reverse( )
delete( ) and deleteCharAt( )
replace( )
substring( )

168
int length( ) //The current length of a StringBuffer can be found via the length( ) method
int capacity( ) //The total allocated capacity can be found through the capacity( ) method.

// StringBuffer length vs. capacity.


class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
Output:
buffer = Hello
length = 5
capacity = 21
169
void setLength(int len) //To set the length of the buffer within a StringBuffer object.
char charAt(int where)
//The value of a single character can be obtained from a StringBuffer via
the charAt( ) method.
void setCharAt(int where, char ch)
//To set the value of a character, ch specifies the new value of that character.

// Demonstrate charAt() and setCharAt().


class setCharAtDemo
{
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " +
sb.charAt(1));
Output:
sb.setCharAt(1, 'i');
buffer before = Hello
sb.setLength(2);
charAt(1) before = e
System.out.println("buffer after = " + sb);
buffer after = Hi
System.out.println("charAt(1) after = " +
sb.charAt(1)); charAt(1) after = i
170
}
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
// To copy a substring of a StringBuffer into an array

StringBuffer append(String str)


// concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object.

StringBuffer append(int num)

StringBuffer append(Object obj)

String.valueOf( ) is called for each parameter to obtain its string


representation. The result is appended to the current StringBuffer
object.
171
// Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
Output:
a = 42!

172
//The insert( ) method inserts one string into another.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
Output:
I like Java!
173
StringBuffer reverse( )
// reverse the characters within a StringBuffer object using reverse( )
// Using reverse() to reverse a StringBuffer.

class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
174
StringBuffer delete(int startIndex, int endIndex) // to delete characters.
StringBuffer deleteCharAt(int loc)
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Output:
After delete: This a test.
After deleteCharAt: his a test.
175
StringBuffer replace(int startIndex, int endIndex, String str);
//It replaces one set of characters with another set inside a StringBuffer object.
// The replacement string is passed in str.
// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output: After replace: This was a test.

String substring(int startIndex) //to return sub strings.


String substring(int startIndex, int endIndex)
176
StringTokenizer
The StringTokenizer class provides the first step in parsing process,
often called the lexer (lexical analyzer) or scanner.

Parsing is the division of text into a set of discrete parts, or tokens.

To use StringTokenizer
Specify an input string and a delimiter string.

Delimiters are characters that separate tokens.

Each character in the delimiters string is considered a valid delimiter.


Ex: “, ; : a”

The default set of delimiters consists of the whitespace characters:


177 Ex: space, tab, newline.
StringTokenizer Constructors

StringTokenizer(String str)

StringTokenizer(String str, String delimiters)

StringTokenizer(String str, String delimiters, boolean delimAsToken)

Methods
int countTokens( ) //returns number of tokens in the string.
boolean hasMoreTokens( ) //checks whether tokens are there or
not
String nextToken( ) //returns the token in the string

178
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo{
//static String str = "Hello Welcome to Java Programming";
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
//StringTokenizer st = new StringTokenizer(str);
//StringTokenizer st = new StringTokenizer(str,",");
StringTokenizer st = new Output:
StringTokenizer(str,",",true); Hello
while(st.hasMoreTokens()) { ,
String tokens = st.nextToken(); Welcome
,
System.out.println(tokens + "\n");
to
} ,
} Java
} ,
179 Programming
Exercise1:

Write a java program that reads a line of integers and


then displays each integer and find the sum of the
integers (using StringTokenizer)

18
0
import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+“is: "+sum);
}
}

Output:
Enter sum of integers: 10+20+30+40
Sum of 10+20+30+40 is: 100

181

You might also like