Unit 1
Unit 1
DATA DATA
Communication
FUNCTION FUNCTION
Object C
DATA
FUNCTION
Inheritance
6. Polymorphism:
Polymorphism means ability to take many forms. It allows a single name/operator to be
associated with different operations depending on the type of data passed to it. Examples of
polymorphism are function overloading, operator overloading and dynamic binding (virtual
functions).
Polymorphism
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding or late binding means that the code associated with a given procedure
call is not known until the time of the call at run time.
8. Message Passing
OOPs consist of a set of objects that communicate with each other. Message passing
involves following steps-
1. Creating classes that define objects and their behavior
2. Creating objects from class definitions and
3. Establishing communication among objects through message passing.
Message passing involves specifying the name of the object, the name of the function i.e.
message and the information to be sent.
Example:
customer. balance(account no)
BENEFITS OF OOPs
OOP offers several benefits to both the program designer and the user. The advantages are:
Through inheritance, we can eliminate redundant code and extend the use of existing
classes
We can build program from the standard working module that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other part of the program.
It is possible to have multiple instances of an object to co-exist without any interference
It is easy to partition the work in a project, based on objects.
Object oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects makes the interface
description with external systems much simpler.
Software complexity can be easily managed.
1. Simple
Java language is simple because:
syntax is based on C++.
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
2. Object-oriented
Like C++, java uses all the OOP concepts like encapsulation, inheritance, and polymorphism etc.
Java is called a purely object-oriented language as everything we write inside class in a java
program.
3. Architecture-Neutral
Java code can be run on multiple platforms e.g., Windows, Linux, Sun Solaris, Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can run on any machine with any processor and with any OS. i.e.,
Write Once and Run Anywhere (WORA).
4. Security
When we use a Java-compatible Web browser, we can safely download Java applets
without fear of viral infection or malicious intent. Java achieves this protection by confining a
Java program to the Java execution environment and not allowing it access to other parts of the
computer. This control is exercised by JVM.
6. Portability:
Java does not have implementation dependent aspects and it yields or gives same result on any
machine. We may carry the java bytecode to any platform.
7. Distributed:
Java is designed for use on network; it has an extensive library which works in agreement with
Transmission Control Protocol (TCP) and the Internet Protocol (IP) .
We can create distributed applications in java. RMI (Remote Method Invocation) and EJB
(Enterprise JavaBeans) are used for creating distributed applications. We may access files by
calling the methods from any machine on the internet.
8. Multithreaded:
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows us to
write programs that do many things simultaneously. The Java run-time system comes with an
elegant yet sophisticated solution for multiprocess synchronization that enables us to construct
smoothly running interactive systems.
9. Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner. This is crucial to the robustness of the applet environment,
in which small fragments of byte code may be dynamically updated on a running system.
1.2 JVM
Java Virtual Machine (JVM) is the engine that drives the Java code. Mostly in other Programming
Languages, compiler produce code for a particular systembut Java compiler produce Bytecode for a Java
Virtual Machine. When we compile a Java program, then bytecode is generated. Bytecode is the source
code that can be used to run on any platform. Bytecode is an intermediary language between Java source
and the host system. It is the medium which compiles Java code to bytecode which gets interpreted on a
different machine and hence it makes it Platform/Operating system independent.
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have in OS
because JVM is platform dependent.
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in
the method area. For each “.class” file, JVM stores the following information in the method area.
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum.
Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap
memory. Please note that this object is of type Class predefined in java.lang package. These Class object
can be used by the programmer for getting class level information like the name of the class, parent
name, methods and variable information etc. To get this object reference we can use getClass() method
of Object class.
Initialization: In this phase, all static variables are assigned with their values defined in the code and
static block (if any). This is executed from top to bottom in a class and from parent to child in the class
hierarchy.
In general, there are three class loaders:
Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable
of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib”
directory. This path is popularly known as the bootstrap path. It is implemented in native
languages like C, C++.
Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in
the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory
specified by the java.ext.dirs system property. It is implemented in java by the
sun.misc.Launcher$ExtClassLoader class.
System/Application class loader: It is a child of the extension class loader. It is responsible to
load classes from the application classpath. It internally uses Environment Variable which
mapped to java.class.path. It is also implemented in Java by the
sun.misc.Launcher$AppClassLoader class.
JVM Memory
1. Method area: In the method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There
is only one method area per JVM, and it is a shared resource. From java 8, static variables are
now stored in Heap area.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area
per JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block
of this stack is called activation record/stack frame which stores methods calls. All local
variables of that method are stored in their corresponding frame. After a thread terminates, its
run-time stack will be destroyed by JVM. It is not a shared resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread
has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native
method information.
JVM
JVM is the abbreviation for Java virtual machine which is basically specification that provides a
runtime environment in which Java byte code can be executed i.e it is something which is abstract and
its implementation is independent to choose the algorithm and has been provided by Sun and other
companies. It is JVM which is responsible for converting Byte code to the machine specific code. It
can also run those programs which are written in other languages and compiled to Java bytecode.The
JVM performs the mentioned tasks: Loads code, Verifies code, Executes code, Provides runtime
environment.
JRE
JRE is Java runtime environment which is the implementation of JVM i.e the specifications which are
defined in JVM are implemented and creates corresponding environment for the execution of code.JRE
comprises mainly java binaries and other classes to execute the program alike of JVM it physically
exists. Along with Java binaries JRE also consist of various technologies of deployment, user interfaces
to interact with code executed, some base libraries for different functionalities and language and util
based libraries.
JDK
JDK is abbreviation for Java Development Kit which includes all the tools, executable and binaries
required to compile, debug and execute a Java Program.JDK is platform dependent i.e there is separate
installers for Windows, Mac, and Unix systems.JDK includes both JVM and JRE and is entirely
responsible for code execution. It is the version of JDK which represent version of Java.
S.
Key JDK JRE JVM
No.
Definition JDK (Java Development JRE (Java Runtime JVM (Java Virtual Machine) is
Kit) is a software Environment) is the an abstract machine that is
development kit to implementation of platform-dependent and has
develop applications in JVM and is defined as three notions as a specification,
Java. In addition to JRE, a software package a document that describes
JDK also contains that provides Java requirement of JVM
number of development class libraries, along implementation,
1
tools (compilers, with Java Virtual implementation, a computer
JavaDoc, Java Debugger Machine (JVM), and program that meets JVM
etc.). other components to requirements, and instance, an
run applications implementation that executes
written in Java Java byte code provides a
programming. runtime environment for
executing Java byte code.
Prime JDK is primarily used for On other hand JRE is JVM on other hand specifies all
functionality code execution and has majorly responsible for the implementations and
2
prime functionality of creating environment responsible to provide these
development. for code execution. implementations to JRE.
Tools As JDK is responsible On other hand JRE JVM does not include software
for prime development does not contain tools development tools.
so it contains tools for such as compiler or
developing, debugging debugger etc. Rather it
4
and monitoring java contains class libraries
application. and other supporting
files that JVM requires
to run the program.
Implementation JDK = Java Runtime JRE = Java Virtual JVM = Only Runtime
Environment (JRE) + Machine (JVM) + environment for executing the
5
Development tools Libraries to run the Java byte code.
application
Documentation Section
It includes the comments that improve the readability of the program. A comment is a non- executable
statement that helps to read and understand a program especially when your programs get more complex.
Eg:1
// Calculate sum of two numbers
Eg:2
/*calculate sum of two
numbersand it is a multiline
comment */
Package Statement
A package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc.
java.lang.*; package is imported by default and this package is known as default package. It must
appear as the first statement in the source code file before any class or interface declaration. This
statement is optional.
Import statements
An import statement is used for referring classes that are declared in other packages. The import
statement is written after a package statement but before any class definition. You can import a
specific class or all the classes of the package.
Example If you want to import Date class of java.util package using import statement then write.
import java.util.Date;
Interface Section
In the interface section, we specify the interfaces. An interface is similar to a class but contains
only constants and method declarations.
Class Definition:
Java program may contain multiple class definition. Classes are primary feature of Java program.
The classes are used to map real world problems.
Output:
Welcome to Java World
1.4 Identifiers
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name,
method name, package name, constant name, and more. There are some reserved words that cannot be
used as an identifier.
Example:
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello JavaTpoint");
}
}
From the above example, we have the following Java identifiers:
1. HelloJava (Class name)
2. main (main method)
3. String (Predefined Class name)
4. args (String variables)
5. System (Predefined class)
6. out (Variable name)
7. println (method)
Data types
Data type defines the values that a variable can take. For example, if a variable has int data type, it can
only take integer values.
Primitive Data types:
byte
This can hold whole number between -128 and 127.
Mostly used to save memory and when you are certain that the numbers would be in the limit
specified by byte data type.
Default size of this data type: 1 byte. Default value: 0
Example:
class JavaExample
{
public static void main(String[] args)
{
byte num;
num = 113;
System.out.println(num);
}
}
short & int
Short: This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte short num = 45678;
int: Used when short is not large enough to hold the number, it has a wider range: -
2,147,483,648 to 2,147,483,647
Default size: 4 byte Default value: 0
Example
class JavaExample
{
public static void main(String[] args)
{
short num;
num = 150;
System.out.println(num); }
}
}
Output
150
long
Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example
class JavaExample
{
public static void main(String[] args)
{
long num = -12332252626L;
System.out.println(num);
}
}
Output
-12332252626
double
Sufficient for holding 15 decimal digits
size: 8 bytes
Example
class JavaExample
{
public static void main(String[] args)
{
double num = -42937737.9d;
System.out.println(num);
}
}
Output
-4.29377379E7
float
Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
class JavaExample
{
public static void main(String[] args)
{
float num = 19.98f;
System.out.println(num);
}
}
Output
19.98
boolean
boolean: holds either true of false.
class JavaExample
{
public static void main(String[] args)
{
boolean b = false;
System.out.println(b);
}
}
Output
false
char
char: holds characters.
size: 2 bytes
class JavaExample
{
public static void main(String[] args)
{
char ch = 'Z';
System.out.println(ch);
}
}
Output
Z
1.5 Variables
In Java, Variables are the data containers that save the data values during Java program
execution. Every Variable in Java is assigned a data type that designates the type and quantity of value
it can hold. A variable is a memory location name for the data. Java 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. Variables in Java are only a name given to a memory location. All the operations
done on the variable affect that memory location. In Java, all variables must be declared before use.
Syntax:
datatype variablename;
The Scope and Lifetime of Variables:
Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. The scope defined by a method begins
with its opening curly brace. Variables declared inside a scope are not visible (that is, accessible)to code
that is defined outside that scope. Scopes can be nested. When this occurs, the outer scope encloses the
inner scope. This means that objects declared in the outer scope will be visible to code within the inner
scope. However, Objects declared within the inner scope will not be visible outside it. To understand
the effect of nested scopes, consider the following program:
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main x = 10;
if(x == 10)
{ // start 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);
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope and is
accessible to all subsequent code within main( ). Within the if block, y is declared. Since a block defines
a scope, y is only visible to other code within its block and lifetime of y is over once it comes out from
the block. Within the f block, x can be used because code within a block (that is, a nested scope) has
access to variables declared by an enclosing scope. Also, a variable declared within a block will lose its
value when the block is left. Thus, the lifetime of a variable is confined to its scope. If a variable
declaration includes an initializer, then that variable will be reinitialized each time the block in which it
is declared is entered. There are three types of variables in Java:
local variable
instance variable
static variable
a) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class are not even aware that the variable exists. A local
variable cannot be defined with "static" keyword.
b) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static. It is called instance variable because its value is instance specific and is not shared
among instances.
c) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory
Example
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
1.6 Comments
Three types of comments or comment lines are defined by Java i.e. single-line, multiline and
documentation comment line. Comment lines are never executed during program execution. They
included in a program just to convey some message to the programmer or user.
// single line comment: Single line comment is used, when comments consists of a line.
/* multi line
Comment*/: Multiline comment is used, when comments consists of more than one line.
/** documentation Comment */: Documentation comment is used to include documentation part of a
program.
1.8 Operators
Operators are the symbols used for performing specific operations. Each operator performs specific
operations. Java provides many types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operator
Unary Operators
Ternary Operator
Bitwise Operators
Shift Operators
instance of operator
1. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
2. Relational Operator
These operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements.
== Equal to x == y
!= Not equal x != y
3. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function like
AND gate and OR gate in digital electronics.
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
Example
class Main
{
public static void main(String[] args)
{
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
Output
x && y: false
x || y: true
!x: false
4. Assignment Operator
Assignment operator (=) is used to assign a value to any variable. It has right-to-left associativity, i.e.
value given on the right-hand side of the operator is assigned to the variable on the left. The assignment
operator can be combined with other operators to build a shorter version of the statement called a
Compound Statement.
For example, instead of a = a+5, we can write a += 5.
+=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
-=, for subtracting the right operand from the left operand and then assigning it to the variable
on the left.
*=, for multiplying the left operand with the right operand and then assigning it to the variable
on the left.
/=, for dividing the left operand by the right operand and then assigning it to the variable on the
left.
%=, for assigning the modulo of the left operand by the right operand and then assigning it to
the variable on the left.
Example
class Main
{
public static void main(String[] args)
{
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
5. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.
Unary minus (-), used for negating the values.
Unary plus (+) indicates the positive value (numbers are positive without this, however).
Increment operator (++), used for incrementing the value by 1. There are two varieties of
increment operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
Decrement operator (--), used for decrementing the value by 1. There are two varieties of
decrement operators.
Post-decrement: Value is first used for computing the result and then
decremented.
Pre-Decrement: The value is decremented first, and then the result is computed.
Example
class Main
{
public static void main(String[] args)
{
int a = 10;
int b = 10;
System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement : " + (b--));
System.out.println("Predecrement : " + (--b));
}
}
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
6. Ternary Operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the
name Ternary.
Syntax
condition ? if true : if false
Example
class Main
{
public static void main(String[] args)
{
int a = 20, b = 10, result;
result = (a > b) ? a : b;
System.out.println("Max of two numbers = "+ result);
}
}
Output
Max of two numbers = 20
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be used
with any of the integer types.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement
representation of the input value, i.e., with all bits inverted.
Example
class Main
{
public static void main(String[] args)
{
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. 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.
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as multiplying the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left
as a result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing
the number with some power of two.
Example
class Main
{
public static void main(String[] args)
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
Output
a<<1 : 20
a>>1 : 5
a) Simple if
It is used to decide whether a certain statement or block of statements will be executed or not. If
a certain condition is true then a block of statements is executed otherwise not.
Syntax
if(condition)
{
// Statements to execute if
// condition is true
}
The statements will be evaluated if the value of the condition is true
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>0)
System.out.println(n+" is a positive number!");
}
}
Output
Enter n:
3
3 is a positive number!
b) If-else Syntax
Together with if, else statement can be used to execute a block of code when the condition is
false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
if(n>=10 && n<100)
System.out.println(n+" is a Two digit number!");
else
System.out.println(n+" is not a Two digit number!");
}
}
Output
Enter n:
86
86 is a Two digit number!
c) Nested if
A nested if is an if statement that is the target of another if or else. Nested if statements mean an
if statement inside an if statement.
Syntax
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n1, n2, n3;
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers: ");
n1 = in.nextInt();
n2 = in.nextInt();
n3 = in.nextInt();
if(n1>n2)
{
if(n1>n3)
{
System.out.println(n1+" is greater!");
}
}
else
{
if(n2>n3)
System.out.println(n2+" is greater!");
else
System.out.println(n3+" is greater!");
}
}
}
Output
Enter 3 numbers:
89
125
36
125 is greater!
d) if-else-if ladder
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int mark;
Scanner in = new Scanner(System.in);
System.out.println("Enter a mark: ");
mark = in.nextInt();
if(mark>90)
{
System.out.println("Grade - O");
}
else if(mark>80)
{
System.out.println("Grade - A");
}
else if(mark>70)
{
System.out.println("Grade - B");
}
else if(mark>60)
{
System.out.println("Grade - C");
}
else if(mark>=50)
{
System.out.println("Grade - D");
}
else
{
System.out.println("Fail");
}
}
}
Output
Enter a mark:
86
Grade – A
ii) switch
The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression. Syntax
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
switch(n)
{
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5 :
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
case 7 :
System.out.println("Sunday");
break;
default:
System.out.println("Invalid");
}
}
}
Output
Enter n:
5
Friday
iii) Jump
jump: Java supports three jump statements: break and continue. These statements transfer control to
another part of the program.
a) break: In Java, a break is majorly used to terminate a sequence in a switch statement.
b) continue: Sometimes it is useful to force an early iteration of a loop.
Example for break
import java.util.*;
class Main
{
public static void main(String args[])
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
for (int i = 1; i < n; i++)
{
if (i == 5)
break;
System.out.print(i + " ");
}
}
}
Output
Enter n:
10
1234
equals() Compares two strings. Returns true if the strings are equal, and
false if not
replace() Searches a string for a specified value, and returns a new string
where the specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that matches the given
regular expression with the given replacement
replaceAll() Replaces each substring of this string that matches the given
regular expression with the given replacement
Program
class Main
{
public static void main(String args[])
{
String s = "Java programming";
System.out.println("String length = " + s.length());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
String s1 = "C++";
String s2 = "Programming";
System.out.println("Concatenated string = " +s1.concat(s2));
String s4 = "Python Programming";
System.out.println("Index of on " +s4.indexOf("on"));
System.out.println("Index of a = " +s4.indexOf('a',3));
Boolean out = "Java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equals("Java");
System.out.println("Checking Equality " + out);
out = "java".equalsIgnoreCase("Java");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
String word = "Hello";
System.out.println("Changing to lower Case " +word.toLowerCase());
System.out.println("Changing to UPPER Case " +word.toUpperCase());
String word1 = " Java is easy to learn ";
System.out.println("Trim the word " + word1.trim());
String str1 = "Java programming";
System.out.println("Original String " + str1);
String str2 = str1.replace("Java" ,"C") ;
System.out.println("Replaced Java with C -> " + str2);
}
}
Output
String length = 16
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++Programming
Index of on 4
Index of a = 12
Checking Equality true
Checking Equality false
Checking Equality true
the difference between ASCII value is=-13
Changing to lower Case hello
Changing to UPPER Case HELLO
Trim the word Java is easy to learn
Original String Java programming
Replaced Java with C -> C programming
StringBuffer class
StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing to modify the contents of a string without
creating a new object every time.
Example
class Main
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Java programming");
System.out.println("String length = " + s.length());
System.out.println("String capacity = "+s.capacity());
System.out.println("Character at 3rd position = "+ s.charAt(3));
System.out.println("Substring " + s.substring(3));
System.out.println("Substring = " + s.substring(2,5));
StringBuffer s1 = new StringBuffer("C++");
StringBuffer s2 = new StringBuffer(" Programming");
System.out.println("Concatenated string = " +s1.append(s2));
System.out.println("String1 = " + s1);
System.out.println("String2 = " + s2);
s1.insert(15," is easy to learn");
System.out.println("String1 = " + s1);
s1.replace(0,3, "Java");
System.out.println("String1 = " + s1);
s1.delete(0, 4);
System.out.println("String1 = " + s1);
s1.reverse();
System.out.println("String1 = " + s1);
}
}
Output
String length = 16
String capacity = 32
Character at 3rd position = a
Substring a programming
Substring = va
Concatenated string = C++ Programming
String1 = C++ Programming
String2 = Programming
String1 = C++ Programming is easy to learn
String1 = Java Programming is easy to learn
String1 = Programming is easy to learn
String1 = nrael ot ysae si gnimmargorP
StringBuilder
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.
StringBuilder Constructors
StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16
characters.
StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial
capacity specified by the capacity argument.
StringBuilder(CharSequence seq): Constructs a string builder that contains the same
characters as the specified CharSequence.
StringBuilder(String str): Constructs a string builder initialized to the contents of the specified
string.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
StringBuilder str = new StringBuilder();
str.append("StringBuilder");
System.out.println("String = " + str.toString());
StringBuilder str1 = new StringBuilder("Class");
System.out.println("String1 = " + str1.toString());
StringBuilder str2 = new StringBuilder(10);
System.out.println("String2 capacity = "+ str2.capacity());
StringBuilder str3 = new StringBuilder(str1.toString());
System.out.println("String3 = " + str3.toString());
str3.reverse();
System.out.println("Reversed String3 = " + str3.toString());
}
}
Output
String = StringBuilder
String1 = Class
String2 capacity = 10
String3 = Class
Reversed String3 = ssalC
StringJoiner
StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated
by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. StringJoiner
provides an easy way to do that without much code to write.
StringJoiner Constructors
• StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no
prefix or suffix, and a copy of the supplied delimiter.
Adds a copy of the given CharSequence value as the next element of the
add()
StringJoiner value. If newElement is null, then “null” is added.
Adds the contents of the given StringJoiner without prefix and suffix as the next
element if it is non-empty. If the given StringJoiner is empty, the call has no effect.
merge() Suppose the other StringJoiner is using a different delimiter. In that case, elements
from the other StringJoiner are concatenated with that delimiter, and the result is
appended to this StringJoiner as a single element.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
StringJoiner sj1 = new StringJoiner(",");
System.out.println(sj1);
sj1.setEmptyValue("sj1 is empty");
System.out.println(sj1);
sj1.add("Java");
sj1.add("C programming");
sj1.add("Python").add("C++");
System.out.println(sj1);
System.out.println("Length of sj1 : "+ sj1.length());
StringJoiner sj2 = new StringJoiner(":");
sj2.add("Hai");
System.out.println(sj2);
sj2.add("Hello");
System.out.println(sj2);
sj1.merge(sj2);
System.out.println(sj1);
System.out.println(sj1.toString());
}
}
Output
sj1 is empty
Java,C programming,Python,C++
Length of sj1 : 29
Hai
Hai:Hello
Java,C programming,Python,C++,Hai:Hello
Java,C programming,Python,C++,Hai:Hello
StringTokenizer
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object
internally maintains a current position within the string to be tokenized. A token is returned by taking a
substring of the string that was used to create the StringTokenizer object. It provides the first step in the
parsing process often called lexer or scanner. The String Tokenizer class allows an application to break
strings into tokens.
StringTokenizer Construtors
• StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and
form feed.
• StringTokenizer(String str, String delim): delim is a set of delimiters that are used to
tokenize the given string.
• StringTokenizer(String str, String delim, boolean flag): The first two parameters have the
same meaning wherein The flag serves the following purpose.
Example
import java.util.*;
{
public static void main(String args[])
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
Output
Output
Hello
How
are
you
JAVA
Code
String
JAVA
:
Code
String