[go: up one dir, main page]

0% found this document useful (0 votes)
22 views97 pages

Unit1-BCA IADC

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)
22 views97 pages

Unit1-BCA IADC

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/ 97

Indian Academy Degree College

Faculty of BCA

I. Introduction to Java:Basics of Java Programming


What is Java?
● Java is a programming language and a platform.
● Java is a high level, robust, object-oriented and secure programming language.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has a runtime environment (JRE) and API, it is called a platform
independent.

Simple java example:


class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
● Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every
machine. Examples of standalone application are Media player, antivirus, etc. AWT
and Swing are used in Java for creating standalone applications.

Prepared By:Prof.Shweta Joshi Page 1


Indian Academy Degree College
Faculty of BCA

2) Web Application
● An application that runs on the server side and creates a dynamic page is called a
web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
3) Enterprise Application
● An application that is distributed in nature, such as banking applications, etc. is
called enterprise application. It has advantages of the high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
● An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions


There are 4 platforms or editions of Java:
1) Java SE (Java platform Standard Edition)
● It is a Java programming platform. It includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like
OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java platform Enterprise Edition)
● It is an enterprise platform which is mainly used to develop web and enterprise
applications. It is built on the top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java platform Micro Edition)
● It is a micro platform which is mainly used to develop mobile applications.
4) JavaFX
● It is used to develop rich internet applications. It uses a light-weight user interface
API.

OOP Concepts
(Class, Object, Encapsulation, Inheritance, Polymorphism)
● Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.

1. Object
● Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
Prepared By:Prof.Shweta Joshi Page 2
Indian Academy Degree College
Faculty of BCA

● An Object can be defined as an instance of a class. An object contains an address and


takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
● Example: A dog is an object because it has states like color, name, breed, etc. as well
as behaviors like wagging the tail, barking, eating, etc.

2. Class
● Collection of objects is called class. It is a logical entity.
● A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

3. Inheritance
● When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
4. Polymorphism
● If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle,circle etc.
● Polymorphism means that a call to a member function will cause a different function
to be executed depending on the type of object that invokes the function.
● There are two types of polymorphism compile time and run time polymorphism
● In Java, we use method overloading(compile time) and method overriding(runtime)
to achieve polymorphism.
● Method overloading means having multiple methods with same name but with
different signatures(number,type and order of parameters) in same class.
● When a subclass contains a method with the same name and signature as in the
super class then it is called as method overriding.

5. Abstraction
● Hiding internal details and showing functionality is known as abstraction. For
example we know how to drive car i.e clutch, break,..(interface of car),…etc we also
know what happens when we press the break but we don’t know how it
happened(internal mechanism called implementation)?It is abstracted from the
driver. This is called abstraction.
● Abstraction separates specification(or interface) from implementation of class.
● In Java, we use abstract class and interface to achieve abstraction.

Prepared By:Prof.Shweta Joshi Page 3


Indian Academy Degree College
Faculty of BCA

6. Encapsulation
● Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
● A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

OOP over POP


POP OOP
Divided into Smaller parts called Parts called objects
functions
Importance Given to function as well as Given to data because it
sequence of actions works as a real world
Approach Top down Bottom up
Access Specifier Does not have access Public,private,protected
specifier
Data Moving Data can move freely from Objects can move and
function to function communicate with each
other through functions
Expansion To add new data in function It is easy to add new data
is difficult and function
Data access Function uses global data Data can not move from
for sharing that can be function to function because
accessed freely of access specifier
Data hiding No proper way for data Provides data hiding sop
hiding so less secure more security
Overloading Not possible Possible in form of method
and operator
Examples C,VB,Pascal,FORTRAN C++,JAVA,C#.net,VB.net

Features of Java
A list of most important features of Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent

Prepared By:Prof.Shweta Joshi Page 4


Indian Academy Degree College
Faculty of BCA

5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
● Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because Java
syntax is based on C++ (so easier for programmers to learn it after C++).
● Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
● There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
● Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior.
● Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

Basic OOP concepts are:


1. Class:
Class is a collection of data member and member functions. It is a blueprint of object.
2. Object:
It is an instance of class. It is used for accessing property and method of class.
3. Encapsulation:
Wrapping of data member and member function is known as encapsulation.
4. Inheritance:
The process of creating a new class from the existing class is known as inheritance.
5. Abstraction:
Abstraction is a process of hiding the implementation details and showing only necessary
information to the user.

Prepared By:Prof.Shweta Joshi Page 5


Indian Academy Degree College
Faculty of BCA

6. Polymorphism:
● The process of ability to take more than one form is known as polymorphism.There
are two types of polymorphism:Compile time(Method overloading) and run
time(Method overriding,Virtual class).
Method overloading:
● Method name is same and no of arguments and types are different in same class.
Method overriding:
● Method name is same and no of arguments and types are same in different class.
7. Platform Independent
● Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in
which a program runs.
● There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
● The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms. It
has two components:
1. Runtime Environment
2. API(Application Programming Interface)
● Java code can be run on multiple platforms, for example, 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 be run on multiple platforms, i.e., Write
Once and Run Anywhere(WORA).
8. Secured
● Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.

Prepared By:Prof.Shweta Joshi Page 6


Indian Academy Degree College
Faculty of BCA

o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
o Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
9. Robust
● Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
10.Architecture-neutral
● Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
● In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
11.Portable
● Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
12.High-performance
● Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
13.Distributed
● Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of Java
makes us able to access files by calling the methods from any machine on the
internet.
14.Multi-threaded
● A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It

Prepared By:Prof.Shweta Joshi Page 7


Indian Academy Degree College
Faculty of BCA

shares a common memory area. Threads are important for multi-media, Web
applications, etc.
15.Dynamic
● Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.
● Java supports dynamic compilation and automatic memory management (garbage
collection).

C++ vs Java
● There are many differences and similarities between the C++ programming language
and Java. A list of top differences between C++ and Java are given below:

Comparison C++ Java


Index

Platform-indepe C++ is platform-dependent. Java is platform-independent.


ndent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.

Design Goal C++ was designed for systems Java was designed and created as an
and applications interpreter for printing systems but
programming. It was an later extended as a support network
extension of C programming computing. It was designed with a
language. goal of being easy to use and
accessible to a broader audience.

Goto C++ supports Java doesn't support the goto


the goto statement. statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by interfaces in java.

Prepared By:Prof.Shweta Joshi Page 8


Indian Academy Degree College
Faculty of BCA

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You Java supports pointer internally.


can write pointer program in However, you can't write the pointer
C++. program in java. It means java has
restricted pointer support in java.

Compiler and C++ uses compiler only. C++ Java uses compiler and interpreter
Interpreter is compiled and run using the both. Java source code is converted
compiler which converts into bytecode at compilation time.
source code into machine The interpreter executes this
code so, C++ is platform bytecode at runtime and produces
dependent. output. Java is interpreted that is
why it is platform independent.

Call by Value C++ supports both call by Java supports call by value only.
and Call by value and call by reference. There is no call by reference in java.
reference

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.

Documentation C++ doesn't support Java supports documentation


comment documentation comment. comment (/** ... */) to create
documentation for java source code.

Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide override all non-static methods by
whether or not override a default. In other words, non-static
function. methods are virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the top

Prepared By:Prof.Shweta Joshi Page 9


Indian Academy Degree College
Faculty of BCA

for the negative numbers. For


positive numbers, it works same like
>> operator.

Inheritance Tree C++ creates a new Java uses a single inheritance tree
inheritance tree always. always because all classes are the
child of Object class in java. The
object class is the root of
the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented Java is also


language. However, in C an object-oriented language.
language, single root However, everything (except
hierarchy is not possible. fundamental types) is an object in
Java. It is a single root hierarchy as
everything gets derived from
java.lang.Object.

C++ Example
#include <iostream>
int main() {
cout << "Hello C++ Programming";
return 0;
}

Java Example
File: Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To Compile:javac Simple.java

Prepared By:Prof.Shweta Joshi Page 10


Indian Academy Degree College
Faculty of BCA

TO run:java Simple

Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code
into byte code.

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents visibility. It means it is
visible to all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main method is executed by the JVM, so it
doesn't require to create an object to invoke the main method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class. We will
learn about the internal working of System.out.println statement later.

Valid java main method signature


