Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views48 pages

Unit 1

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

Unit 1

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

Hindusthan College of Engineering and Technology

Hindusthan College of Engineering and Technology


An Autonomous InstitutionInstitution,
(An Autonomous Affiliated toAffiliated
Anna University | ApprovedChennai)
to Anna University, by AICTE, New Delhi
Valley
Accredited with Campus,
‘A’ Grade by NAAC | Accredited
Pollachi Highway, Coimbatore – 641032
by NBA (ECE, MECH, EEE, IT & CSE)
Valley Campus, Pollachi Highway, Coimbatore 641 032.| www.hicet.ac.in
22CS3251 / OBJECT ORIENTED PROGRAMMING
USING JAVA

UNIT 1 - INTRODUCTION TO JAVA and OOP


Object Oriented Programming - First java program Hello World - JVM architecture - JDK – JRE -
identifiers – variables – comments - command line arguments - operators in java - control structures -
Series and patterns - strings - immutable string - string operations - String Buffer class - StringBuilder
class - String Joiner - String Tokenizer.

1.1 Object Oriented Programming


Object-oriented programming (OOP) is the core of Java. OOP allows decomposition of a problem
into several entities called objects and then builds data and function around these objects. The data of
an object can be accessed only by the function associated with that object. However, function of one
object can access the function of other objects.
Object A Object B

DATA DATA

Communication
FUNCTION FUNCTION

Object C

DATA

FUNCTION

Organization of data and function in OOP


Basic Concepts of Object-Oriented Programming:
The basic Concepts used extensively in Object Oriented Programming are,
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
1. Objects :
An object is an instance of a class. Objects are variables of the type class and it is a real
time entity. Every object is associated with data and functions which define meaningful
operations on that object. An Object is a collection of data members and associated member
functions.
2.Classes:
Class is a collection of data members and member functions. Objects with similar
properties and methods are grouped together to form a Class. A Class is a collection of objects of
similar type. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects becomes functions of the class and is referred to as Methods. No
memory is allocated when a class is created. Memory is allocated only when an object is created.
Example:
Car Santro
Class : Car
Car Alto Attributes:
Car Etios Name
Model //data members
Year of Manufacture
Colour Engine
Power
Class Object Operations:
Start( ) // member functions
Stop( )
Accelerate( )
3. Data Abstraction:
Data Abstraction increases the power of programming language by creating user defined
data types called Abstract Data Types (ADTs). Data Abstraction also represents only the essential
features and hides the implementation details.
4. Data Encapsulation:
The wrapping up of data and functions into a single unit called class is known as
Encapsulation. When using Data Encapsulation, data is not accessed directly by the program; it
is only accessible through the functions present inside the class. Data Encapsulation enables the
important concept of data hiding or information hiding.
5. Inheritance:
Inheritance is the process of deriving the properties (data members and member
functions) of one class (base class) to another class (derived class). The base class is also known
as parent class or super class, the new class that is formed will have the combined features of
both the classes and is called as derived class. Derived class is also known as a child class or sub
class. Inheritance helps in reducing the overall code size of the program, and helps in reusability
of the code.

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)

object message information

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.

Difference Between Structured Programming and Object-Oriented Programming


S. No. Structured Programming Object Oriented Programming
1. The data and functions are considered The data and functions are considered as
as separate entities. single entities.
2. The abstraction is based on Algorithms. The abstraction is based on Classes and
Objects.
It does not support the concept of It supports the concept of inheritance,
3. inheritance, polymorphism, data polymorphism, data encapsulation.
encapsulation.
4. Example: C, COBOL C++, Java

Features of Java (Java buzz words):

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.

5. Robust (Strong/ Powerful):


Java programs will not crash because of its exception handling and its memory management
features. Java uses strong memory management. There is a lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling and type
checking mechanism in java. All these points make java robust.

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.

The Java Architecture