1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
Prepared By:Prof.Shweta Joshi Page 11
Indian Academy Degree College
Faculty of BCA

7. final public static void main(String[] args)

Invalid java main method signature


1. public void main(String[] args)
2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract public static void main(String[] args)

Standard JDK Tools and Utilities


● Basic Tools (appletviewer, apt, extcheck, jar, java, javac, javadoc, javah, javap, jdb)
● Security Tools (keytool, jarsigner, policytool, kinit, klist, ktab)
● Internationalization Tools (native2ascii)
● Remote Method Invocation (RMI) Tools (rmic, rmiregistry, rmid, serialver)
● Java IDL and RMI-IIOP Tools (tnameserv, idlj, orbd, servertool)
● Java Deployment Tools (javafxpackager, pack200, unpack200)
● Java Web Start Tools (javaws)
● Java Troubleshooting, Profiling, Monitoring and Management Tools (jcmd,
jconsole, jmc, jvisualvm)
● Java Web Services Tools (schemagen, wsgen, wsimport, xjc)

Experimental JDK Tools and Utilities


● Monitoring Tools (jps, jstat, jstatd)
● Troubleshooting Tools (jinfo, jhat, jmap, jsadebugd, jstack)
● Scripting Tools (jrunscript)

II. History of Java


● The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television
industry at the time.
● The history of java starts with Green Team. Java team members (also known
as Green Team), initiated this project to develop a language for digital devices such
as set-top boxes, televisions, etc. However, it was suited for internet programming.
Later, Java technology was incorporated by Netscape.
● The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted and Dynamic".
● Java is used in internet programming, mobile devices, games, e-business solutions,
Prepared By:Prof.Shweta Joshi Page 12
Indian Academy Degree College
Faculty of BCA

etc.
● James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
● Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
● Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
● After that, it was called Oak and was developed as a part of the Green project.

Why Java named "Oak"?


● Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania, etc.
● In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?


● The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the
essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to
spell and fun to say.
● According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.
● Java is an island of Indonesia where first coffee was produced (called java coffee).
● Notice that Java is just a name, not an acronym.
● Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
● In 1995, Time magazine called Java one of the Ten Best Products of 1995.
● JDK 1.0 released in(January 23, 1996).

Structure of a Java program


Prepared By:Prof.Shweta Joshi Page 13
Indian Academy Degree College
Faculty of BCA

1. Documentation Section
It includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. Using comments we can write in the documentation section. The comments
may be single-line, multi-line, and documentation comments.
Example:
Single line comment: //
Multi-line Comment:/* …..*/
Documentation Comment: /** …….*/

2. Package Declaration
The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed. There can be only
one package statement in a Java program. It must be defined before any class and
interface declaration.We use the keyword package to declare the package name.
Ex.package packagename;

1. Import Statements
If we want to use any class of a particular package, we need to import that class. The
import statement represents the class stored in the other package. We use the import

Prepared By:Prof.Shweta Joshi Page 14


Indian Academy Degree College
Faculty of BCA

keyword to import the class. It is written before the class declaration and after the
package statement.
Ex. import java.util.*;
Import java.util.scanner;

4. Interface Section
It is an optional section. We can create an interface in this section if required. We use the
interface keyword to create an interface. An interface is a slightly different from the class.
It contains only constants and method declarations.
Ex.
interface runnable{
final static int a=10;
void run();
void show();
}

5. Class Definition
In this section, we define the class.Without the class, we cannot create any Java program.
We use the class keyword to define the class. It contains information about user-defined
methods, variables, and constants. Every Java program has at least one class that contains
the main() method.

6. Class Variables and Constants


In this section, we define variables and constants that are to be used later in the program.
In a Java program, the variables and constants are defined just after the class definition.
Ex.
class Demo{
int a;
void show()
{
}
}

7. Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method. In other words, it is an
entry point of the class. It must be inside the class. Inside the main method, we create
objects and call the methods.

Methods

Prepared By:Prof.Shweta Joshi Page 15


Indian Academy Degree College
Faculty of BCA

In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions execute at
runtime and perform the specified task.
Ex.
public static void main(String args[])
{
int a=10;
void show(){
System.out.println(“value of a is:”+a);
}
}

Phases of java program Development:


There are five phases needed to run the Java program.
Phase-1: Edit
When we write a Java program on any editor & save it, then it is stored in a disk with an
extension of .java. This .java file is platform-independent
Phase-2: Compile
The compiler’s work is to convert the high-level language to bytecodes then store it with an
extension of .class. To compile we use the “javac” command.The compiler checks for syntax
errors, and if everything is correct then it starts translating the .java file else it gives a
compile-time error. After compilation of the .java file, the .java file is translated to .class file.
Phase-3: Load
The class loader reads the code, compiles it, and puts those bytecodes from the disk to primary
memory. From the class loader, the codes are stored in primary memory. When we execute the
“java” command to run the Java application then the .class file (which contains bytecode) is
loaded into the RAM, and this task is done by the class loader.
Phase-4: Verify
This step confirms that the bytecodes are valid and make sure that they do not risk the Java
security restrictions.
Phase-5: Execute
In this step, the JVM (Java Virtual Machine) reads the byte and translates it to the language that
the machine can understand that is machine language then executes the program and stores it in
values in primary memory.

Prepared By:Prof.Shweta Joshi Page 16


Indian Academy Degree College
Faculty of BCA

Prepared By:Prof.Shweta Joshi Page 17


Indian Academy Degree College
Faculty of BCA

III. Java Tokens:


A token is the smallest element of a program that is meaningful to the compiler. Tokens can
be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators

1. Keyword: Keywords are pre-defined or reserved words in a programming language.


Each keyword is meant to perform a specific function in a program. Java language
supports following keywords:

abstract assert boolean


break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
to transient transitive
try uses void
volatile while with

2. Identifiers: Identifiers are used as naming of variables, functions and arrays. You
cannot use keywords as identifiers; they are reserved for special use
Prepared By:Prof.Shweta Joshi Page 18
Indian Academy Degree College
Faculty of BCA

Example of valid Identifiers:


num,Num,n1,n_1,$up,_top

Examples of invalid identifiers :


My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character

3. Constants/Literals: Constants are also like normal variables. But, the only difference
is, their values can not be modified by the program once they are defined. Constants
refer to fixed values. They are also called as literals.Constants may belong to any of the
datatype.
Syntax:
final data_type variable_name;
● For example, the number 100 is a literal. Literals are also commonly called
constants.
● Java literals can be of any of the primitive data types.
● By default, integer literals are of type int. If you want to specify a long literal, append
an l or an L.For example, 12 is an int, but 12L is a long.
● By default, floating point literals are of type double. To specify a float literal, append
an F or f to the constant. For example, 10.19F is of type float.
● Hexadecimal, Octal, and Binary Literals: In programming it is sometimes easier to
use a number system based on 8 or 16 instead of 10.The number system based on 8
is called octal, and it uses the digits 0 through 7. In octal the number 10 is the same
as 8 in decimal. The base 16 number system is called hexadecimal and uses the
digits 0 through 9 plus the letters A through F, which stand for 10, 11, 12, 13, 14, and
15.
● For A hexadecimal literal must begin with 0x or 0X (a zero followed by an x or X). An
octal literal begins with a zero.
● Here are some examples:
hex=0XFF; //255 in decimal
oct=011; //9 in decimal
● It is possible to specify an integer literal by use of binary. To do so, precede the
binary number with a 0b or 0B. For example, this specifies the value 12 in binary:
0b1100.

Prepared By:Prof.Shweta Joshi Page 19


Indian Academy Degree College
Faculty of BCA

● String Literals:
● Java supports one other type of literal: the string. A string is a set of characters
enclosed by double quotes. For example,”this is a String.”

● Special Symbols: The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
● Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
● Parentheses(): These special symbols are used to indicate function calls and
function parameters.
● Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
● comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
● semicolon : It is an operator that essentially invokes something called an
initialization list.
● asterick (*): It is used to create pointer variable.
● assignment operator: It is used to assign values.

4. Separators:
● The most commonly used separator in Java is the semicolon (;). As you have
seen, it is used to terminate the statements.
● The separators are listed in the following table :
● Symbol ● Name ● Description

Used to contain the lists of parameters in


method definition and invocation. Also used for
() Parentheses defining the precedence in expressions,
containing expressions in control statements,
and surrounding cast types.

Used to contains the values of automatically


{} Braces initialized arrays. Also used to define a block of
code, for classes, methods, and local scopes.

Used to declare array types. Also used when


[] Brackets
dereferencing array values.

Prepared By:Prof.Shweta Joshi Page 20


Indian Academy Degree College
Faculty of BCA

; Semicolon Terminates the statements

Separates consecutive identifiers in a variable


, Comma declarations. Also used to chain statements
together inside a for statement

Used to separate packages names from


. Period subpackages and classes. Also used to separate
a variable or method from a reference variable.

Used to create a method or constructor


:: Colons
reference (Added by JDK 8)

Comments in Java
In Java there are three types of comments:
1. Single – line comments.
Syntax:
//Comments here( Text in this line only is considered as comment )

2. Multi – line comments.


Syntax:
/*Comment starts
continues
continues
.
.
.
Commnent ends*/

3. Documentation comments.
Syntax:
/**Comment start
*
*tags are used in order to specify a parameter
*or method or heading
*HTML tags can also be used
*such as <h1>
*
*comment ends*/
Prepared By:Prof.Shweta Joshi Page 21
Indian Academy Degree College
Faculty of BCA

Operators in java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator
o Special Operator-instanceOf and dot(.) operator

1.Arithmetic operators:
Java defines the following arithmetic operators:

2.Increment and Decrement Operator:

Prepared By:Prof.Shweta Joshi Page 22


Indian Academy Degree College
Faculty of BCA

3.Relational Operators:

Prepared By:Prof.Shweta Joshi Page 23


Indian Academy Degree College
Faculty of BCA

4.Logical operators:

Example:
boolean p=true,q=false,r;
int a=24,b=12,c=2;
q= !p;
System.out.println("Logical unary NOT ~ Operator "+q);
r=p^q;
System.out.println("Logical XOR ^ Operator "+r);
boolean s=(p&!q)&&(r&p);
System.out.println("Logical AND && Operator "+s);
s=(a<b)||(a<c);
System.out.println("Logical OR || Operator "+s);
Output:
Logical unary NOT ~ Operator false
Logical XOR ^ Operator true
Logical AND && Operator true

Prepared By:Prof.Shweta Joshi Page 24


Indian Academy Degree College
Faculty of BCA

Logical OR || Operator false

5.Conditional operator or ternary operator:

6.Assignment Operator:

Prepared By:Prof.Shweta Joshi Page 25


Indian Academy Degree College
Faculty of BCA

7.Bitwise Operator:

Prepared By:Prof.Shweta Joshi Page 26


Indian Academy Degree College
Faculty of BCA

Example:
int i=5;
i&k =0
i|k=7
i==k;=>false
i<<3;=>40.

8.Special Operators:

Prepared By:Prof.Shweta Joshi Page 27


Indian Academy Degree College
Faculty of BCA

Java Operator Precedence

Operator Type Category Precedence

Unary Postfix expr++ expr--

Prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

Additive +-

Shift Shift << >> >>>

Relational comparison < > <= >= instanceof

Equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary Ternary ?:

Prepared By:Prof.Shweta Joshi Page 28


Indian Academy Degree College
Faculty of BCA

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

IV. Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
2. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
3. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


● In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
● Java is a statically-typed programming language. It means, all variables must be
declared before its use. That is why we need to declare variable's type and name.
● There are 8 types of primitive data types:
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Prepared By:Prof.Shweta Joshi Page 29


Indian Academy Degree College
Faculty of BCA

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Prepared By:Prof.Shweta Joshi Page 30


Indian Academy Degree College
Faculty of BCA

Boolean Data Type


● The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
● The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example: Boolean one = false

Byte Data Type


● The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
● The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20

Short Data Type


● The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.
● The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example: short s = 10000, short r = -5000

Int Data Type


● The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive).
● Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its
default value is 0.
● The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example: int a = 100000, int b = -200000

Long Data Type


● The long data type is a 64-bit two's complement integer.
● Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its
default value is 0. The long data type is used when you need a range of values more
than those provided by int.
Prepared By:Prof.Shweta Joshi Page 31
Indian Academy Degree College
Faculty of BCA

Example: long a = 100000L, long b = -200000L

Float Data Type


● The float data type is a single-precision 32-bit IEEE 754 floating point.Its value
range is unlimited.
● It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for
precise values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f

Double Data Type


● The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited.
● The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example: double d1 = 12.3

Char Data Type


● The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.
Example: char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?


● It is because java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system

Type casting:
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
● Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

● Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting
● Widening casting is done automatically when passing a smaller size type to a larger
Prepared By:Prof.Shweta Joshi Page 32
Indian Academy Degree College
Faculty of BCA

size type:
public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}}

Narrowing Casting
● Narrowing casting must be done manually by placing the type in parentheses in
front of the value:
public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}

Prepared By:Prof.Shweta Joshi Page 33


Indian Academy Degree College
Faculty of BCA

V. Variables in JAVA:
● variables are declared using this form of statement,
Syntax: datatype varname;
Example: int a;
● where type is the data type of the variable, and varname is its name
Initializing a Variable:
● One way to give a variable a value is through an assignment statement, Another way is
by giving it an initial value when it is declared. The general form of initialization is
shown here:
Syntax: datatype var = value;
● Here, value is the value that is given to var when var is created.
Example: int a=10;
● When declaring two or more variables of the same type using a comma separated list,you
can give one or more of those variables an initial value.
Example: int a,b=8,c=10,d;
Dynamic Initialization:
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.

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. Thus, each time you start a new block, you are creating a new
scope. A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
Prepared By:Prof.Shweta Joshi Page 34
Indian Academy Degree College
Faculty of BCA

● Two of the most common scopes in Java are those defined by a class and those defined
by a method. variables declared inside a scope are not visible (that is, accessible) to code
that is defined outside that scope. Thus, when you declare a variable within a scope, you
are localizing that variable and protecting it from unauthorized access and/or
modification.
● A variable declared within a block is called a local variable. variables are created when
their scope is entered, and destroyed when their scope is left. This means that a variable
will not hold its value once it has gone out of scope.

Prepared By:Prof.Shweta Joshi Page 35


Indian Academy Degree College
Faculty of BCA

How to get an input from user:


● The java.util.Scanner class is a simple text scanner which can parse primitive types and
strings using regular expressions.
● Following are the important points about Scanner − A Scanner breaks its input into
tokens using a delimiter pattern, which by default matches whitespace.
● A scanning operation may block waiting for input.
How to use Java Scanner class:
● To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class.
● For Example: Scanner in = new Scanner(System.in);
● To get the instance of Java Scanner which parses the strings, we need to pass the strings
in the constructor of Scanner class.
● For Example: Scanner in = new Scanner("Hello Java");

Methods:
Type Method Description

Prepared By:Prof.Shweta Joshi Page 36


Indian Academy Degree College
Faculty of BCA

Example:
import java.util.*;
public class ScannerDemo {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
String s = "Hello, Java.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s); //Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext()); //Print the string
System.out.println("String: " +scan.nextLine());
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
String st = "Hello/This is Java/we use scanner class.";
Scanner sc = new Scanner(st);
sc.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(sc.hasNext()){
System.out.println(sc.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +sc.delimiter());
}
}

Reading Console Input

Prepared By:Prof.Shweta Joshi Page 37


Indian Academy Degree College
Faculty of BCA

We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
● read() method is used with BufferedReader object to read characters. As this
function returns integer type value has we need to use typecasting to convert it into
char type.
Example:
class StreamDemo
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/sbj/bca/java prog/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}

VI. Decision Making in Java (if, if-else, switch, break, continue,


jump)
● In programming at some situations where we want a certain block of code to be
executed when some condition is fulfilled.
● A programming language uses control statements to control the flow of execution of
program based on certain conditions. These are used to cause the flow of execution

Prepared By:Prof.Shweta Joshi Page 38


Indian Academy Degree College
Faculty of BCA

to advance and branch based on changes to the state of a program.

Java’s Selection statements:


● if
● if-else
● nested-if
● if-else-if
● switch-case
● jump – break, continue, return