Java Virtual Machine acts as a run-time engine to run Java applications. JVM is the one that calls the
main method present in a java code. JVM is a part of JRE (Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java-enabled system without any
adjustment. This is all possible because of JVM.
When we compile a .java file, .class files (contains byte-code) with the same class names present in .java
file are generated by the Java compiler. This .class file goes into various steps when we run it. These
steps together describe the whole JVM.

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading
 Linking
 Initialization

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.

Linking: Performs verification, preparation, and (optionally) resolution.


 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly
formatted and generated by a valid compiler or not. If verification fails, we get run-time
exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier.
Once this activity is completed then the class file is ready for compilation.
 Preparation: JVM allocates memory for class static variables and initializing the memory to
default values.
 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.

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.

Platform JDK is platform Like of JDK JRE is JVM is platform independent.


Independence dependent i.e for also platform
3
different platforms dependent.
different JDK required.
S.
Key JDK JRE JVM
No.

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

1.3 STRUCTURE OF JAVA PROGRAMMING


The Basic Structure of a Simple Java program
A Java program consists of different sections. Some of them are mandatory but some areoptional. The
optional section can be excluded from the program depending upon the requirements of the programmer.

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.

Main Method Class Section:


Every program in Java consists of at least one class, the one that contains the main method. The
main () method which is from where the execution of program actually starts and follow the
statements in the order specified. The class section is mandatory.
First Java Program
WAP to print a message “Welcome to Java World”
class Example
{
public static void main (String args[])
{
System.out.println ("Welcome to Java World");
}
}

Output:
Welcome to Java World

How to compile the above program:


To compile the Example program, execute the compiler, javac, specifying the name of the source
file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the byte code version of the
program. As discussed earlier, the Java byte code is the intermediate representation of our
program that contains instructions the Java interpreter will execute. Thus, the output of javac is
not code that can be directly executed. To run the program, we must use the Java interpreter,
called java. To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
Welcome to Java World

Explanation of above program


public static void main(String args[])
All Java applications begin execution from main ( ) function. (This is just like C/C++.)
 The public keyword is an access specifier, which allows the programmer 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 class in which it is declared. It also tells
thecompiler to access the class.
 The keyword static is reserved keyword which means that a method is accessible and
usable even though no objects of the class exist
 The keyword void simply tells the compiler that main ( ) does not return a value.
 main ( ) is the method called when a Java application begins. Keep in mind that Java is
case-sensitive. Thus, Main is different from main.
 String args[ ] declares a parameter named args, which is an array of instances of the
class String. (Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present when
the program is executed.
System.out.println ("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by a new line on
the screen. Output is actually accomplished by the built-in println( ) method. In this
case, println( ) displays the string which is passed to it.

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)

Rules for Identifiers in Java


There are some rules and conventions for declaring the identifiers in Java. If the identifiers are not
properly declared, we may get a compile-time error. Following are some rules and conventions for
declaring identifiers:
 A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a
dollar sign ($). for example, @javatpoint is not a valid identifier because it contains a special
character which is @.
 There should not be any space in an identifier. For example, java point is an invalid identifier.
 An identifier should not contain a number at the starting. For example, 123javatpoint is an invalid
identifier.
 An identifier should be of length 4-15 letters only. However, there is no limit on its length. But
it is good to follow the standard conventions.
 We cannot use the Java reserved keywords as an identifier such as int, float, double, char, etc.
For example, int double is an invalid identifier in Java.
 An identifier should not be any query language keywords such as SELECT, FROM, COUNT,
DELETE, etc.

Java Reserved Keywords


Java reserved keywords are predefined words, which are reserved for any functionality or meaning. We
cannot use these keywords as our identifier names, such as class name or method name. These keywords
are used by the syntax of Java for some functionality. If we use a reserved word as our variable name, it
will throw an error. In Java, every reserved word has a unique meaning and functionality. Some of the
reserved keywords in Java are:
abstract continue for protected transient
assert default goto public try
boolean do if static throws
break double implements strictfp package
byte else import super private
case enum interface short switch
catch extends instanceof return void
char final int synchronized volatile
class finally long throw date
const float native this while

Example of Valid and Invalid Identifiers


Valid identifiers: Following are some examples of valid identifiers in Java:
TestVariable
testvariable
a
i
Test_Variable
_testvariable
$testvariable
sum_of_array
TESTVARIABLE
num123
NumBer12
Invalid identifiers: Below are some examples of invalid identifiers:
Test Variable ( We cannot include a space in an identifier)
123java (The identifier should not begin with numbers)
java+point (The plus (+) symbol cannot be used)
a-javatpoint (Hyphen symbol is not allowed)
java_&_Tpoint (ampersand symbol is not allowed)
Java'point (we cannot use an apostrophe symbol in an identifier)

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.7 Command Line Arguments


Java command-line argument is an argument i.e., passed at the time of running the Java program. In
Java, the command line arguments passed from the console can be received in the Java program and
they can be used as input. The users can pass the arguments during the execution bypassing the
command-line arguments inside the main() method.
When command-line arguments are supplied to JVM, JVM wraps these and supplies them to args[]. It
can be confirmed that they are wrapped up in an args array by checking the length of args using
args.length. Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass
into the main() function. We can check these arguments using args.length method. JVM stores the first
command-line argument at args[0], the second at args[1], the third at args[2], and so on.
Example
import java.util.*;
public class Main
{
public static void main(String args[])
{
int a, b, c;
String s = args[0]+args[1];
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(s);
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("Sum = "+c);
}
}
Output
3
4
34
Sum = 7

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.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x


Example
class Main
{
public static void main (String[] args)
{
int a = 10;
int b = 3;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1

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.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Example
class Main
{
public static void main(String[] args)
{
int a = 10;
int b = 3;
int c = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

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.

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! 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

1.9 Control Statements


A programming language uses control statements to control the flow of execution of a program based
on certain conditions. Java’s Selection statements:
 if
 switch-case
 jump
i) If Statements
 Simple if
 If else
 If-else-if Ladder
 Nested if

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

Example for continue


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 = 0; i < n; i++)
{
if (i % 2 == 0)
continue;
System.out.print(i + " ");
}
}
}
Output
Enter n:
20
1 3 5 7 9 11 13 15 17 19

1.10 String Class


The string is a sequence of characters. In Java, objects of String are immutable which means a constant
and cannot be changed once created. The String class has a set of built-in methods that you can use on
strings.
Method Description
charAt() Returns the character at the specified index (position)

compareTo() Compares two strings lexicographically

compareToIgnoreCase() Compares two strings lexicographically, ignoring case


differences

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

copyValueOf() Returns a String that represents the characters of the character


array

endsWith() Checks whether a string ends with the specified character(s)

equals() Compares two strings. Returns true if the strings are equal, and
false if not

equalsIgnoreCase() Compares two strings, ignoring case considerations

getChars() Copies characters from a string to an array of chars

indexOf() Returns the position of the first found occurrence of specified


characters in a string

isEmpty() Checks whether a string is empty or not

lastIndexOf() Returns the position of the last found occurrence of specified


characters in a string

length() Returns the length of a specified string

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

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

substring() Returns a new string which is the substring of a specified string

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters


toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value

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.

• StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It


constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and
suffix. If no characters are added to the StringJoiner and methods accessing the string value are
invoked, it will return the prefix + suffix (or properties thereof) in the result
unless setEmptyValue has first been called.

Method Action Performed

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.

length() Returns the length of the String representation of this StringJoiner.

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.

toString() Returns the String object of this StringJoiner


Sets the string to be used when determining the string representation of this
setEmptyValue()
StringJoiner, and no elements have been added yet; that is when it is empty

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.

Method Action Performed

countTokens() Returns the total number of tokens present

hasMoreToken() Tests if tokens are present for the StringTokenizer’s string

nextElement() Returns an Object rather than String

hasMoreElements() Returns the same value as hasMoreToken

nextToken() Returns the next token from the given StringTokenizer.

Example
import java.util.*;

public class Main

{
public static void main(String args[])

StringTokenizer st1 = new StringTokenizer("Hello How are you", " ");

while (st1.hasMoreTokens())

System.out.println(st1.nextToken());

StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");

while (st2.hasMoreTokens())

System.out.println(st2.nextToken());

StringTokenizer st3 = new StringTokenizer("JAVA : Code : String", " :", true);

while (st3.hasMoreTokens())

System.out.println(st3.nextToken());

}
Output
Output

Hello

How

are

you

JAVA

Code

String

JAVA

:
Code

String

You might also like