These statements allow you to control the flow of your program’s execution based upon
conditions known only during run time.
● if: if statement is the most simple decision making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example:
class IfDemo
{
public static void main(String args[])
{
int i = 10;

if (i > 15)
System.out.println("10 is less than 15");
System.out.println("I am Not in if");
}
}

if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false. Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax:
if (condition)
Prepared By:Prof.Shweta Joshi Page 39
Indian Academy Degree College
Faculty of BCA

{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
class IfElseDemo
{
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

nested-if: A nested if is an if statement that is the target of another if or else. Nested if


statements means an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
class NestedIfDemo
{
Prepared By:Prof.Shweta Joshi Page 40
Indian Academy Degree College
Faculty of BCA

public static void main(String args[])


{
int i = 10;

if (i == 10)
{
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}

if-else-if ladder: Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example:
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
Prepared By:Prof.Shweta Joshi Page 41
Indian Academy Degree College
Faculty of BCA

else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

switch-case 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:
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
Prepared By:Prof.Shweta Joshi Page 42
Indian Academy Degree College
Faculty of BCA

case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}

jump: Java supports three jump statement: break, continue and return. These three
statements transfer control to other part of the program.
1. Break: In Java, break is majorly used for:
● Terminate a sequence in a switch statement (discussed above).
● To exit a loop.
● Used as a “civilized” form of goto.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Example:
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}

Using break as a Form of goto:


● Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner.
● Java uses label. A Label is use to identifies a block of code.

Prepared By:Prof.Shweta Joshi Page 43


Indian Academy Degree College
Faculty of BCA

● Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
● break statement can be use to jump out of target block.
You cannot break to any label which is not defined for an enclosing block.
Syntax:
break label;
Example:
class BreakLabelDemo
{
public static void main(String args[])
{
boolean t = true;
first:
{
// Illegal statement here as label second is not
// introduced yet break second;
second:
{
third:
{
// Before break
System.out.println("Before the break statement");

// break will take the control out of


// second label
if (t)
break second;
System.out.println("This won't execute.");
}
System.out.println("This won't execute.");
}
System.out.println("This is after second block.");
}
Prepared By:Prof.Shweta Joshi Page 44
Indian Academy Degree College
Faculty of BCA

}}
2. Continue:
● Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body
for this particular iteration.
● This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue
statement performs such an action.
Example:
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}
3. Return:
● The return statement is used to explicitly return from a method. That is, it causes a
program control to transfer back to the caller of the method.
Example:
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement

Prepared By:Prof.Shweta Joshi Page 45


Indian Academy Degree College
Faculty of BCA

// after return
System.out.println("This won't execute.");
}
}

VII. Looping structure in java


● Sometimes it is necessary for the program to execute the statement several times,
and Java loops execute a block of commands a specified number of times until a
condition is met.
● Every programming language has the feature to instruct to do such repetitive tasks
with the help of certain form of statements. The process of repeatedly executing a
collection of statement is called looping.
● Java supports many looping features which enable programmers to develop concise
Java programs with repetitive processes which as follows:

1. While loop:
● while loop is the most basic loop in Java. It has one control condition and executes as
long the condition is true.
● The condition of the loop is tested before the body of the loop is executed; hence it is
called an entry-controlled loop.
Syntax:
while (condition)
{
statement(s);
Incrementation;
}
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
while (n <= times) {
System.out.println("Java while loops:" + n);
n++;
}
}
}
2. do-while loop:
● Java do-while loops are very similar to the while loops, but it always executes the

Prepared By:Prof.Shweta Joshi Page 46


Indian Academy Degree College
Faculty of BCA

code block at least once and furthermore as long as the condition remains true.
This loop is an exit-controlled loop.
Syntax:
do
{
statement(s);
}while( condition );
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 0;
do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}
}
3. for loop:
● Java for loops is very similar to Java while loops in that it continues to process a
block of code until a statement becomes false, and everything is defined in a single
line.
Syntax:
for ( init; condition; increment )
{
statement(s);
}
Example:
public class Sample {
public static void main(String args[]) {
int n = 1, times = 5;
for (n = 1; n <= times; n = n + 1) {
System.out.println("Java for loops:" + n);
}
}
}

4. Enhanced for loop in Java


● This is mainly used to traverse collection of elements including arrays.

Prepared By:Prof.Shweta Joshi Page 47


Indian Academy Degree College
Faculty of BCA

Syntax:
for(declaration : expression) {
// Statements
}
● Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
● Expression − This evaluates to the array you need to loop through. The expression
can be an array variable or method call that returns an array.
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

5. For-each loop in Java


For-each is another array traversing technique like for loop, while loop, do-while loop.
● It starts with the keyword for like a normal for-loop.
● Instead of declaring and initializing a loop counter variable, you declare a variable that
is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
● In the loop body, you can use the loop variable you created rather than using an
indexed array element.
● It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:
for (type var : array)
{
statements using var;
Prepared By:Prof.Shweta Joshi Page 48
Indian Academy Degree College
Faculty of BCA

}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
Example:
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
for(int i:arr)
System.out.println(i);
}}

Creating and using Class with members


● All of data or attributes and behavior of objects are defines within classes. Class is a
collection of data member and member functions. It is a blueprint of object.
Declaration:
Syntax:
class classname
{
Field declarations;
Constructor;
Method declarations;
}
● Here the class body contains all the code, constructors for initializing new objects,
declarations for the fields that provide the state of the class and its objects and
methods to implement the behavior of the class and its objects.
Example:
class employee
{
int eno;
String name;
}
● A class is a kind of factory for constructing objects. In every java program we must
have at least one class.
● The class provides the basic framework of an object so it is known as templates.

Prepared By:Prof.Shweta Joshi Page 49


Indian Academy Degree College
Faculty of BCA

● A class is description from which many objects or instances are constructed.


● A class creates a logical framework that defines the relationship between members.
● In c++ you can declare global variables outside the class but in java everything must
be included in the class.

Object creation:
● An Object contains properties and performs actions. Properties are represented by
variables and actions are performed by function which known as method.
● Objects are created and destroyed as the program runs and there can be many
objects in the same class.
● In java creating an object of a class is a two step process:
● At first we need to declare a variable of the class type. This variable does not define
an object.
● Second we must acquire an actual physical copy of object and assign it to that
variable.We can do this using new operator.
Syntax:
classname objectname;
objectname=new classname();
or
classname objectname=new classname();

● Here new operator dynamically allocates memory runtime for an object.


● () with classname specifies the default constructor for the class.java will
automatically call the default constructor.

New operator:
● It creates single instance of a class and returns a reference to that object.
● This reference is the address in memory of the object allocated by new operator.
Example:
Employee e=new Employee ();
● Here e is a reference to an instance of object. The reference is then stored in t he
variable. The variable e is a reference to the object. It does not actually contain it.

Dot operator:
● It is used to obtain the value of the instance variable.
Syntax:
Objectreference.variablename;
Example:
e.name;

Prepared By:Prof.Shweta Joshi Page 50


Indian Academy Degree College
Faculty of BCA

Difference between class and object


Class Object
It defines a model It is an instance of a class.
It declares attributes of objects. Object has state.
It declares the behavior of objects. Object has behavior.

Various Members within a class:


A class definition contains:
1. Access Modifier: Specifies the availability of the class from other classes.
2. Class Keyword: Tells compiler that following code block defines a class.
3. Instance fields: Variables and constants that are used by objects of the class.
4. Constructors: Methods used to control the initial state of any object created.
5. Instance methods: Define the functions that can act upon objects in this class.
6. Class fields: Variables and constants that belong to the class and are shared by all
objects.
7. Class Methods: It is used to control the values of class fields.

Instance Variable:
● An instance variable is a variable whose separate copy is available to each object.
● A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time.
● It gets memory at runtime when an object or instance is created. That is why it is
known as an instance variable.

Example to define a class:


Class employee
{
String name;
Int eno;
}
Class data
{
Public static void main(String args[])
{
Employee e1=new employee();
E1.name=”Happy”;
E1.no=1;
System.out.println(“Name of employee:”+e1.name);
Prepared By:Prof.Shweta Joshi Page 51
Indian Academy Degree College
Faculty of BCA

System.out.println(“id number of employee:”+e1.no);


}
}

Method in Java:
In Java, a method is like a function which is used to expose the behavior of an object.
Syntax:
Returntype functionname
{
//line1…
}
Advantage of Method
o Code Reusability
o Code Optimization
How to access a method in Java:
we have to use object name and dot(.) operator to access a method in java.
Syntax: objectname.methodname();
Example: d.show();

Method overloading:
● If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
● If we have to perform only one operation, having same name of the methods
increases the readability of the program.
● When we call a method in an object java matches up the method name first and then
the number and type of parameters to decide which one of definitions to execute.
This process is known as polymorphism.
● There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

Example:
class M{
void disp(){
System.out.println("Hello");
}
void disp(int x){

Prepared By:Prof.Shweta Joshi Page 52


Indian Academy Degree College
Faculty of BCA

System.out.println(x);
}
void disp(String s){
System.out.println(s);
}
}
class Methodoverload{
public static void main(String args[])
{
M m=new M();
m.disp();
m.disp("JAVA");
m.disp(8);
}
}

Can we overload java main() method?


● Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.
Example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Output:
Main with String[]

3 Ways to initialize object


There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor

Prepared By:Prof.Shweta Joshi Page 53


Indian Academy Degree College
Faculty of BCA

1) Object and Class Example: Initialization through reference


● Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.
Example:
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Ila";
System.out.println(s1.id+" "+s1.name);
}
}

2)Object and Class Example: Initialization through method


● In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying
the state (data) of the objects by invoking the displayInformation() method.
Example:
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){
System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();

Prepared By:Prof.Shweta Joshi Page 54


Indian Academy Degree College
Faculty of BCA

Student s2=new Student();


s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

● As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in memory.

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:
o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc.

Difference between object and class


There are many differences between object and class. A list of differences between object
and class are given below:
Prepared By:Prof.Shweta Joshi Page 55
Indian Academy Degree College
Faculty of BCA

No. Object Class

1) Object is an instance of a class. Class is a blueprint or template from


which objects are created.

2) Object is a real world entity such as Class is a group of similar objects.


pen, laptop, mobile, bed, keyboard,
mouse, chair etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new Class is declared using class


keyword mainly e.g. keyword e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per Class is declared once.


requirement.

6) Object allocates memory when it is Class doesn't allocated memory when


created. it is created.

7) There are many ways to create There is only one way to define class in
object in java such as new keyword, java using class keyword.
newInstance() method, clone()
method, factory method and
deserialization.

VII. Access Modifier/Visibility Modifier:


● Access control is the process of controlling visibility of a variable or method. There
are mainly three access modifiers:
Public:
● Least restrictive.
● Variables and methods declared as public may be seen and used by any other class.
If any access specifier is not defined then the default access specifier is worked in
any other classes of the same package.

Prepared By:Prof.Shweta Joshi Page 56


Indian Academy Degree College
Faculty of BCA

Protected:
● This access specifier gives more security and you can access data members of one
class in other subclasses.
Private:
● Most restrictive access modifier
● Private data members may not be accessed by any other classes.
● An object’s primary job is to encapsulate its data and limit manipulation. This is
achieved by declaring data as private.

Access specifiers for members of a package:


● If any member of a package has a default access specifier then that member is
accessible only inside that package.
● If any member of package has a public access specifier then that member is
accessible everywhere (outside of the package also)

Access Specifier for member of a class:


Access Access Public Protected Default Private
Location Modifier
Sameclass Yes Yes Yes Yes
Subclass in same Yes Yes Yes No
package
Other classes in Yes Yes Yes No
same package
Subclasses in other Yes Yes No No
package
Non subclasses in Yes No No No
other packages

VIII. Constructors in Java:


● In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
● It is a special type of method which is used to initialize the object.
● Every time an object is created using the new() keyword, at least one constructor is
called.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name

Prepared By:Prof.Shweta Joshi Page 57


Indian Academy Degree College
Faculty of BCA

2. A Constructor must have no explicit return type


3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Default Constructor
● A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax:
<class_name>(){}

What is the purpose of a default constructor?


● The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.
Example:
class Shape
{
int x;
Shape()
{
x=10;
}
void disp()
{
int ans=x*x;
System.out.println("Area of square is:"+ans);
}
}
class Shapedemo
{
public static void main(String args[])
{
Shape s=new Shape();
s.disp();
}
}
Prepared By:Prof.Shweta Joshi Page 58
Indian Academy Degree College
Faculty of BCA

Parameterized Constructor
● A constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized constructor?
● The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
Example:
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Constructor Overloading in Java


● In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
● Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists. They are arranged in a way that each constructor
performs a different task. They are differentiated by the compiler by the number of
parameters in the list and their types.
Example:
class Student5{
Prepared By:Prof.Shweta Joshi Page 59
Indian Academy Degree College
Faculty of BCA

int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.
Basis
Java Constructor Java Method

purpose A constructor is used to initialize the A method is used to expose the


state of an object. behavior of an object.
Return type A constructor must not have a return A method must have a return
type. type.

Prepared By:Prof.Shweta Joshi Page 60


Indian Academy Degree College
Faculty of BCA

Invocation The constructor is invoked implicitly. The method is invoked explicitly.


type
Default The Java compiler provides a default The method is not provided by
constructor if you don't have any the compiler in any case.
constructor in a class.
Name The constructor name must be same The method name may or may
as the class name. not be same as the class name.
Super Calls the constructor of the parent Calls an overridden method in
class if it is used must be in first line the parent class.
Inheritance Not inherited Are inherited
Modifiers Can’t be abstract,final,native,static or Can be
synchronized abstract,final,native,static or
synchronized

IX. Array in java:


● In Java, array is an object of a dynamically generated class.
● An array is a fixed size sequenced collection of elements of the same data type which
allocates continuous memory.
● Like C/C++, we can also create single dimentional or multidimentional arrays in
Java.
● Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.

Types of Array in java


There are two types of array.
o Single Dimensional Array
An array which has one row and multiple columns is known as a single dimensional
array.
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)

Prepared By:Prof.Shweta Joshi Page 61


Indian Academy Degree College
Faculty of BCA

dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array


int a[]={33,3,4,5};//declaration, instantiation and initialization

Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);
Prepared By:Prof.Shweta Joshi Page 62
Indian Academy Degree College
Faculty of BCA

}}

Multidimensional Array(Arrays of array)


In such case, data is stored in row and column based index (also known as matrix form)
Syntax to Declare Multidimensional Array in Java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];

Example:
class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Jagged Array or Non rectangular array in Java


● In java it is compulsory to allocate memory for the first dimension in multi
dimension arrays. In this type of array row size is fixed but no of columns for each
row are different. In other words, it is an array of arrays with different number of
columns.
Syntax:
Datatype arrayname[][]=new datatype [rowsize][];
//declaration
int arr[][] = new int[3][];

Prepared By:Prof.Shweta Joshi Page 63


Indian Academy Degree College
Faculty of BCA

Example:
class TestJaggedArray{
public static void main(String[] args){
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Command Line Argument Array
● The java command-line argument is an argument i.e. passed at the time of running
the java program.
● The arguments passed from the console can be received in the java program and it
can be used as an input.
● So, it provides a convenient way to check the behavior of the program for the
different values. To access the command-line argument inside a java program is
quite easy, they are stored as string in String array passed to the args parameter
of main() method. You can pass n numbers of arguments from the command prompt.
Example:
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java

Prepared By:Prof.Shweta Joshi Page 64


Indian Academy Degree College
Faculty of BCA

run by > java CommandLineExample deva

Example:
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A 1 3 abc

Example:
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}

X. Finalizer/Garbage Collection:
● Since objects are dynamically allocated by using the new operator, objects are
destroyed and their memory released for later reallocation.
● In some languages, such as C++,dynamically allocated objects must be manually
released by use of a delete operator.
● Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
● when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed. There is no explicit need
to destroy objects as in C++.

Prepared By:Prof.Shweta Joshi Page 65


Indian Academy Degree College
Faculty of BCA

finalize( ) Method:
● Sometimes an object will need to perform some action when it is destroyed.
● For example,if an object is holding some non-Java resource such as a file handle or
window character font, then you might want to make sure these resources are freed
before an object is destroyed. To handle such situations, Java provides a mechanism
called finalization.
● By using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
● finalize( ) method you will specify those actions that must be performed before an
object is destroyed.
● The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
● Right before an asset is freed, the Java run time calls the finalize( ) method on the
object.
● Syntax:
protected void finalize( )
{
// finalization code here
}
Example:
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");

}
protected void finalize()
{
System.out.println("finalize method called");
}
}

Prepared By:Prof.Shweta Joshi Page 66


Indian Academy Degree College
Faculty of BCA

XI. In-Built Classes:


1. Java.lang.Math Class
● The java.lang.Math class contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric
functions.
Class Declaration
Syntax:
public final class Math extends Object

Field:
Following are the fields for java.lang.Math class −
● static double E − This is the double value that is closer than any other to e, the
base of the natural logarithms.
● static double PI − This is the double value that is closer than any other to pi, the
ratio of the circumference of a circle to its diameter.

Basic Math Functions


⮚ Math.abs()
● The Math.abs() function returns the absolute value of the parameter passed to it.
● The absolute value is the positive value of the parameter.
● If the parameter value is negative, the negative sign is removed and the positive
value corresponding to the negative value without sign is returned.
● Examples:
int abs1 = Math.abs(10); // abs1 = 10
int abs2 = Math.abs(-20); // abs2 = 20
● The Math.abs() method is overloaded in 4 versions:
o Math.abs(int)
o Math.abs(long)
o Math.abs(float)
o Math.abs(double)
⮚ Math.ceil()
● The Math.ceil() function rounds a floating point value up to the nearest integer
value. The rounded value is returned as a double.
● Example:
double ceil = Math.ceil(7.343); // ceil = 8.0

Prepared By:Prof.Shweta Joshi Page 67


Indian Academy Degree College
Faculty of BCA

⮚ Math.floor()
● The Math.floor() function rounds a floating point value down to the nearest integer
value.
● The rounded value is returned as a double.
● Example:
double floor = Math.floor(7.343); // floor = 7.0
⮚ Math.min()
● The Math.min() method returns the smallest of two values passed to it as parameter
● Example:
int min = Math.min(10, 20);
⮚ Math.max()
● The Math.max() method returns the largest of two values passed to it as parameter.
● Example:
int max = Math.max(10, 20);
⮚ Math.round()
● The Math.round() method rounds a float or double to the nearest integer using
normal math round rules (either up or down).
● Example:
double roundedDown = Math.round(23.445);
double roundedUp = Math.round(23.545);
● After executing these two Java statements the roundedDown variable will contain
the value 23.0 , and the roundedUp variable will contain the value 24.0.
⮚ Math.random()
● The Math.random() method returns a random floating point number between 0 and
1. Of course the number is not fully random, but the result of some calculation which
is supposed to make it as unpredictable as possible.
● Example:
double random = Math.random();

Exponential and Logarithmic Math Functions


⮚ Math.exp()
● The Math.exp() function returns e (Euler's number) raised to the power of the value
provided as parameter.

Prepared By:Prof.Shweta Joshi Page 68


Indian Academy Degree College
Faculty of BCA

● Example:
double exp1 = Math.exp(1);
System.out.println("exp1 = " + exp1);
double exp2 = Math.exp(2);
System.out.println("exp2 = " + exp2);
Output:
exp1 = 2.718281828459045
exp2 = 7.38905609893065
⮚ Math.log()
● The Math.log() method provides the logarithm of the given parameter. The base for
the logarithm is i (Euler's number). Thus, Math.log() provides the reverse function
of Math.exp().
● Example:
double log1 = Math.log(1);
System.out.println("log1 = " + log1);
double log10 = Math.log(10);
System.out.println("log10 = " + log10);
output:
log1 = 0.0
log10 = 2.302585092994046
⮚ Math.log10()
● The Math.log10 method works like the Math.log() method except is uses 10 as is
base for calculating the logarithm instead of e (Euler's Number).
● Example:
double log10_1 = Math.log10(1);
System.out.println("log10_1 = " + log10_1);
double log10_100 = Math.log10(100);
System.out.println("log10_100 = " + log10_100);
Output:
log10_1 = 0.0
log10_100 = 2.0
⮚ Math.pow()
● The Math.pow() function takes two parameters. The method returns the value of the
first parameter raised to the power of the second parameter.
● Example:
double pow2 = Math.pow(2,2);

Prepared By:Prof.Shweta Joshi Page 69


Indian Academy Degree College
Faculty of BCA

System.out.println("pow2 = " + pow2);


double pow8 = Math.pow(2,8);
System.out.println("pow8 = " + pow8);
Output:
pow2 = 4.0
pow8 = 256.0
⮚ Math.sqrt()
● The Math.sqrt() method calculates the square root of the parameter given to it.
● Example:
double sqrt4 = Math.sqrt(4);
System.out.println("sqrt4 = " + sqrt4);
double sqrt9 = Math.sqrt(9);
System.out.println("sqrt9 = " + sqrt9);
Output:
sqrt4 = 2.0
sqrt9 = 3.0

Trigonometric Math Functions


⮚ Math.PI
● The Math.PI constant is a double with a value that is very close to the value of PI -
the mathematical definition of PI.
⮚ Math.sin()
● The Math.sin() method calculates the sine value of some angle value in radians.
● Example:
double sin = Math.sin(Math.PI);
System.out.println("sin = " + sin);
Output:
Sin=1.224646…..
⮚ Math.cos()
● The Math.cos() method calculates the cosine value of some angle value in radians.
● Example:
double cos = Math.cos(Math.PI);
System.out.println("cos = " + cos);
Output:
cos=1.224646…..

Prepared By:Prof.Shweta Joshi Page 70


Indian Academy Degree College
Faculty of BCA

⮚ Math.tan()
● The Math.tan() method calculates the tangens value of some angle value in radians.
● Example:
double tan = Math.tan(Math.PI);
System.out.println("tan = " + tan);
Output:
tan=-1.224646…..
⮚ Math.asin()
● The Math.asin() method calculates the arc sine value of a value between 1 and 1.
● Example:
double asin = Math.asin(1.0);
System.out.println("asin = " + asin);
Output:
asin=1.570796…..
⮚ Math.acos()
● The Math.acos() method calculates the arc cosine value of a value between 1 and -1.
● Example:
double acos = Math.acos(1.0);
System.out.println("acos = " + acos);
Output:
acos=0.0
⮚ Math.atan()
● The Math.atan() method calculates the arc tangens value of a value between 1 and
-1.
● Example:
double atan = Math.atan(1.0);
System.out.println("atan = " + atan);
Output:
atan=0.78539816….
⮚ Math.toRadians()
● The Math.toRadians() method converts an angle in degrees to radians.
● Example:
double radians = Math.toRadians(180);
System.out.println("radians = " + radians);

Prepared By:Prof.Shweta Joshi Page 71


Indian Academy Degree College
Faculty of BCA

Output:
radians=3.141….
⮚ Math.toDegrees()
● The Math.toDegrees() method converts an angle in radians to degrees.
● Example:
double degrees = Math.toDegrees(Math.PI);
System.out.println("degrees = " + degrees);
Output:
degrees=180

2. Java.lang.String Class
● The java.lang.String class represents character strings. All string literals in Java
programs, such as "abc", are implemented as instances of this class.
● Strings are constant, their values cannot be changed after they are created. That is
called immutable.
Class Declaration
Syntax:
public final class String extends Object implements Serializable, Comparable<String>,
CharSequence

● By the help of these methods, we can perform operations on string such as


trimming, concatenating, converting, comparing, replacing strings etc.

What is String in java


● Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a
string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword

1. String Literal
● Java String literal is created by using double quotes.
● Example:
String s="welcome";
● Each time you create a string literal, the JVM checks the "string constant pool" first.
Prepared By:Prof.Shweta Joshi Page 72
Indian Academy Degree College
Faculty of BCA

If the string already exists in the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string instance is created and placed in
the pool.
● Example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

● String objects are stored in a special memory area known as the "string constant
pool"
Why Java uses the concept of String literal?
● To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

2. By new keyword
● Example:
String s=new String("Welcome");//creates two objects and one reference variable
● In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s
will refer to the object in a heap (non-pool).
Example:
public class StringMethodsDemo {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " +
targetString.charAt(2));

Prepared By:Prof.Shweta Joshi Page 73


Indian Academy Degree College
Faculty of BCA

System.out.println("After Concat: "+ targetString.concat("-Enjoy-"));


System.out.println("Checking equals ignoring case: "
+s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ targetString.substring(8));
System.out.println("SubString of targetString: "+ targetString.substring(8,
12));
System.out.println("Converting to lower case: "+
targetString.toLowerCase());
System.out.println("Converting to upper case: "+
targetString.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " +
targetString.contains(s1));
System.out.println("searching s2 in targetString: " +
targetString.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}}

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

Constructor Description

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

Prepared By:Prof.Shweta Joshi Page 74


Indian Academy Degree College
Faculty of BCA

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int creates an empty string buffer with the specified capacity as


capacity) length.

Methods:

Modifier and Method Description


Type

public append(String is used to append the specified string with this


synchronized s) string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, is used to insert the specified string with this string
synchronized String s) at the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float),
insert(int, double) etc.

public replace(int is used to replace the string from specified


synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex, String
str)

public delete(int is used to delete the string from specified


synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

Prepared By:Prof.Shweta Joshi Page 75


Indian Academy Degree College
Faculty of BCA

public char charAt(int is used to return the character at the specified


index) position.

public int length() is used to return the length of the string i.e. total
number of characters.

public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex. and endIndex.
endIndex)

Example:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is " + sbLength);
System.out.println("Capacity of " + sb + " is " + sbCapacity);
sb.append("World ");
System.out.println(sb);
sb.insert(5, " ");
sb.insert(sb.length(), 2017);
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(sb.delete(5,11));
StringBuffer sb2 = new StringBuffer("Hello World!");
System.out.println(sb2.deleteCharAt(11));
System.out.println(sb.replace(6,11,"Earth"));
}
}

4. Java.lang.StringBuilder Class:
● Java StringBuilder class is used to create mutable (modifiable) string.

Prepared By:Prof.Shweta Joshi Page 76


Indian Academy Degree College
Faculty of BCA

● The Java StringBuilder class is same as StringBuffer class except that it is non
synchronized. which means it is not thread safe. Its because StringBuilder methods
are not synchronised.

Difference between String and StringBuffer


● There are many differences between String and StringBuffer. A list of differences
between String and StringBuffer are given below:
No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory StringBuffer is fast and consumes
when you concat too many strings because less memory when you concat
every time it creates new instance. strings.

3) String class overrides the equals() method StringBuffer class doesn't override
of Object class. So you can compare the the equals() method of Object
contents of two strings by equals() method. class.

Difference between StringBuffer and StringBuilder:


● Java provides three classes to represent a sequence of characters: String, StringBuffer,
and StringBuilder. The String class is an immutable class whereas StringBuffer and

Prepared By:Prof.Shweta Joshi Page 77


Indian Academy Degree College
Faculty of BCA

StringBuilder classes are mutable. There are many differences between StringBuffer and
StringBuilder.

5. Character Class in Java:


● Java provides a wrapper class Character in java.lang package. An object of type
Character contains a single field, whose type is char. The Character class offers a number
of useful class (i.e., static) methods for manipulating characters. You can create a
Character object with the Character constructor.
Creating a Character object:
Character ch = new Character('a');
The methods of Character class are as follows:
1. boolean isLetter(char ch): This method is used to determine whether the specified char
value(ch) is a letter or not. The method will return true if it is letter([A-Z],[a-z]), otherwise return
false. In place of character, we can also pass ASCII value as an argument as char to int is
implicitly typecasted in java.
Syntax:
boolean isLetter(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is an alphabet, otherwise, return false

Prepared By:Prof.Shweta Joshi Page 78


Indian Academy Degree College
Faculty of BCA

2. boolean isDigit(char ch): This method is used to determine whether the specified char
value(ch) is a digit or not. Here also we can pass ASCII value as an argument.
It returns true if ch is a digit, otherwise, return false.

3.toString(char ch): It returns a String class object representing the specified character
value(ch) i.e a one-character string. Here we cannot pass ASCII value.

Syntax:
String toString(char ch)
Parameters:
ch – a primitive character
Returns: It returns a String object.

4.boolean isUpperCase(char ch): It determines whether the specified char value(ch) is


uppercase or not.
Syntax:
boolean isUpperCase(char ch)
Parameters:
ch – a primitive character
Returns: It returns true if ch is upper case, otherwise, returns false.

5. compareTo():
The compareTo(character another character) method of character class is used to compare two
objects numerically.
Syntax:
public int compareTo(CharcteranotherCharcter )
Parameter:
The above method requires only one parameter:
The character that need to be compared.
The value 0 if the given Character is equal to the argument Character.
A value less than 0 if the given Character is numerically less than the Character argument
A value greater than the given Character is numerically greater than the Character argument.

Example:
Character firstVal = new Character('g');

Prepared By:Prof.Shweta Joshi Page 79


Indian Academy Degree College
Faculty of BCA

Character secondVal = new Character('G');


// compare the first character to the second character.
intcompare1= firstVal.compareTo(secondVal);
if (compare1 == 0) {
System.out.println("The first value 'g' and the second value 'G' are equal.");
}
else if (compare1>0) {
System.out.println("The first value 'g' is greater than the second value 'G'.");
}
else {
System.out.println("The first value 'g' is less than the second value'G'.");
}

6. Java File Class:


● The File class is an abstract representation of file and directory pathname. A pathname
can be either absolute or relative.
● The File class have several methods for working with directories and files such as
creating new directories or files, deleting and renaming directories or files, listing the
contents of a directory etc.
Fields

Modifie Type Field Description


r

static String pathSeparator It is system-dependent path-separator character,


represented as a string for convenience.

static char pathSeparatorChar It is system-dependent path-separator character.

static String separator It is system-dependent default name-separator


character, represented as a string for convenience.

static char separatorChar It is system-dependent default name-separator


character.

Prepared By:Prof.Shweta Joshi Page 80


Indian Academy Degree College
Faculty of BCA

Constructors

Constructor Description

File(File parent, String It creates a new File instance from a parent abstract pathname and
child) a child pathname string.

File(String pathname) It creates a new File instance by converting the given pathname
string into an abstract pathname.

File(String parent, String It creates a new File instance from a parent pathname string and a
child) child pathname string.

File(URI uri) It creates a new File instance by converting the given file: URI into
an abstract pathname.

Methods

Modifie Method Description


r and
Type

static File createTempFile(String It creates an empty file in the default temporary-file


prefix, String suffix) directory, using the given prefix and suffix to generate
its name.

boolean createNewFile() It atomically creates a new, empty file named by this


abstract pathname if and only if a file with this name
does not yet exist.

boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]

boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.

Prepared By:Prof.Shweta Joshi Page 81


Indian Academy Degree College
Faculty of BCA

boolean canRead() It tests whether the application can read the file denoted
by this abstract pathname.

boolean isAbsolute() It tests whether this abstract pathname is absolute.

boolean isDirectory() It tests whether the file denoted by this abstract


pathname is a directory.

boolean isFile() It tests whether the file denoted by this abstract


pathname is a normal file.

String getName() It returns the name of the file or directory denoted by


this abstract pathname.

String getParent() It returns the pathname string of this abstract pathname's


parent, or null if this pathname does not name a parent
directory.

Path toPath() It returns a java.nio.file.Path object constructed from the


this abstract path.

URI toURI() It constructs a file: URI that represents this abstract


pathname.

File[] listFiles() It returns an array of abstract pathnames denoting the


files in the directory denoted by this abstract pathname

long getFreeSpace() It returns the number of unallocated bytes in the


partition named by this abstract path name.

String[] list(FilenameFilter It returns an array of strings naming the files and


filter) directories in the directory denoted by this abstract
pathname that satisfy the specified filter.

boolean mkdir() It creates the directory named by this abstract pathname.

Example 1
import java.io.*;
Prepared By:Prof.Shweta Joshi Page 82
Indian Academy Degree College
Faculty of BCA

public class FileDemo {


public static void main(String[] args) {
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

XII. this keyword in java:


● There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
● The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
Example:
class student
{
int rollno,marks;

Prepared By:Prof.Shweta Joshi Page 83


Indian Academy Degree College
Faculty of BCA

String name;
student(int rollno,String name,int marks)
{
this.rollno=rollno;
this.name=name;
this.marks=marks;
}
void show()
{

System.out.println("Rollno:"+rollno+"\nName:"+name+"\nMarks:"+marks);
}
}
class Thisdemo2
{
public static void main(String args[])
{
student s=new student(1,"Aarshvi",50);
s.show();
}
}
2. this can be used to invoke current class method (implicitly)
● You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
Example:
class A{
void m()
{
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
//m();//same as this.m()
Prepared By:Prof.Shweta Joshi Page 84
Indian Academy Degree College
Faculty of BCA

this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}
}
3. this() can be used to invoke current class constructor.
● The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
● Call to this() must be the first statement in constructor.

Example1:
Calling default constructor from parameterized constructor:
class A{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}
}
Example2:
Calling parameterized constructor from default constructor:
Prepared By:Prof.Shweta Joshi Page 85
Indian Academy Degree College
Faculty of BCA

class A{
A()
{
this(5);
System.out.println("hello a");
}
A(int x)
{
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[])
{
A a=new A();
}
}
4.this can be passed as an argument in the method call.
● The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling.

Example:
class S2{
void m(S2 obj)
{
System.out.println("method is invoked");
}
void p()
{
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
Prepared By:Prof.Shweta Joshi Page 86
Indian Academy Degree College
Faculty of BCA

}
5.this can be passed as argument in the constructor call.
● We can pass the this keyword in the constructor also. It is useful if we have to use
one object in multiple classes.
Example:
class B{
A4 obj;
B(A4 obj)
{
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

6.this can be used to return the current class instance from the method.
● We can return this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive).
Syntax:
return_type method_name(){
return this;
}
Example:
Prepared By:Prof.Shweta Joshi Page 87
Indian Academy Degree College
Faculty of BCA

class A{
A getA()
{
return this;
}
void msg()
{
System.out.println("Hello java");
}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Notes:

Static and non static members


● The static keyword in Java is used for memory management mainly. We can apply
java static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class than an instance of the class.
● The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

static variable
o If you declare any variable as static, it is known as a static variable. The static
variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name
of students, etc.

Prepared By:Prof.Shweta Joshi Page 88


Indian Academy Degree College
Faculty of BCA

o The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
● It makes your program memory efficient (i.e., it saves memory).
Example:
class Student{
int rollno;//instance variable
String name;
static String college ="DSTC";//static variable
Student(int r, String n){
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(1,"Kia");
Student s2 = new Student(2,"ria");
s1.display();
s2.display();
}
}

static method
● If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
Syntax:
static returntype functionname{
Prepared By:Prof.Shweta Joshi Page 89
Indian Academy Degree College
Faculty of BCA

///……..
}
Example:
class static1
{
int st=30;
static void show()
{
System.out.println("Hello static keyword is used");
System.out.println("st="+st);
}

}
class Staticdemo
{
public static void main(String args[])
{
int a=10;
int b=20;
int c=2;
System.out.println("a="+a+"\nb="+b+"\nc="+c);
static1.show();
st=b+c;
System.out.println("The value of st is:"+st);
}
}
● There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
Example:
class A{
int a=40;
public static void main(String args[]){
System.out.println(a); //gives an error
Prepared By:Prof.Shweta Joshi Page 90
Indian Academy Degree College
Faculty of BCA

}
}

Why is the Java main method static?


● It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the
problem of extra memory allocation.

static block
● Is used to initialize the static data member.
● It is executed before the main method at the time of classloading
Example:
class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}

Can we execute a program without main() method?


● No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK
1.7, it is not possible to execute a java class without the main method.

Difference table:
Topic static Non static

Definition A static method is a method that Every methods in java are


belongs to a class, but its not non-static method, but the
belongs to an instance of that methods must not
class and this method can be have static keyword before
called without the instance or method
object of that class. name. non-static methods can
access any static method

Prepared By:Prof.Shweta Joshi Page 91


Indian Academy Degree College
Faculty of BCA

and static variable also,


without using the object of the
class.

Accessing In static method, the method can In non-static method, the


members only access only static data method can access static data
and members and static methods of members and static methods as
methods another class or same class but well as non-static members
cannot access non-static methods and method of another class or
and variables. same class.

Binding Static method uses compile time Non-static method uses


process or early binding. runtime or dynamic binding.

Overriding Static method cannot be Non-static method can be


overridden because of early overridden because of runtime
binding. binding.

Memory In static method, less memory is In non-static method, much


allocation use for execution because memory is used for execution
memory allocation happens only because here memory
once, because the static keyword allocation happens when the
fixed a particular memory for method is invoked and the
that method in ram. . memory is allocated every time
when the method is called.

Static variable can access with Non-static variable can access


class reference. with object reference.
Accessing Syntax Syntax
variable class_name.variable_name obj_ref.variable_name

JVM
● JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist.
● It is a specification that provides a runtime environment in which Java byte code can
be executed. It can also run those programs which are written in other languages
and compiled to Java byte code.

Prepared By:Prof.Shweta Joshi Page 92


Indian Academy Degree College
Faculty of BCA

● JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent.
● There are three notions of the JVM:
specification, implementation, and instance.
1. A specification: where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2.An implementation: Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance: Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
● The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
● It contains class loader, memory area, execution engine etc.

Prepared By:Prof.Shweta Joshi Page 93


Indian Academy Degree College
Faculty of BCA

JRE:
● JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
● The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment.
● It is the implementation of JVM. It physically exists.
● It contains a set of libraries + other files that JVM uses at runtime. The
implementation of JVM is also actively released by other companies besides Sun
Micro Systems.

Prepared By:Prof.Shweta Joshi Page 94


Indian Academy Degree College
Faculty of BCA

JDK :
● JDK is an acronym for Java Development Kit.
● The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets. It contains JRE + development tools.
● JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
● The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.

Prepared By:Prof.Shweta Joshi Page 95


Indian Academy Degree College
Faculty of BCA

Difference between JDK and JRE


JDK JRE
JDK is an acronym for Java Development JRE is an acronym for Java Runtime
Kit . Environment
It is a bundle of software components that It is an implementation of the Java Virtual
is used to develop Java based applications machine, which actually executes Java
includes JRE , and the compilers and tools programs. It includes the JVM (Java Virtual
(like JavaDoc, and Java Debugger) to create machine), core libraries and other
and compile programs. additional components to run applications
JDK = JRE + Development/debugging tools and applets written in Java.
The JDK is a superset of the JRE , and The JRE does not contain tools and utilities
contains everything that is in the JRE, plus such as compilers or debuggers for
tools such as the compilers and debuggers developing applets and applications.
necessary for developing applets and
applications.
if you are planning to do some Java when you only care about running Java
development , you need JDK . programs on your browser or computer
you need only JRE

Java has a feature that Write Once and Run anywhere explain.
● One of the initial "killer feature" of Java was supposed to be the write once, run
anywhere nature of it.

Prepared By:Prof.Shweta Joshi Page 96


Indian Academy Degree College
Faculty of BCA

● Earlier, it is not practically possible to have different versions of an application for


different devices because the devices have variety of CPUs, operating system and
browsers. The same code must work on all the computers, therefore we need a
portable code .
● Portability refers to the ability to run a program on different machines. "Java is
portable" , means that you can run Java byte code on any hardware that has a
compliant JVM (Java Virtual Machine).
● The Java Compiler compiles a java program (.java file) and converts it into class files
(.class) that contain byte codes , which is the intermediate language between source
code and machine code .
● These byte codes are not platform specific, so with the help of JVM (Java virtual
machine), the java program can run on wide variety of platforms. The JVM (Java
virtual machine) is platform dependent i.e. its implementation differs from platform
to platform (like windows, Linux atc.), but these all JVMs can execute the same
java byte code .
● This is something which can be termed as 'write once and run anywhere'

What is JIT compiler?


● The Just-In-Time (JIT) compiler is a component of the JRE (Java Runtime
Environment) that improves the performance of Java applications at run time.
● It helps improve the performance of Java programs by compiling bytecodes into
native machine code at runtime.

Prepared By:Prof.Shweta Joshi Page 97

You might also like