SlideShare a Scribd company logo
1 of 110
Download to read offline
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 1
By: Manish Swarnkar
9887474850
Java Training Module
c
(A Software Development Company and Training Center)
Contact Information:
Contact No: +91-8947920041,
9829761399
Email: info@aimstutorial.com
info@integrationedutech.com
Website: www.aimstutorial.com
www.integrationedutech.com
Address
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan)
302020
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 2
By: Manish Swarnkar
9887474850
Java
 Java is an object oriented programming language originally developed by Sun Micro
System and released in 1995.
 Java was originally by James Gosling at Sun Microsystems (which has since merge in
Oracle Corporation).
 Java programs are platform independent which means they can be run on any operating
system.
 Java codes that run on one platform does not need to recompile to run on another
platform, it’s called “write once run anywhere”.
Java Features
1. Object Oriented
Java is an object oriented programming language which follows the concepts of oop’s.
2. Platform Independent
Java application programs written on one operating system can be able to run on any
platform. So the java is platform independent.
On compilation java program is compiled into byte code (.class file). This byte code is
platform independent and can be run on any machine, in addition to this bytecode format
also provide security. Any machine with Java Runtime Environment can run java
programs.
3. Simple
Java syntax is similar to c and c++ and it follow the oop’s concepts so it is easy to learn.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 3
By: Manish Swarnkar
9887474850
4. Secure
Java’s securing feature it enable to develop virus free, tamper free (software which is not
modify by attacker). Authentication techniques are based on public key encryption
Note: A cryptographic system that uses two keys -- a public key known to everyone
and a private or secret key known only to the recipient of the message. When John
wants to send a secure message to Jane, he uses Jane's public key to encrypt the
message. Jane then uses her private key to decrypt it.
 Class loader- It adds security by separation by separating the package for the
classes of the local file system from those that are imported from network sources.
 Byte code verifiers-It checks the code fragments for illegal code that can violate
access right to objects.
 Security Manager- It determines what resources a class can access such as
reading and writing to the local disk.
 High Performance- Compilation of program to an architecture independent
machine like language, result in a small efficient interpreter of java programs. The
java environment also complies the java byte code into native machine code at
runtime.
5. Architectural Neutral
Java compiler generates an architectural neutral object file format which makes the
compiler code to be executed on many processors, with the presence of java runtime
system.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for
both 32 and 64 bit architectures.
6. Portable
We may carry the java byte code to any platform.
7. Robust
Robust simply means strong. Java uses strong memory management. There is lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points make
java robust.
8. 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 shares a common
memory area. Threads are important for multi-media, Web applications etc.
9. Interpreted
Java is a compiled programming language, but rather than compile straight to executable
machine code, it compiles to an intermediate binary form called JVM byte code. The byte
code is then compiled and/or interpreted to run the program.
10. High Performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 4
By: Manish Swarnkar
9887474850
11. Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine on
the internet.
12. Dynamic
Java is considered more dynamic than c and c++. In java the application can be create
more dynamic.
Types of java Application
1. Web Application
Java is used to create server side applications. Currently , servelet, jsp, struts, jsf etc
technology are used.
2. Stand- Alone Application
It is also known as desktop application or window based application. An application
that we need to install on every machine such as antivirus, media player etc. AWT and
Swing is used in java for creating standalone application.
3. Enterprise Application
An application that is distributed in nature, such as banking application etc. In java
EJB is used to create enterprise application.
4. Mobile application
Java is used to create application software for mobile devices. Currently
java ME is used for creating application for small devices and java is programming for
Google Android application development.
Different Editions of java Technology
1. Java SE
Java SE or Java Standard Edition provides tools and API’s that can use to create
server application, desktop application and even applets. These programs developed
using java SE can be run on almost every popular operating system include Linux,
Macintosh, Solaris, and Windows.
2. JEE
Based on the foundation framework of the standard edition, java Enterprise Edition
helps in web application service, component model and enterprise class service
oriented architecture.
3. JME
Java Micro Edition or JME is use for the development of software for devices like
mobile phones, PDA’s, TV set-top box, game programming.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 5
By: Manish Swarnkar
9887474850
C++ v/s Java
Comparison C++ Java
Platform-
independent
C++ is platform-dependent. Java is platform-independent.
Mainly used for
C++ is mainly used for system
programming.
Java is mainly used for application
programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Goto C++ supports goto statement. Java doesn't support goto statement.
Multiple
inheritance
C++ supports multiple
inheritance.
Java doesn't support multiple inheritance
through class. It can be achieved by
interfaces in java.
Operator
Overloading
C++ supports operator
overloading.
Java doesn't support operator
overloading.
Pointers
C++ supports pointers. You
can write pointer program in
C++.
you can't write the pointer program in
java. It means java has restricted pointer
support in java.
Compiler and
Interpreter
C++ uses compiler only. Java uses compiler and interpreter both.
Call by Value and
Call by reference
C++ supports both call by
value and call by reference.
Java supports call by value only. There is
no call by reference in java.
Structure and
Union
C++ supports structures and
unions.
Java doesn't support structures and
unions.
Thread Support
C++ doesn't have built-in
support for threads. It relies
on third-party libraries for
thread support.
Java has built-in thread support.
Documentation
comment
C++ doesn't support
documentation comment.
Java supports documentation comment
(/** ... */) to create documentation for
java source code.
Virtual Keyword
C++ supports virtual keyword
so that we can decide whether
or not override a function.
Java has no virtual keyword. We can
override all non-static methods by
default. In other words, non-static
methods are virtual by default.
unsigned right
shift >>>
C++ doesn't support >>>
operator.
Java supports unsigned right shift >>>
operator that fills zero at the top for the
negative numbers. For positive numbers,
it works same like >> operator.
Inheritance Tree
C++ creates a new inheritance
tree always.
Java uses single inheritance tree always
because all classes are the child of Object
class in java. Object class is the root of
inheritance tree in java.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 6
By: Manish Swarnkar
9887474850
Java oop’s Concepts or java oop’s paradigm
 Object Oriented Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.
 The programming paradigm where everything is represented as an object is known as
truly object-oriented programming language.

OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming
is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Abstraction
 Encapsulation
 Polymorphism
Class
 It is similar to structures in C language. Class can also be defined as user defined data
type but it also contains functions in it. So, class is basically a blueprint for object.
 A class enclosed both the data and function that operate on the data, into a single unit.
The variable and function enclosed in a class are called member and member functions
respectively. Member functions define the permission operation on the data member of a
class.
data
Data 1
Data2
Data3
fun()1
fun()2
fun(3)
function
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 7
By: Manish Swarnkar
9887474850
Object
 Objects are the basic unit of OOP. They are instances of class, which have data
members and use various member functions to perform tasks.
 Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be more
than one instance of a class. Each instance of a class can hold its own relevant data.
Inheritance
 Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class. The new class that is
formed is called derived class. Derived class is also known as a child class or sub class.
Inheritance helps in reducing the overall code size of the program, which is an
important concept in object-oriented programming.
 Inheritance is a way to reuse once written code again and again. The derived class can
use all the functions which are defined in base class, hence making code reusable.
Animal
Mammal Reptile
Elephant Tiger Crocodile
Data1
Data2
Fun1
Fun2
Data
Function
Obj
2
Obj
1
Data
function
Data
function
Obj
3
Data
function
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 8
By: Manish Swarnkar
9887474850
Data Abstraction
 Abstraction refers to showing only the essential features of the application and hiding
the details. In C++, classes provide methods to the outside world to access & use the
data variables, but the variables are hidden from direct access.
 Data abstraction allows a program to ignore the details of how a data type is
represented. Abstraction (derived from a Latin word , meaning away from and ,
meaning to draw) refers to the act of representing essential features without including
the background details or explanations.
 While classifying a class, both data members and member functions are expressed in
the code. But, while using an object (that is an instance of a class) the built in data
types and the members in the class get ignored which is known as data abstraction.
Data Encapsulation
 Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
 It can also be said data binding. Encapsulation is all about binding the data variables
and functions together in class.
 C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can contain
private, protected and public members. By default, all items defined in a class are
private.
Polymorphism
 The term Polymorphism get derived from the Greek word where ‘poly’+ ‘morphos’
where ‘poly’ means many and ‘morphos’ means forms.
 Polymorphism makes the code more readable. It is a feature, which lets is create
functions with same name but different.
 The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
Shap
Draw()
Box obj
Draw(Box)
Triangle obj
Draw(Triangle)
Circle obj
Draw(Circle)
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 9
By: Manish Swarnkar
9887474850
Setting Path for Java
Java is freely available on the oracle website Download the latest version of JDK(java
Development Kit)on your machine. Install JDK on your machine. Once you have installed
java on your machine it need to set environment variable to point to correct installation
directory.
An environment variable is a dynamic “object ” on a computer that stores a value (like a key
value ), which can be reference by one or more software programs in Windows. Like in java ,
we will set environment variable with name ”java” and its values will be the path of /bin
directory present variable which will give it the path to the execution.
Step: 1 Right click on My Computer icon and select properties.
Step: 2 Go to Advance Setting Tab
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 10
By: Manish Swarnkar
9887474850
Step: 3 Click on Environment Variable Button
Step:4 Now alter the path variable so that it also contains the path to jdk installed
directory.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 11
By: Manish Swarnkar
9887474850
First java Program
public class FirstJava
{
public static void main(String[] args)
{
System.out.println("Welcome in Aims");
}
}
 class: class is a keyword is used to declare classes in java
 public: It is an access specifiers . Public means this function is visible to all.
 static: static is used to make a function static. To execute a static function you
do not have to create an Object of the class. The main () method here is called
by jvm, without creating any object for class.
 void: void is return type, meaning this function will not return anything.
 main(): main() method is the most important method in a java program . this
is the method which is executed hence all logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
 System.out.println(): This is used to print anything on the consol like
printf()in c.
Steps to compile and Run FirstJava Program
Step: 1 Open a text editor like Notepad and write the code as above.
Step: 2 save the file as FirstJava.java
Step: 3Open command prompt and go to the directory where you saved your first java
program
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 12
By: Manish Swarnkar
9887474850
Step: 4 Type javac FirstJava.java then enter to compile the program
Step: 5 Now Type java FirstJava on command prompt the enter to run program.
Step: 6 Now you will be able to see Welcome in Aims oriented on your command
prompt.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 13
By: Manish Swarnkar
9887474850
Java Development Kit (JDK)
JDK is an acronym for Java Development Kit.
It physically exists. It contains JRE + the complete set of class file for all the java technology
package, which include basic language classes.GUI components classes, an advanced
collection API, and so no.
Java Virtual Machine (JVM)
It is an abstract machine or imaginary machine that is implemented by emulating it in
software on a real machine. Code for JVM is stored in .class file. It is a specification that
provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM specification provides concrete definition for the implementation of the following:
an instruction set (equivalent to that of a center processing machine [CPU]), a register set,
the class file format, a runtime stack, a garbage-collector heap a memory area etc.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM Internal Architecture
It contains
1. Class loader: class loader loads all classes needed for the execution of a program. The class
loader adds security.
2. Memory area
1. Class (Method) Area: Class (Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
2. Heap: It is the runtime data area in which objects are allocated.
3. Stack: It holds local variables and partial results, and plays a part in method invocation and
return.
4. Program counter Registers: PC (program counter) register. It contains the address of the
Java virtual machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.
3. Execution engine
It contains
1. A virtual processor
2. Interpreter: Read byte code stream the execute the instruction
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 14
By: Manish Swarnkar
9887474850
Java Runtime Environment (JRE)
It is used to provide runtime environment. It is the implementation of JVM. It physically
exists. It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs is also actively released by other companies besides Sun Micro
Systems.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 15
By: Manish Swarnkar
9887474850
Difference between JRE and JDK
Sr.
no
JRE JDK
1 JRE is an implementation of the java
Virtual Machine which actually
executes java program
JDk is bundle of software that is used to
develop java base application
2 Java Runtime Environment is a plug-
in needed for running java programs
Java Development Kit is needed for
developing java application
3 JRE include the JVM, core libraries
And other additional component to run
application and applets written in java
JDk include the JRE, set of API classes, java
complier and additional files needed to write
java applets and applications.
Byte Code:
When the java program compile the source code is converted in intermediate code with
extension .class called, Byte Code which is read by the JVM machine.
 Byte code and JVM both makes java platform independent.
Just-In-Time (JIT) Compiler
In some Java technology runtime environments a portion of verified byte code is
compiled to native machine code by the JIT(Just-In-Time compiler)and execute directly
on the hardware platform. This compiler is called Just-IN-Time Complier. It enables the java
software code to run close to the speed of C or C++ with small delay at load time to enable
the code to be compiled to the native machine code.
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Introduction of java
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 16
By: Manish Swarnkar
9887474850
Byte Code Verifier
Java software code passes several tasks before running on your machine. The JVM puts the
code through byte code verifiers that tests the format of code fragments and check code for
illegal code, called byte code verifiers. It provides securities for java programs.
Garbage Collection
It provides a system-level thread that tracks each memory allocation. During idle cycles in
the JVM, the garbage collection threads checks for and free any memory that can freed.
Garbage collection happens automatically during the life time of a java technology program,
eliminating the need to deal locate memory and avoiding memory leak.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 17
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
Tokens
 Each and every smallest individual unit in a program is known as tokens.
 Tokens are the basic buildings blocks in language which are constructed together to
write a program.
 The keywords, identifiers, constants, string literals, and operators are examples
of tokens. Punctuation characters such as brackets [ ], braces { }, parentheses ( ), and
commas (,) are also tokens.
1.Keywords
 Keywords are those words whose meaning is already defined by language
 There are 50 Keywords in java.
 Keywords are also called as reserved words.
 const and goto are two keywords which are reserved in java but not defined by
java language.
abstract continue goto package switch
assert default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extern int short try
catch final interface static void
char finally long stricfp volatile
class float native super while
const for new synchronized
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 18
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
2.Identifiers
Identifiers are the name given to various programming element like variable name, class
name, object name array name, function name interface name, package name.
Rules for constructing identifier name
 All the identifiers must start with either a letter (a to z or A to z) or currency
character ($) or an underscore.
 They can have alphabets, digits, and the underscore (_) and dollar sign ($)
characters.
 They must not begin with a digit.
 After first character, an identifier can have any combination of character.
 A java keyword cannot use as an identifiers.
 Identifiers in java are case sensitive abc and ABC are two different identifiers.
Uppercase and lowercase are distinct.
Java developers have followed some naming conventions.
1. When more than one word are used in a public methods and instance
name, the second and subsequent words are marked with a leading
letters.
Examples:
dayTemperature
firstDayOfMonth
totalMarks
2. All private and local variable use only lowercase letters combine with
underscores.
Examples:
length
batch_strength
3. All classes and interface start with uppercase letter(and each subsequent
word with a leading uppercase)
Example:
Student
HelloJava
Vehical
MotorCycle
4. Variables that represent constant values use all uppercase letter and
underscore between words.
Example:
TOTAL
F_MAX
PRINCIPAL_AMOUNT
5. Package name should be in lowercase
Example:
java, lang, sql, util, etc.
6. Method name should be in lowercase letters.
Example:
print (), println().
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 19
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
3.Constants or Literals
 Constants or Literals are the fixes values which are not change during the execution of
the programs.
 Literals are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in a variable.
 Constants or Literals are declare using final keywords
There are five major types of literals.
1. Integer literals
Integers are any numeric values either positive or negative without having
fractional part.
Integer datatype consists of the following primitive data types:
byte, int, short, long can be expressed in decimal(base 10),
hexadecimal(base 16) or octal(base 8) number system.
Example:
final int decimal=100;
final int octal=0144;
final int hexa=0x64;
2. Floating literals
 Floats are the numeric values either negative or positive having
fractional parts.
 Java has two types of floating point numbers: float and double.
 By default floating point literals is double
 We can define the floating point literals by appending F or f suffix
after the values.
Example:
final float pi=3.14f;
3. Character literals
A Character literals is a single character in a pair of single quote such as ‘a’,
‘#’
Char datatypes is a single 16-bit Unicode character.
Example:
final char ch=’A’;
final char ch=’u0041’;
final char ch=’t’;
final char ch=’u0009’;
Escape Sequence Characters
Escape Character Meaning
n New line
t Tab
b Backspace
r Carriage return
f Form feed
 backslash
’ single quote
”” double quotation marks
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 20
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
4. String literals
The set of characters represented as String literals. It is use “double
quotes”.
final String ch="Aims";
5. Boolean literals
The values true and false are treated as literals in java. When we assign a
value to a boolean variable is true or false.
final boolean bool=true;
4.Operator
Operator is the special symbols the perform the mathematical and logical manipulation.
Types of operator
1. Arithmetic operator
Operators which are used for arithmetical operation (+, -, *, /, and %) called
arithmetic operator.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
2. Relational operator
Operators are used to test the relation between two values called relational operator.
All relational operators are binary operators and therefore require two operands. A
relational expression returns false when the relation is false and a true when it is
true.
Relational Operators Meaning
< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
! = Not equal to
public class RelationalOperatorsDemo
{ public static void main(String args[])
{
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 21
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
3. Logical operator
Operators which are used to combine one or more relational expression called logical
operator.
Operators Meaning operation
|| OR a||b is true
&& AND a&&b is false
! NOT (!a) is false
public class LogicalOperatorsDemo
{
public static void main(String args[]) {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
}
4. Bitwise operator
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in java are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ One ‘Complement
>> Bitwise right shift
<< Bitwise left Shift
Truth Table of Bitwise operator
x y x|y x&y x^y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 22
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
public class BitwiseOperatorsDemo
{
public static void main(String args[])
{
int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1
int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int z; System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
}
}
5. Ternary operator
Operator that performs operation on three operands called ternary operator.
Conditional Operator
 The conditional operator ? : is called ternary operator as it requires three
operands.
Syntax:
Conditional Exp? Exp1: Exp2
If the value of conditional expression is true then the exp1 is evaluated, otherwise exp2 is
evaluated.
public class TernaryOperatorsDemo
{
public static void main(String args[]) {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
}
6. Assignment operator
Operator ('=') which is used for assigning a value to a variable is called assignment
operator. This operator takes the expression on its right-hand-side and places it into
the variable on its left-hand-side.
For example: m = 5;
Operator Example Equivalent to
+ = A + = 2 A = A + 2
- = A - = 2 A = A - 2
% = A % = 2 A = A % 2
/= A/ = 2 A = A / 2
*= A * = 2 A = A * 2
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 23
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
7. Increment or decrement operator
Operator which perform operation only on one operand are called Unary operator.
1. Increment Operator
++ Operator increment the value of a variable by 1 is called increment operator.
 Pre-increment
++ is written before variable name. Value is incremented first then
incremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=++a;
System.out.println(i);
}
}OUTPUT: 6
Post-increment
 ++ is written after variable name. Value is assigned to expression after that the
value is increment.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a++;
System.out.println(i);
}
}OUTPUT:5
2. Decrement Operator
-- Operator decrement the value of a variable by 1 is called decrement operator.
 Pre-decrement
-- is written before variable name. Value is decremented first then
decremented value is used in expression.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=--a;
System.out.println(i);
}
}OUTPUT: 4
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 24
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Tokens
 Post-decrement
-- is written after variable name. Value is assigned in expression then the
decrement the value.
Ex:
public class IncPre
{
public static void main(String args[]) {
int i, a=5;
i=a--;
System.out.println(i);
}
}OUTPUT:5
5.Separator
The separators define the structure of a program. The separators are used parentheses (
), braces { }, the period (.) and (;) semicolon.
Comments
Comments are special part of the program, to describe or explain the code which make
easy to understand.
Comments are those lines which are not read by the compilers.
Types of Comments
1. Single line comments
Single line comments starts with two forward slash (//)
It useful when only single lines are commented.
final int a=5// a is constants variable
2. Multiline comments
Multiline comments are starts with forward slash/ and after that star (*) and
the text or comment line put then again star(*) put the again forward slash(/)
put to comment .
It is useful when we comment multiple line in program.
3. Document comment
/** document comment*/
This is document comment it described the author and other information
about a program. The JDK javadoc tool uses doc comment for
automatically generated documentation.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 25
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Data Types
Data Types:
Data type are the keyword which assign a type to a variable.
There are two data types available in Java
 Primitive Data Types
 Reference/Object Data Types
Primitive Data Types
Eight Primitive datatypes are predefined by the java.
byte
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50
short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000
int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 26
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Data Types
float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f
double
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values, generally
the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4
boolean
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true
char
 char data type is a single 16-bit Unicode character
 Minimum value is 'u0000' (or 0)
 Maximum value is 'uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'
Reference Datatypes
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 27
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Class
Class
“Class is a user defined data types, which holds variables and , which can be accessed and
used by creating instance of that class.”
Class is just a blue print, which declare and defined variables and methods. All objects
of this class will share these data member and function.
About Class:
1. Class name start with an uppercase letter. If class name is made then one word, the
first letter of each word must be in uppercase.
Ex:- Class Study, class AimsTutorial
2. Objects of the class holds separate copies of data member. We can create as many
objects of a class as we need.
How to declare class:
Syntax:
public class Class_Name
{
variables;
methods( );
public static void main(String[] args)
{
Class_Name obj=new Class_Name()
}
};
Example:
public class Aims
{
int i=10;
public static void main(String[] args)
{
Aims a1=new Aims();
System.out.println(a1.i);
}
}
Output: 10;
Objects
Objects are the variable which declare using class name, it holds the data variable, declared in
the class and the member function works on these class objects.
How to declare objects:
public class Abc
{
int x=10;
void display( )
{
System.out.println(x);
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 28
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Class
public static void main(String[] args)
{
Abc obj=new Abc();
Obj.display();
}
}
Output:10
 Each object has different data variables.
 Object are initialized using special methods are called constructor.
A class can contain any of the following variable types.
 Local variables − Variables which defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the method
and the variable will be destroyed when the method has completed.
class Test
{
public static void main(String[] args)
{
int a=10; Local variables
int b=20;
System.out.println(a+b);
}
}
 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
class Test
{
int a=10;
int b=20;
void add()
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 29
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Array
 Static variable or Class variables − Class variables are variables declared within a
class, outside any method, with the static keyword.
class Test
{
static int b=20;
public static void main(String[] args)
{
System.out.println(b);//20
}
}
Arrays:-
1) Array is a final class inheritance is not possible.
2) Arrays are used to store the multiple numbers of elements of single type.
3) The length of the array is established at the time of array creation. After creation the length
is fixed.
Root structure:-
java.lang.Object
+--java.lang.reflect.Array
public final class Array extends Object
single dimensional array declaration:-
int[] a;
int []a;
int a[];
declaration & instantiation & initialization :-
approach 1:- int a[]={10,20,30,40};
approach 2:- int[] a=new int[100];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;
10 20 30 40 50 60 70 80 90
Ex:-printing the array elements
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 30
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Array
Ex:-printing the array elements by using for loop
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
declaration of two dimensional array:-
int[][] a;
int [][]a;
int a[][];
int []a[];
Ex:-
class Test
{
public static void main(String[] args)
{
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
}
Methods (behaviors):-
1) Methods are used to provide the business logic of the project.
2) The methods like a functions in C-language called functions, in java language is called
methods.
3) Inside the class it is possible to declare any number of methods based on the developer
requirement.
4) As a software developer while writing method we have to fallow the coding standards like
the method name starts with lower case letters if the method contains two words every inner
word also starts uppercase letter.
5) It will improve the reusability of the code. By using methods we can optimize the code.
Syntax:-
[modifiers-list] return-Type Method-name (parameter-list)throws Exception
Ex:-
public void m1()
public void m2(int a, int b)
Method Signature:-
The name of the method and parameter list is called Method Signature. Return type and
modifiers list not part of a method signature.
Ex:- m1(int a,int b)------Method Signature
m2();------------------Method signature
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 31
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Array
There are two types of methods:-
 Instance method
Method which are declare and defined inside a class and without static keyword and
called using object.
class Test
{
void display()
{
System.out.println("Aims Tutorial");
}
public static void main(String[] args)
{
Test t=new Test();
t.display();
}
}
 Static method
Method which are declare and defined inside a class and with static keyword and
called using classname.
class Test
{
Static void display()
{
System.out.println("Aims Tutorial");
}
public static void main(String[] args)
{
Test.display();
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 32
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Constructor
Heap memory Stack memory
1) It is used to store the objects 1) It is used to store the function calls and
local variables.
2) We are getting outOfMemoryError 2) If the there is no memory in the stack to
store method calls or local variables the JVM
will throw the StackOverflowError.
3) Having more memory compared with the
stack memory.
4) Heap memory is also known as public
memory. This is applicable all the objects.
This memory is shared by all threads.
5)the objects are created in the heap memory
with the help of new operator
3) Stack memory is very less memory when
compared with the heap memory
4) Stack memory also known as private
memory. This is applicable only for owners.
5) Destroy when the method is completed.
Jvm is creating stack memory
Constructor
Constructor is a special type of method which has same as class that is used to initialize the
object. Constructor is called at the time of object creation. It constructs the value or provides
data for the object that is why it is known as constructor.
Rules for creating constructor
1. Constructor name must be same as its class name.
2. Constructor must have no return type.
Types of constructor
1. Default constructor.
A Constructor that have no parameter is known as default constructor.
Purpose of default constructor
 Default constructor provide the default value to the object 0,null etc depending on the
type.
class Bike
{
public static void main(String args[])
{
Bike b=new Bike();
}
Bike()
{
System.out.println(“Default constructor is created”);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 33
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Constructor
2. Parameterized constructor.
A Constructor that has parameter is known as parameterized constructor.
 Why use parameterized Constructor
 parameterized constructor provide the different values to the distinct object
class Square
{
public static void main(String args[])
{
Square b=new Square (5);
}
Square(int n)
{
System.out.println(n*n);
}
}
this heyword:-
This keyword is used to represent
1. Current class variables.
2. Current class methods.
3. Current class constructors.
class Test
{
int a=10;
int b=20;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
}
public static void main(String[] args)
{
Test t=new Test();
t.add(100,200);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 34
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
INHERITANCE
Inheritance is the capability of acquire property(variables) and behaviors(methods)
of another class is called inheritance.
1. The main purpose of the inheritance is code extensibility whenever we are extending
automatically the code is reused.
2. In inheritance one class giving the properties and behavior and another class is taking the
properties and behavior.
3. Inheritance is also known as is-a relationship means two classes are belongs to the same
hierarchy.
4. By using extends keyword we are achieving inheritance concept.
5. In the inheritance the person who is giving the properties is called parent the person who
is taking the properties is called child.
6. To reduce length of the code and redundancy of the code sun peoples introducing
inheritance concept.
Types of Inheritance
1. Single Inheritance
In this inheritance one derived class inherits from only one base class. It is the simplest
form of inheritance.
A
Base class
B
Derived class
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 35
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
2. Multiple Inheritance
In this type of inheritance a single derived class inherits from two or more than two base
classes.
3. Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which is turn inherits
from some other class. The super class for one is sub class for another class.
A
Base class
B
Base class
C
Derived class
B
Derived class
A
Base class
C
Derived class
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 36
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
4. Hierarchical Inheritance
In this type of inheritance multiple derived classes are inherits from a single base class.
5. Hybrid Inheritance
Hybrid inheritance is combination of multiple and multilevel inheritance. Two or more
type of inheritance are used to design called Hybrid inheritance.
A
Derived class
B
Derived class
C
Base class
B
Derived class
C
Derived class
A
Base class
D
Derived class
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 37
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
1. Single Inheritance
public class Shap
{
int width;
int height;
void setdata(int w, int h)
{
width=w;
height=h;
}
}
class Rectangle extends Shap
{
int getArea()
{
return(width*height);
}
public static void main(String[] args)
{
Rectangle Rect;
Rect.setdata(5,7);
System.out.prinln(“Total Area="+Rect.getArea());
}
2. Multilevel
publc class Student
{
int rollno;
void read(int rollno)
{
this.rollno=rollno;
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 38
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
class Marks extends Student
{
int m1, m2, m3;
void getMarks(int m1,int m2,int m3)
{
this.m1=m1;
this.m2=m2;
this.m3=m3;
}
}
class Result extends Marks
{
int total;
void process()
{
total=m1+m2+m3;
}
void print()
{
System.out.prinln(“Total result="+total);
}
public static void main(String[] args)
{
Result R;
R.read();
R.getMarks();
R.process();
R.print();
}
}
Output: Enter RollNo=234
Enter Marks in Sub1=20
Enter Marks in Sub2=30
Enter Marks in Sub3=40
Total result=90
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 39
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Inheritance
3. Hierarchal
public class Shap
{
int width;
int height;
void setdata(int w, int h)
{
width=w;
height=h;
}
}
public class Rectangle extends Shap
{
int getArea()
{
return width*height;
}
}
public class Triangle extends Shap
{
int getArea()
{
return (width*height)/2;
}
public static void main(String[] args)
{
Rectangle rect;
Triangle tri;
rect.setdata(5,7);
tri.setdata(5,8);
System.out.println(“Area of Rectangle="+rect.getArea());
System.out.prinln(“Area of Triangle="+tri.getArea());
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 40
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Polymorphism
POLYMORPHISM
1) One thing can exhibits more than one form called polymorphism.
2) The ability to appear in more forms.
3) Polymorphism is a Greek word poly means many and morphism means forms.
Types of Polymorphism
1. Compile Time Polymorphism (Early binding, Static binding)
2. Run Time Polymorphism (Late binding, Dynamic binding)
Ex:-Method Overloading Ex:-Method Overriding
A. Method overloading ( Compile Time Polymorphism ,Early binding, Static binding)
 If any class has multiple method with same name but different parameters then they
are said to be overloaded.
 Function overloading allows to use the same name for different function to
performed either same or different action in the same class.
 Method overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of
arguments, then you can simply overload the method There are two types of
method overloading in java
1. By Changing number of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(int a, int b, int c)
{
System.out.prinln(a+b+c);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2,3,4);
}
}
2. By having different types of arguments
Class Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void add(float a, float b)
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 41
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Polymorphism
{
System.out.prinln(a+b);
}
public static void main(String args[])
{
Cal C1=new Cal();
C1.add(2,4);
C1.add(2.5f,3.4f);
}
}
B. Constructor overloading
 Just like Method constructor can be overloaded.
 We can define multiple constructors with different parameters to overload.
Class Cal
{
void Cal(int a, int b)
{
System.out.prinln(a+b);
}
void Cal(int a, int b, int c)
{
System.out.prinln(a+b+c);
}
public static void main(String args[])
{
Cal C1=new Cal(2,3);
Cal C2=new Cal(3,4,5);
}
}
B. Method Overriding
 If we inherit a class into the derived class and provide a definition for one of the
base class’s method again. The method is said to be overriding.
 Requirement for method overriding
 Inheritance should be there. method overriding cannot be done within a class, for
this we require a derived class and a base class.
 method signature should be same in base class and derived class.
class Base
{
void show()
{
System.out.prinln(“Base Class”+”t");
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 42
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Polymorphism
class Derived extends Base
{
void show()
{
System.out.prinln("Derived Class");
}
public static void main(String[]args)
{
Base B=new Base();
Derived D=new Derived();
B.show();
D.show();
}
}
Output:
Base Class
Derived Class
 In the above example, we are calling the overridden function using Base Class and Derived
Class object. Base class object call base class version of function and derived class’s object
call Derived class version of function.
Difference between method overloading and method overriding in java
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
No. Method Overloading Method Overriding
1)
Method overloading is used to increase the readability of
the program.
Method overriding is used to provide
the specific implementation of the
method that is already provided by its
super class.
2) Method overloading is performed within class.
Method overriding occurs in two classes
that have IS-A (inheritance)
relationship.
3)
In case of method overloading, parameter must be
different.
In case of method overriding,
parameter must be same.
4)
Method overloading is the example of compile time
polymorphism.
Method overriding is the example of
run time polymorphism.
5)
In java, method overloading can't be performed by
changing return type of the method only. Return type
can be same or different in method overloading. But you
must have to change the parameter.
Return type must be same or covariant
in method overriding.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 43
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Abstraction
ABSTRACTION
Hiding the internal implementation details and highlighting the essential functionality to the
user this mechanism is called abstraction.
Ex:
a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of services
like withdraw, money transfer, mobile registration).
b. Mobile phones (The mobile persons are hiding the internal circuit implementation and
highlighting touch screen).
Abstraction concepts are implemented in java by abstract class and interface
1. Abstract Class
Abstract class is a java class which contains at least one abstract method.
To specify the particular class is abstract and particular method is abstract method by
using abstract modifier.
For the abstract classes it is not possible to create an object. Because it contains the
unimplemented methods.
For any class if we don’t want instantiation then we have to declare that class as abstract
i.e., for abstract classes instantiation (creation of object) is not possible.
abstract class Test
{
abstract void m3();
}
Abstract class:-
class Test
{
abstract void m1();
abstract void m2();
abstract void m3();
}
abstract class Add
{
abstract void add(int a, int b);
}
class Cal extends Add
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 44
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Abstraction
Abstract methods:-
The method which is having declaration but not implementations such type of methods are
called abstract Method. Hence every abstract method should end with “;”.
The child classes are responsible to provide implementation for parent class abstract
methods.
public abstract Add
{
abstract void add(int a, int b);//it is abstract method which has no definition
}
class Cal
{
void add(int a, int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Cal C1=new Cal();
C1.add(3,4);
}
}
2. Interface
1. Interface is also one of the type of class it contains only abstract methods.
2. For the interfaces also .class files will be generated.
3. Each and every interface by default abstract hence it is not possible to create an
object.
4. Interfaces not alternative for abstract class it is extension for abstract classes.
5. 100 % pure abstract class is called interface.
6. The Interface contains only abstract methods means unimplemented methods.
7. Interfaces giving the information about the functionalities it are not giving the
information about internal implementation.
8. To provide implementation for abstract methods we have to take separate class that
class we can called it as implementation class for that interface.
9. Interface can be implemented by using implements keyword.
10. For the interfaces also the inheritance concept is applicable.
Syntax:-
Interface interface-name
Ex:- interface it1
Note: -
if we are declaring or not By default interface methods are public abstract
interface it1 abstract interface it1
{ {
Void m1(); Both are same public abstract void m1();
Void m2(); public abstract void m2();
} }
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 45
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Abstraction
interface Cal
{
void add(int a, int b);
void sub(int a, int b);
}
class Solution implements Cal
{
void add(int a, int b)
{
System.out.prinln(a+b);
}
void sub(int a, int b)
{
System.out.prinln(a-b);
}
public static void main(String[] args)
{
Solution S1=new Solution()’
S1.add();
S1.sub();
}
}
Adaptor class:-
It is a intermefdiate class between the interface and user defined class. And it contains empty
implementation of interface methods.
Limitation of interface advantage of adaptor classes
interface it
{
void m1();
void m2();
;
;
void m100()
}
Class Test implements it
{
Must provide implementation of 100 methods otherwise compiler raise compilation
error
}
interface it
{
void m1();
void m2();
;
;
void m100() ;
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 46
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Abstraction
class Adaptor implements it
{
void m1()
{
}
void m2()
{
}
;
;
void m100()
{
}
};
class Test implements it
{
must provide the 100 methods implementation
};
class Test extends Adaptor
{
provide the implementation of required methods.
};
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 47
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Encapsulation
Encapsulation
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapsulations by taking the private data(variables) members.
To get and set the values from private members use getters and setters to set the data and to
get the data.
Ex:-
class Encapsulation
{
private int sid;
private int sname;
public void setSid(int x)
{
this.sid=sid;
}
public int getSid()
{
return sid;
}
public void setSname(String sname)
{
this.sname=sname;
}
public String getSname()
{
return sname;
}
}
To access encapsulated use fallowing code:-
class Test
{
public static void main(String[] args)
{
Encapsulation e=new Encapsulation();
e.setSid(100);
e.setSname("ratan");
int num=e.getSid();
String name=e.getSname();
System.out.println(num);
System.out.println(name);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 48
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Super key-word
Super Key-word
Super:- Super keyword is used to represent
1) Call the Super class variable.
2) Call the super class constructor.
3) Call the super class methods.
Super keyword is not required
class Parent
{
int a=10;
int b=20;
}
class Child extends Parent
{
int x=100;
int y=200;
void add(int i,int j)
{
System.out.println(i+j);
System.out.println(x+y);
System.out.println(a+b);
}
public static void main(String[] args)
{
Child c=new Child();
c.add(1000,2000);
}
}
Super keyword is required
class Test1
{
int a=10;
int b=20;
};
class Test extends Test1
{
int a=100;
int b=200;
void add(int a,int b)
{
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b);
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 49
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Super key-word
public static void main(String[] args)
{
Test t=new Test();
t.add(1000,2000);
}
}
Command Line Arguments:-
The arguments which are passed from command prompt is called command line arguments.
We are passing command line arguments at the time program execution.
Ex1:-
class Test
{
public static void main(String[] args)
{
System.out.println(args.length);
System.out.println(args[0]);
System.out.println(args[1]);
}
}
Compilation : Javac Test.java
Execution : java Test a b c //a,b,c are the command line arguments
Output : 3
a
b
Modifiers
Modifiers are the keyword which define the accessibility or scope of a variable , class method
in the program.
1. Public
 This is the modifier applicable for classes, methods and variables (only for
instance and static variables but not for local variables).
 If a class is declared with public modifier then we can access that class from
anywhere (within the package and outside of the package).
 If we declare a member(variable) as a public then we can access that member
from anywhere but Corresponding class should be visible i.e., before checking
member visibility we have to check class visibility.
Ex:-
public class Test // public class can access anywhere
{
public int a=10; //public variable can access any where
public void m1() //public method can access any where
{
System.out.println("public method access in any package");
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 50
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Modifiers
public static void main(String[] args)
{
Test t=new Test();
t.m1();
System.out.println(t.a);
}
}
2. Default:-
 This is the modifier applicable for classes, methods and variables (only for
instance and static variables but not for local variables).
 If a class is declared with <default> modifier then we can access that class only
within that current package but not from outside of the package.
 Default access also known as a package level access.
 The default modifier in the java language is default.
class Test
{
void m1()
{
System.out.println("m1-method");
}
void m2()
{
System.out.println("m2-method");
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
t.m2();
}
}
in the above program we are not providing any modifier for the methods and classes
at that situation the default modifier is available for methods and classes that is default
modifier. Hence we can access that methods and class with in the package.
3. Private:-
 Private is a modifier applicable for methods and variables. If a member
declared as private then we can access that member only from within the
current class.
 If a method declare as a private we can access that method only within the
class. it is not possible to call even in the child classes also.
class Test
{
private void m1()
{
System.out.println("we can access this method only with in this class");
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 51
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Modifiers
public static void main(String[] args)
{
Test t=new Test();
t.m1();
}
}
4. Protected :-
 If a member declared as protected then we can access that member with in the
current package anywhere but outside package only in child classes.
 But from outside package we can access protected members only by using
child reference. If we try to use parent reference we will get compile time error.
 Members can be accesses only from instance area directly i.e., from static area
we can’t access instance members directly otherwise we will get compile time
error.
Ex:-demonstrate the user defined packages and imports.
Aims project source file:-
package calculator;
public class Cal
{
protected void add(int a, int b)
{
System.out.println(a+b);
}
protected void sub(int a, int b)
{
System.out.println(a-b);
}
protected void multi(int a, int b)
{
System.out.println(a*b);
}
}
import calculator.Cal;
public class Solution extends Cal
{
public static void main(String[] args)
{
Solution S1=new Solution();
S1.add(3,4);
S1.sub(3,2);
S1.multi(3,5);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 52
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
String
1) String is a final class it is present in java.lang package.
2) String is nothing but a group of characters or character array.
3) Once we are creating String object it is not possible to do the modifications on existing
object called immutability nature.
Constructors of string class:-
1) String str=new String(java.lang.String);
This constructor takes the String as a argument.
Ex:-
String str=new String(“Aims”);
System.out.println(str);//Aims
2) Stirng str=new String(char[]);
This constructor take the array of characters as a argument.
Ex:-
char[] ch={'a','b','c','d'};
String str1=new String(ch);
System.out.println(str1); //abcd
3) String str=new String(char[] ,int ,int );
This contractor takes the array of characters with starting index and ending index. First int
represent the starting position Second int represent the ending position.
Ex:-
char[] ch={'a','b','c','d'};
String str1=new String(ch,1,3);
System.out.println(str1);//bcd
Ex:-
class Test
{
public static void main(String[] args)
{
String str="Manish";
System.out.println(str); //Manish
String str1=new String("Manish");
System.out.println(str1); //Manish
String str2=new String(str1);
System.out.println(str2);
char[] ch={'a','i','m','s'};
String str3=new String(ch);
System.out.println(str3); //aims
char[] ch1={'t','u','t','o','r','i','a',’l’};
String str4=new String(ch1,1,5);
System.out.println(str4); //utorial
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 53
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
String is immutability nature:-
Once we are creating string object it is not possible to do the modifications on the existing
object is called immutability nature.
public class Test
{
public static void main(String[] args)
{
String str1=new String("Aims");
str1.concat("Tutorial”);
System.out.println(str1);
}
}
OUTPUT: Aims
String class Methods
Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 String concat(String str) concatenates specified string
4 int indexOf(int ch) returns specified char value index
5 String toLowerCase() returns string in lowercase.
6 String toUpperCase() returns string in uppercase.
7 String trim() removes beginning and ending spaces of this string.
8 static String valueOf(int value) converts given type into string. It is overloaded.
String charAt()
The java string charAt() method returns a char value at the given index number. The
index number starts from 0
public class CharAtExample
{
public static void main(String args[])
{
String name="AimsTutorial";
char ch=name.charAt(4); //returns the char value at the 4th index
System.out.println(ch);
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 54
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
}
}
String length()
The java string length() method length of the string. It returns count of total number of characters.
The length of java string is same as the unicode units of the string.
public class LengthExample
{
public static void main(String args[])
{
String s1="java";
String s2="python";
System.out.println("string length is: "+s1.length());
//10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());
//6 is the length of python string
}
}
String concat()
The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.
public class ConcatExample
{
public static void main(String args[])
{
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}
}
String indexOf()
The java string indexOf() method returns index of given character value or substring. If it is
not found, it returns -1. The index counter starts from zero.
public class IndexOfExample
{
public static void main(String args[])
{
int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4);//3
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 55
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
String toLowerCase()
The java string toLowerCase() method returns the string in lowercase letter. In other
words, it converts all characters of the string into lower case letter.
public class StringLowerExample
{
public static void main(String args[])
{
String s1="AMIS TUTORIAL";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
String toUpperCase
The java string toUpperCase() method returns the string in uppercase letter. In other
words, it converts all characters of the string into upper case letter.
public class StringUpperExample
{
public static void main(String args[])
{
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
String trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is 'u0020'. The trim() method in java string checks this unicode value before
and after the string, if it exists then removes the spaces and returns the omitted string.
public class StringTrimExample
{
public static void main(String args[])
{
String s1=" hello student ";
System.out.println(s1+"welcome");//without trim()
System.out.println(s1.trim()+"in aims");//with trim()
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 56
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
StringBuffer
1. String Buffer is a class present in the java.lang package.
2. StringBuffer is a final class so it can’t be inherited.
3. StringBuffer is a mutable class so it is possible to change the content in the same location.
4. StringBuffer .equals() method is used for reference comparison.
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
Constructors:-
1. StringBuffer sb=new StringBuffer();
2. StringBuffer sb1=new StringBuffer(int capacity);
3. StringBuffer sb2=new StringBuffer(String str);
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 57
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 58
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
class A
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK
1.5.
Important Constructors of StringBuilder class
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity
as length.
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 when you
concat too many strings because every time it creates new
StringBuffer is fast and consumes
less memory when you cancat
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 59
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
String
instance. strings.
3)
String class overrides the equals() method of Object class.
So you can compare the contents of two strings by equals()
method.
StringBuffer class doesn't override
the equals() method of Object class.
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences between
StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
1)
StringBuffer is synchronized i.e. thread safe. It
means two threads can't call the methods of
StringBuffer simultaneously.
StringBuilder is non-synchronized i.e. not thread
safe. It means two threads can call the methods of
StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depends on your implementation.
class Student
{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[])
{
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1.toString);
System.out.println(s2);//compiler writes here s2.toString()
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 60
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Wrapper Classes
Wrapper classes
1) To represent primitive data types as a Object form we required some classes these classes
are called wrapper classes.
2) All wrapper classes present in the java.lang package.
3) Int,byte…. Acts as a primitives we can make the primitives into the objects is called
wrapper calless the the wrapper classes are Integer,Short-----.
4) We are having 8 primitive data types hence sun peoples are providing 8 wrapper classes.
Data types and corresponding wrapper classes:-
byte ----- Byte
short ----- Short
int ----- Integer
long ----- Long
float ----- Float
double ----- Double
boolean ----- Boolean
char ------ Character
6) Byte,Short,Integer,Long,Float,Double these are child classes of Number class.
Constructors of wrapper classes:-
All most all wrapper classes contain two constructors:-
1. Integer i=new Integer(10);
2. Integer i=new Integer(“10”);
Primitives Wrapper classes Fallowing constructor
arguments
byte
short
int
long
float
double
char
Boolean
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Byte or String
Short or String
Int or String
Long or String
Float or double or String
double or String
Char
Boolean or String
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 61
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Wrapper Classes
Wrapper classes hierarchy
The main importance of wrapper classes:-
1. To convert a data types into the object means we are giving object from data types by
using constructor.
2. To convert String into the data types by using parsexxx() method
Utility methods:-
1. valueOf()
2. xxxValue()
3. parsexxx()
1) valueOf():-
By using valueof() we are creating wrapper object and it is a alternative to the constructor.
class Test
{
public static void main(String[] args)
{
//by using constructor converting String/primitive to wrapper object
Integer i=new Integer(10);
System.out.println(i);
//by using valueOf() converting String/primitive to the wrapper object
Boolean b=Boolean.valueOf("true");
System.out.println(b);
}
}
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 62
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Wrapper Classes
XxxValue():-
by using XXXValue() method we are converting wrapper objects into the corresponding
primitive values
class Test
{
public static void main(String[] args)
{
Integer i=Integer.valueOf(150);
System.out.println("byte value :"+i.byteValue());//-106
System.out.println("short value :"+i.shortValue());//150
System.out.println("int value :"+i.intValue());//150
System.out.println("long value :"+i.longValue());//150
System.out.println("float value :"+i.floatValue());//150.0
System.out.println("double value :"+i.doubleValue());//150.0
Character c=new Character('s');
char ch=c.charValue();
System.out.println(ch);
Boolean b=new Boolean(false);
boolean bb=b.booleanValue();
System.out.println(bb);
}
}
parseXXX():-
by using above method we are converting String into the corresponding primitive.
class Test
{
public static void main(String[] args)
{
String str1="10";
String str2="20";
System.out.println(str1+str2);//1020
int a=Integer.parseInt(str1);
float f=Float.parseFloat(str2);
System.out.println(a+f);//30.0
}
}
Autoboxing and Autounboxing:-(introduced in the 1.5 version)
Until 1.4 version we are not allowed to place primitive in the wrapper and wrapper in the
place of primitive. The programmer is responsible person to do the explicit conversion
primitive to the wrapper and wrapper to the primitive.
Autoboxing:-
Integer i=10;
System.out.println(i);
The above statement does not work on the 1.4 and below versions. The auto conversion of the
primitive into the Wrapper object is called the autoboxing these conversions done by
compiler at the time of compilation.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 63
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Wrapper Classes
Autounboxing:-
int a=new Integer(100);
System.out.println(a);
The auto conversion of the wrapper object to the primitive value is called autounboxing and
these conversions are done by compiler at the time of compilation.
Ex :-
class Test
{
static Integer i=10;//i is wrapper object
static int j;//j is primitive variable
static void print(int i)
{
j=i;
System.out.println(j);
}
public static void main(String[] args)
{
print(i);
System.out.println(j);
}
}
Automatic conversion of the primitive to wrapper and wrapper to the primitive:-
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 64
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
Java.io package
 Java io(input/output) is used to process to the input and produced the output.
 Java uses the concept of stream and makes fast I/O operation.
 The java.io package is the collection of classes which are requires to input and output.
 We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
System.out.println("simple message");
System.err.println("error message");
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 65
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream
Method Description
1) public void write(int)throws
IOException
is used to write a byte to the current output
stream.
2) public void write(byte[])throws
IOException
is used to write an array of byte to the current
output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 66
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input
stream of bytes.
Useful methods of InputStream
Method Description
1) public abstract int read()throws
IOException
reads the next byte of data from the input stream. It
returns -1 at the end of file.
2) public int available()throws
IOException
returns an estimate of the number of bytes that can be
read from the current input stream.
3) public void close()throws
IOException
is used to close the current input stream.
InputStream Hierarchy
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 67
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutStream.
FileOutputStream class methods
Method Description
protected void finalize() It is sued to clean up the connection with the file output stream.
void write(byte[] ary)
It is used to write ary.length bytes from the byte array to the
file output stream.
void write(byte[] ary, int off,
int len)
It is used to write len bytes from the byte array starting at offset
off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel()
It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD()
It is used to return the file descriptor associated with the
stream.
void close() It is used to closes the file output stream.
Java FileOutputStream Example 1: write byte
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...(this is the output which show at consol after the execution of the program)
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 68
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
The content of a text file testout.txt is set with the data A.
testout.txt
A (this is data which is written by the program in the testout.txt file)
Java FileOutputStream example 2: write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
String s="Welcome to Aims Tutorial.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to Aims Tutorial.
testout.txt
Welcome to Aims Tutorial.
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader
class.
Java FileInputStream class methods
Method Description
int available()
It is used to return the estimated number of bytes that can be read
from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off,
int len)
It is used to read up to len bytes of data from the input stream.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 69
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
long skip(long x)
It is used to skip over and discards x bytes of data from the input
stream.
FileChannel
getChannel()
It is used to return the unique FileChannel object associated with
the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize()
It is used to ensure that the close method is call when there is no
more reference to the file input stream.
void close() It is used to closes the stream.
Java FileInputStream example 1: read single character
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be created. In
this file, we are having following content:
Welcome to Aims Tutorial.
After executing the above program, you will get a single character from the file which is 87 (in
byte form). To see the text, you need to convert it into character.
Output:
Welcome to AimsTutorial
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 70
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
Java FileInputStream example 2: read all characters
package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Welcome to Aims Tutorial
BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally uses
buffer to store data. It adds more efficiency than to write data directly into a stream. So, it
makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:IO Packag
etestout.txt"));
Java BufferedOutputStream class constructors
Constructor Description
BufferedOutputStream(OutputStream os)
It creates the new buffered output stream which is
used for writing the data to the specified output
stream.
BufferedOutputStream(OutputStream os,
int size)
It creates the new buffered output stream which is
used for writing the data to the specified output
stream with a specified buffer size.
Aims Tutorial
Oriental Bank of Commerce
H.No.:69/339 VT Road Ward 27,
Mansarovar Jaipur (Rajasthan) 302020
Contact No: +91-8947920041
P a g e | 71
By: Manish Swarnkar
9887474850
Java Tutorial
By:Manish Swarnkar
Contact No:9887474850
manishsony4u@gmail.com
Java.io package
Java BufferedOutputStream class methods
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int
off, int len)
It write the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset
void flush() It flushes the buffered output stream.
Example of BufferedOutputStream class:
In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Aims Tutorial.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
Success
testout.txt
Welcome to Aims Tutorial.
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes
Java notes

More Related Content

What's hot

Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.Bhautik Jethva
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 

What's hot (20)

Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Methods in java
Methods in javaMethods in java
Methods in java
 
core java
core javacore java
core java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java literals
Java literalsJava literals
Java literals
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Java
JavaJava
Java
 

Similar to Java notes

Introduction to java
Introduction to javaIntroduction to java
Introduction to javashwanjava
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxSuganthiDPSGRKCW
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptxprstsomnath22
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdfDeepakChaudhriAmbali
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
 
Introduction to Java by Java homework experts
Introduction to Java by Java homework expertsIntroduction to Java by Java homework experts
Introduction to Java by Java homework expertsMitchell Lee
 
Java Course training in Hamirpur Himachal Pradesh
Java Course training in Hamirpur Himachal PradeshJava Course training in Hamirpur Himachal Pradesh
Java Course training in Hamirpur Himachal PradeshExcellence Technology
 
C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...MCM COmpetitive Classes
 
Features of java - javatportal
Features of java - javatportalFeatures of java - javatportal
Features of java - javatportalJavaTportal
 
Java homework help
Java homework helpJava homework help
Java homework helpcalltutors
 

Similar to Java notes (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
E farming
E farmingE farming
E farming
 
String class
String classString class
String class
 
Java-Unit-I.ppt
Java-Unit-I.pptJava-Unit-I.ppt
Java-Unit-I.ppt
 
HR OPERATION MANAGER
HR OPERATION MANAGERHR OPERATION MANAGER
HR OPERATION MANAGER
 
What is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK TechnologiesWhat is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK Technologies
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to Java by Java homework experts
Introduction to Java by Java homework expertsIntroduction to Java by Java homework experts
Introduction to Java by Java homework experts
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java Course training in Hamirpur Himachal Pradesh
Java Course training in Hamirpur Himachal PradeshJava Course training in Hamirpur Himachal Pradesh
Java Course training in Hamirpur Himachal Pradesh
 
C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...C,c++,java,php,.net training institute in delhi, best training institute for ...
C,c++,java,php,.net training institute in delhi, best training institute for ...
 
Professional-core-java-training
Professional-core-java-trainingProfessional-core-java-training
Professional-core-java-training
 
Features of java - javatportal
Features of java - javatportalFeatures of java - javatportal
Features of java - javatportal
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
 
Java homework help
Java homework helpJava homework help
Java homework help
 
Professional-core-java-training
Professional-core-java-trainingProfessional-core-java-training
Professional-core-java-training
 

Recently uploaded

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 

Recently uploaded (20)

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 

Java notes

  • 1. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 1 By: Manish Swarnkar 9887474850 Java Training Module c (A Software Development Company and Training Center) Contact Information: Contact No: +91-8947920041, 9829761399 Email: info@aimstutorial.com info@integrationedutech.com Website: www.aimstutorial.com www.integrationedutech.com Address Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020
  • 2. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 2 By: Manish Swarnkar 9887474850 Java  Java is an object oriented programming language originally developed by Sun Micro System and released in 1995.  Java was originally by James Gosling at Sun Microsystems (which has since merge in Oracle Corporation).  Java programs are platform independent which means they can be run on any operating system.  Java codes that run on one platform does not need to recompile to run on another platform, it’s called “write once run anywhere”. Java Features 1. Object Oriented Java is an object oriented programming language which follows the concepts of oop’s. 2. Platform Independent Java application programs written on one operating system can be able to run on any platform. So the java is platform independent. On compilation java program is compiled into byte code (.class file). This byte code is platform independent and can be run on any machine, in addition to this bytecode format also provide security. Any machine with Java Runtime Environment can run java programs. 3. Simple Java syntax is similar to c and c++ and it follow the oop’s concepts so it is easy to learn.
  • 3. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 3 By: Manish Swarnkar 9887474850 4. Secure Java’s securing feature it enable to develop virus free, tamper free (software which is not modify by attacker). Authentication techniques are based on public key encryption Note: A cryptographic system that uses two keys -- a public key known to everyone and a private or secret key known only to the recipient of the message. When John wants to send a secure message to Jane, he uses Jane's public key to encrypt the message. Jane then uses her private key to decrypt it.  Class loader- It adds security by separation by separating the package for the classes of the local file system from those that are imported from network sources.  Byte code verifiers-It checks the code fragments for illegal code that can violate access right to objects.  Security Manager- It determines what resources a class can access such as reading and writing to the local disk.  High Performance- Compilation of program to an architecture independent machine like language, result in a small efficient interpreter of java programs. The java environment also complies the java byte code into native machine code at runtime. 5. Architectural Neutral Java compiler generates an architectural neutral object file format which makes the compiler code to be executed on many processors, with the presence of java runtime system. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures. 6. Portable We may carry the java byte code to any platform. 7. Robust Robust simply means strong. Java uses strong memory management. There is lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points make java robust. 8. 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 shares a common memory area. Threads are important for multi-media, Web applications etc. 9. Interpreted Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program. 10. High Performance Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
  • 4. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 4 By: Manish Swarnkar 9887474850 11. Distributed We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet. 12. Dynamic Java is considered more dynamic than c and c++. In java the application can be create more dynamic. Types of java Application 1. Web Application Java is used to create server side applications. Currently , servelet, jsp, struts, jsf etc technology are used. 2. Stand- Alone Application It is also known as desktop application or window based application. An application that we need to install on every machine such as antivirus, media player etc. AWT and Swing is used in java for creating standalone application. 3. Enterprise Application An application that is distributed in nature, such as banking application etc. In java EJB is used to create enterprise application. 4. Mobile application Java is used to create application software for mobile devices. Currently java ME is used for creating application for small devices and java is programming for Google Android application development. Different Editions of java Technology 1. Java SE Java SE or Java Standard Edition provides tools and API’s that can use to create server application, desktop application and even applets. These programs developed using java SE can be run on almost every popular operating system include Linux, Macintosh, Solaris, and Windows. 2. JEE Based on the foundation framework of the standard edition, java Enterprise Edition helps in web application service, component model and enterprise class service oriented architecture. 3. JME Java Micro Edition or JME is use for the development of software for devices like mobile phones, PDA’s, TV set-top box, game programming.
  • 5. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 5 By: Manish Swarnkar 9887474850 C++ v/s Java Comparison C++ Java Platform- independent C++ is platform-dependent. Java is platform-independent. Mainly used for C++ is mainly used for system programming. Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications. Goto C++ supports goto statement. Java doesn't support goto statement. Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java. Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading. Pointers C++ supports pointers. You can write pointer program in C++. you can't write the pointer program in java. It means java has restricted pointer support in java. Compiler and Interpreter C++ uses compiler only. Java uses compiler and interpreter both. Call by Value and Call by reference C++ supports both call by value and call by reference. Java supports call by value only. There is no call by reference in java. Structure and Union C++ supports structures and unions. Java doesn't support structures and unions. Thread Support C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support. Java has built-in thread support. Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ... */) to create documentation for java source code. Virtual Keyword C++ supports virtual keyword so that we can decide whether or not override a function. Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default. unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that fills zero at the top for the negative numbers. For positive numbers, it works same like >> operator. Inheritance Tree C++ creates a new inheritance tree always. Java uses single inheritance tree always because all classes are the child of Object class in java. Object class is the root of inheritance tree in java.
  • 6. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 6 By: Manish Swarnkar 9887474850 Java oop’s Concepts or java oop’s paradigm  Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc.  The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.  OOPs (Object Oriented Programming System) Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:  Object  Class  Inheritance  Abstraction  Encapsulation  Polymorphism Class  It is similar to structures in C language. Class can also be defined as user defined data type but it also contains functions in it. So, class is basically a blueprint for object.  A class enclosed both the data and function that operate on the data, into a single unit. The variable and function enclosed in a class are called member and member functions respectively. Member functions define the permission operation on the data member of a class. data Data 1 Data2 Data3 fun()1 fun()2 fun(3) function
  • 7. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 7 By: Manish Swarnkar 9887474850 Object  Objects are the basic unit of OOP. They are instances of class, which have data members and use various member functions to perform tasks.  Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object represents a particular instance of a class. There can be more than one instance of a class. Each instance of a class can hold its own relevant data. Inheritance  Inheritance is the process of forming a new class from an existing class or base class. The base class is also known as parent class or super class. The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program, which is an important concept in object-oriented programming.  Inheritance is a way to reuse once written code again and again. The derived class can use all the functions which are defined in base class, hence making code reusable. Animal Mammal Reptile Elephant Tiger Crocodile Data1 Data2 Fun1 Fun2 Data Function Obj 2 Obj 1 Data function Data function Obj 3 Data function
  • 8. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 8 By: Manish Swarnkar 9887474850 Data Abstraction  Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes provide methods to the outside world to access & use the data variables, but the variables are hidden from direct access.  Data abstraction allows a program to ignore the details of how a data type is represented. Abstraction (derived from a Latin word , meaning away from and , meaning to draw) refers to the act of representing essential features without including the background details or explanations.  While classifying a class, both data members and member functions are expressed in the code. But, while using an object (that is an instance of a class) the built in data types and the members in the class get ignored which is known as data abstraction. Data Encapsulation  Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.  It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.  C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are private. Polymorphism  The term Polymorphism get derived from the Greek word where ‘poly’+ ‘morphos’ where ‘poly’ means many and ‘morphos’ means forms.  Polymorphism makes the code more readable. It is a feature, which lets is create functions with same name but different.  The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. Shap Draw() Box obj Draw(Box) Triangle obj Draw(Triangle) Circle obj Draw(Circle)
  • 9. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 9 By: Manish Swarnkar 9887474850 Setting Path for Java Java is freely available on the oracle website Download the latest version of JDK(java Development Kit)on your machine. Install JDK on your machine. Once you have installed java on your machine it need to set environment variable to point to correct installation directory. An environment variable is a dynamic “object ” on a computer that stores a value (like a key value ), which can be reference by one or more software programs in Windows. Like in java , we will set environment variable with name ”java” and its values will be the path of /bin directory present variable which will give it the path to the execution. Step: 1 Right click on My Computer icon and select properties. Step: 2 Go to Advance Setting Tab
  • 10. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 10 By: Manish Swarnkar 9887474850 Step: 3 Click on Environment Variable Button Step:4 Now alter the path variable so that it also contains the path to jdk installed directory.
  • 11. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 11 By: Manish Swarnkar 9887474850 First java Program public class FirstJava { public static void main(String[] args) { System.out.println("Welcome in Aims"); } }  class: class is a keyword is used to declare classes in java  public: It is an access specifiers . Public means this function is visible to all.  static: static is used to make a function static. To execute a static function you do not have to create an Object of the class. The main () method here is called by jvm, without creating any object for class.  void: void is return type, meaning this function will not return anything.  main(): main() method is the most important method in a java program . this is the method which is executed hence all logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.  System.out.println(): This is used to print anything on the consol like printf()in c. Steps to compile and Run FirstJava Program Step: 1 Open a text editor like Notepad and write the code as above. Step: 2 save the file as FirstJava.java Step: 3Open command prompt and go to the directory where you saved your first java program
  • 12. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 12 By: Manish Swarnkar 9887474850 Step: 4 Type javac FirstJava.java then enter to compile the program Step: 5 Now Type java FirstJava on command prompt the enter to run program. Step: 6 Now you will be able to see Welcome in Aims oriented on your command prompt.
  • 13. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 13 By: Manish Swarnkar 9887474850 Java Development Kit (JDK) JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + the complete set of class file for all the java technology package, which include basic language classes.GUI components classes, an advanced collection API, and so no. Java Virtual Machine (JVM) It is an abstract machine or imaginary machine that is implemented by emulating it in software on a real machine. Code for JVM is stored in .class file. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. The JVM specification provides concrete definition for the implementation of the following: an instruction set (equivalent to that of a center processing machine [CPU]), a register set, the class file format, a runtime stack, a garbage-collector heap a memory area etc. The JVM performs following main tasks:  Loads code  Verifies code  Executes code  Provides runtime environment JVM Internal Architecture It contains 1. Class loader: class loader loads all classes needed for the execution of a program. The class loader adds security. 2. Memory area 1. Class (Method) Area: Class (Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. 2. Heap: It is the runtime data area in which objects are allocated. 3. Stack: It holds local variables and partial results, and plays a part in method invocation and return. 4. Program counter Registers: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. 5. Native Method Stack: It contains all the native methods used in the application. 3. Execution engine It contains 1. A virtual processor 2. Interpreter: Read byte code stream the execute the instruction
  • 14. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 14 By: Manish Swarnkar 9887474850 Java Runtime Environment (JRE) It is used to provide runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime. Implementation of JVMs is also actively released by other companies besides Sun Micro Systems.
  • 15. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 15 By: Manish Swarnkar 9887474850 Difference between JRE and JDK Sr. no JRE JDK 1 JRE is an implementation of the java Virtual Machine which actually executes java program JDk is bundle of software that is used to develop java base application 2 Java Runtime Environment is a plug- in needed for running java programs Java Development Kit is needed for developing java application 3 JRE include the JVM, core libraries And other additional component to run application and applets written in java JDk include the JRE, set of API classes, java complier and additional files needed to write java applets and applications. Byte Code: When the java program compile the source code is converted in intermediate code with extension .class called, Byte Code which is read by the JVM machine.  Byte code and JVM both makes java platform independent. Just-In-Time (JIT) Compiler In some Java technology runtime environments a portion of verified byte code is compiled to native machine code by the JIT(Just-In-Time compiler)and execute directly on the hardware platform. This compiler is called Just-IN-Time Complier. It enables the java software code to run close to the speed of C or C++ with small delay at load time to enable the code to be compiled to the native machine code.
  • 16. Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Introduction of java Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 16 By: Manish Swarnkar 9887474850 Byte Code Verifier Java software code passes several tasks before running on your machine. The JVM puts the code through byte code verifiers that tests the format of code fragments and check code for illegal code, called byte code verifiers. It provides securities for java programs. Garbage Collection It provides a system-level thread that tracks each memory allocation. During idle cycles in the JVM, the garbage collection threads checks for and free any memory that can freed. Garbage collection happens automatically during the life time of a java technology program, eliminating the need to deal locate memory and avoiding memory leak.
  • 17. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 17 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens Tokens  Each and every smallest individual unit in a program is known as tokens.  Tokens are the basic buildings blocks in language which are constructed together to write a program.  The keywords, identifiers, constants, string literals, and operators are examples of tokens. Punctuation characters such as brackets [ ], braces { }, parentheses ( ), and commas (,) are also tokens. 1.Keywords  Keywords are those words whose meaning is already defined by language  There are 50 Keywords in java.  Keywords are also called as reserved words.  const and goto are two keywords which are reserved in java but not defined by java language. abstract continue goto package switch assert default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extern int short try catch final interface static void char finally long stricfp volatile class float native super while const for new synchronized
  • 18. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 18 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens 2.Identifiers Identifiers are the name given to various programming element like variable name, class name, object name array name, function name interface name, package name. Rules for constructing identifier name  All the identifiers must start with either a letter (a to z or A to z) or currency character ($) or an underscore.  They can have alphabets, digits, and the underscore (_) and dollar sign ($) characters.  They must not begin with a digit.  After first character, an identifier can have any combination of character.  A java keyword cannot use as an identifiers.  Identifiers in java are case sensitive abc and ABC are two different identifiers. Uppercase and lowercase are distinct. Java developers have followed some naming conventions. 1. When more than one word are used in a public methods and instance name, the second and subsequent words are marked with a leading letters. Examples: dayTemperature firstDayOfMonth totalMarks 2. All private and local variable use only lowercase letters combine with underscores. Examples: length batch_strength 3. All classes and interface start with uppercase letter(and each subsequent word with a leading uppercase) Example: Student HelloJava Vehical MotorCycle 4. Variables that represent constant values use all uppercase letter and underscore between words. Example: TOTAL F_MAX PRINCIPAL_AMOUNT 5. Package name should be in lowercase Example: java, lang, sql, util, etc. 6. Method name should be in lowercase letters. Example: print (), println().
  • 19. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 19 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens 3.Constants or Literals  Constants or Literals are the fixes values which are not change during the execution of the programs.  Literals are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in a variable.  Constants or Literals are declare using final keywords There are five major types of literals. 1. Integer literals Integers are any numeric values either positive or negative without having fractional part. Integer datatype consists of the following primitive data types: byte, int, short, long can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number system. Example: final int decimal=100; final int octal=0144; final int hexa=0x64; 2. Floating literals  Floats are the numeric values either negative or positive having fractional parts.  Java has two types of floating point numbers: float and double.  By default floating point literals is double  We can define the floating point literals by appending F or f suffix after the values. Example: final float pi=3.14f; 3. Character literals A Character literals is a single character in a pair of single quote such as ‘a’, ‘#’ Char datatypes is a single 16-bit Unicode character. Example: final char ch=’A’; final char ch=’u0041’; final char ch=’t’; final char ch=’u0009’; Escape Sequence Characters Escape Character Meaning n New line t Tab b Backspace r Carriage return f Form feed backslash ’ single quote ”” double quotation marks
  • 20. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 20 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens 4. String literals The set of characters represented as String literals. It is use “double quotes”. final String ch="Aims"; 5. Boolean literals The values true and false are treated as literals in java. When we assign a value to a boolean variable is true or false. final boolean bool=true; 4.Operator Operator is the special symbols the perform the mathematical and logical manipulation. Types of operator 1. Arithmetic operator Operators which are used for arithmetical operation (+, -, *, /, and %) called arithmetic operator. Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulus 2. Relational operator Operators are used to test the relation between two values called relational operator. All relational operators are binary operators and therefore require two operands. A relational expression returns false when the relation is false and a true when it is true. Relational Operators Meaning < Less than <= Less than or equal to == Equal to > Greater than >= Greater than or equal to ! = Not equal to public class RelationalOperatorsDemo { public static void main(String args[]) { int x = 10, y = 5; System.out.println("x > y : "+(x > y)); System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x <= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y)); } }
  • 21. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 21 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens 3. Logical operator Operators which are used to combine one or more relational expression called logical operator. Operators Meaning operation || OR a||b is true && AND a&&b is false ! NOT (!a) is false public class LogicalOperatorsDemo { public static void main(String args[]) { boolean x = true; boolean y = false; System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y)); System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("!x : " + (!x)); } } 4. Bitwise operator These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits. Bit wise operators in java are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift). Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise XOR ~ One ‘Complement >> Bitwise right shift << Bitwise left Shift Truth Table of Bitwise operator x y x|y x&y x^y 0 0 0 0 0 0 1 1 0 1 1 0 1 0 1 1 1 1 1 0
  • 22. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 22 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens public class BitwiseOperatorsDemo { public static void main(String args[]) { int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1 int z; System.out.println("x & y : " + (x & y)); System.out.println("x | y : " + (x | y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("~x : " + (~x)); System.out.println("x << y : " + (x << y)); System.out.println("x >> y : " + (x >> y)); System.out.println("x >>> y : " + (x >>> y)); } } 5. Ternary operator Operator that performs operation on three operands called ternary operator. Conditional Operator  The conditional operator ? : is called ternary operator as it requires three operands. Syntax: Conditional Exp? Exp1: Exp2 If the value of conditional expression is true then the exp1 is evaluated, otherwise exp2 is evaluated. public class TernaryOperatorsDemo { public static void main(String args[]) { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } } 6. Assignment operator Operator ('=') which is used for assigning a value to a variable is called assignment operator. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. For example: m = 5; Operator Example Equivalent to + = A + = 2 A = A + 2 - = A - = 2 A = A - 2 % = A % = 2 A = A % 2 /= A/ = 2 A = A / 2 *= A * = 2 A = A * 2
  • 23. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 23 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens 7. Increment or decrement operator Operator which perform operation only on one operand are called Unary operator. 1. Increment Operator ++ Operator increment the value of a variable by 1 is called increment operator.  Pre-increment ++ is written before variable name. Value is incremented first then incremented value is used in expression. Ex: public class IncPre { public static void main(String args[]) { int i, a=5; i=++a; System.out.println(i); } }OUTPUT: 6 Post-increment  ++ is written after variable name. Value is assigned to expression after that the value is increment. Ex: public class IncPre { public static void main(String args[]) { int i, a=5; i=a++; System.out.println(i); } }OUTPUT:5 2. Decrement Operator -- Operator decrement the value of a variable by 1 is called decrement operator.  Pre-decrement -- is written before variable name. Value is decremented first then decremented value is used in expression. Ex: public class IncPre { public static void main(String args[]) { int i, a=5; i=--a; System.out.println(i); } }OUTPUT: 4
  • 24. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 24 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Tokens  Post-decrement -- is written after variable name. Value is assigned in expression then the decrement the value. Ex: public class IncPre { public static void main(String args[]) { int i, a=5; i=a--; System.out.println(i); } }OUTPUT:5 5.Separator The separators define the structure of a program. The separators are used parentheses ( ), braces { }, the period (.) and (;) semicolon. Comments Comments are special part of the program, to describe or explain the code which make easy to understand. Comments are those lines which are not read by the compilers. Types of Comments 1. Single line comments Single line comments starts with two forward slash (//) It useful when only single lines are commented. final int a=5// a is constants variable 2. Multiline comments Multiline comments are starts with forward slash/ and after that star (*) and the text or comment line put then again star(*) put the again forward slash(/) put to comment . It is useful when we comment multiple line in program. 3. Document comment /** document comment*/ This is document comment it described the author and other information about a program. The JDK javadoc tool uses doc comment for automatically generated documentation.
  • 25. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 25 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Data Types Data Types: Data type are the keyword which assign a type to a variable. There are two data types available in Java  Primitive Data Types  Reference/Object Data Types Primitive Data Types Eight Primitive datatypes are predefined by the java. byte  Byte data type is an 8-bit signed two's complement integer  Minimum value is -128 (-2^7)  Maximum value is 127 (inclusive)(2^7 -1)  Default value is 0  Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.  Example: byte a = 100, byte b = -50 short  Short data type is a 16-bit signed two's complement integer  Minimum value is -32,768 (-2^15)  Maximum value is 32,767 (inclusive) (2^15 -1)  Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer  Default value is 0.  Example: short s = 10000, short r = -20000 int  Int data type is a 32-bit signed two's complement integer.  Minimum value is - 2,147,483,648 (-2^31)  Maximum value is 2,147,483,647(inclusive) (2^31 -1)  Integer is generally used as the default data type for integral values unless there is a concern about memory.  The default value is 0  Example: int a = 100000, int b = -200000 long  Long data type is a 64-bit signed two's complement integer  Minimum value is -9,223,372,036,854,775,808(-2^63)  Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)  This type is used when a wider range than int is needed  Default value is 0L  Example: long a = 100000L, long b = -200000L
  • 26. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 26 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Data Types float  Float data type is a single-precision 32-bit IEEE 754 floating point  Float is mainly used to save memory in large arrays of floating point numbers  Default value is 0.0f  Float data type is never used for precise values such as currency  Example: float f1 = 234.5f double  double data type is a double-precision 64-bit IEEE 754 floating point  This data type is generally used as the default data type for decimal values, generally the default choice  Double data type should never be used for precise values such as currency  Default value is 0.0d  Example: double d1 = 123.4 boolean  boolean data type represents one bit of information  There are only two possible values: true and false  This data type is used for simple flags that track true/false conditions  Default value is false  Example: boolean one = true char  char data type is a single 16-bit Unicode character  Minimum value is 'u0000' (or 0)  Maximum value is 'uffff' (or 65,535 inclusive)  Char data type is used to store any character  Example: char letterA = 'A' Reference Datatypes  Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.  Class objects and various type of array variables come under reference datatype.  Default value of any reference variable is null.  A reference variable can be used to refer any object of the declared type or any compatible type.  Example: Animal animal = new Animal("giraffe");
  • 27. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 27 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Class Class “Class is a user defined data types, which holds variables and , which can be accessed and used by creating instance of that class.” Class is just a blue print, which declare and defined variables and methods. All objects of this class will share these data member and function. About Class: 1. Class name start with an uppercase letter. If class name is made then one word, the first letter of each word must be in uppercase. Ex:- Class Study, class AimsTutorial 2. Objects of the class holds separate copies of data member. We can create as many objects of a class as we need. How to declare class: Syntax: public class Class_Name { variables; methods( ); public static void main(String[] args) { Class_Name obj=new Class_Name() } }; Example: public class Aims { int i=10; public static void main(String[] args) { Aims a1=new Aims(); System.out.println(a1.i); } } Output: 10; Objects Objects are the variable which declare using class name, it holds the data variable, declared in the class and the member function works on these class objects. How to declare objects: public class Abc { int x=10; void display( ) { System.out.println(x); }
  • 28. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 28 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Class public static void main(String[] args) { Abc obj=new Abc(); Obj.display(); } } Output:10  Each object has different data variables.  Object are initialized using special methods are called constructor. A class can contain any of the following variable types.  Local variables − Variables which defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. class Test { public static void main(String[] args) { int a=10; Local variables int b=20; System.out.println(a+b); } }  Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. class Test { int a=10; int b=20; void add() { System.out.println(a+b); } public static void main(String[] args) { Test t=new Test(); System.out.println(t.a+t.b); t.add(); } }
  • 29. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 29 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Array  Static variable or Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. class Test { static int b=20; public static void main(String[] args) { System.out.println(b);//20 } } Arrays:- 1) Array is a final class inheritance is not possible. 2) Arrays are used to store the multiple numbers of elements of single type. 3) The length of the array is established at the time of array creation. After creation the length is fixed. Root structure:- java.lang.Object +--java.lang.reflect.Array public final class Array extends Object single dimensional array declaration:- int[] a; int []a; int a[]; declaration & instantiation & initialization :- approach 1:- int a[]={10,20,30,40}; approach 2:- int[] a=new int[100]; a[0]=10; a[1]=20; a[2]=30; a[4]=40; 10 20 30 40 50 60 70 80 90 Ex:-printing the array elements class Test { public static void main(String[] args) { int[] a={10,20,30,40}; System.out.println(a[0]); System.out.println(a[1]); System.out.println(a[2]); System.out.println(a[3]); } }
  • 30. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 30 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Array Ex:-printing the array elements by using for loop class Test { public static void main(String[] args) { int[] a={10,20,30,40}; for (int i=0;i<a.length;i++) { System.out.println(a[i]); } } } declaration of two dimensional array:- int[][] a; int [][]a; int a[][]; int []a[]; Ex:- class Test { public static void main(String[] args) { int[][] a={{10,20,30},{40,50,60}}; System.out.println(a[0][0]);//10 System.out.println(a[1][0]);//40 System.out.println(a[1][1]);//50 } } Methods (behaviors):- 1) Methods are used to provide the business logic of the project. 2) The methods like a functions in C-language called functions, in java language is called methods. 3) Inside the class it is possible to declare any number of methods based on the developer requirement. 4) As a software developer while writing method we have to fallow the coding standards like the method name starts with lower case letters if the method contains two words every inner word also starts uppercase letter. 5) It will improve the reusability of the code. By using methods we can optimize the code. Syntax:- [modifiers-list] return-Type Method-name (parameter-list)throws Exception Ex:- public void m1() public void m2(int a, int b) Method Signature:- The name of the method and parameter list is called Method Signature. Return type and modifiers list not part of a method signature. Ex:- m1(int a,int b)------Method Signature m2();------------------Method signature
  • 31. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 31 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Array There are two types of methods:-  Instance method Method which are declare and defined inside a class and without static keyword and called using object. class Test { void display() { System.out.println("Aims Tutorial"); } public static void main(String[] args) { Test t=new Test(); t.display(); } }  Static method Method which are declare and defined inside a class and with static keyword and called using classname. class Test { Static void display() { System.out.println("Aims Tutorial"); } public static void main(String[] args) { Test.display(); } }
  • 32. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 32 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Constructor Heap memory Stack memory 1) It is used to store the objects 1) It is used to store the function calls and local variables. 2) We are getting outOfMemoryError 2) If the there is no memory in the stack to store method calls or local variables the JVM will throw the StackOverflowError. 3) Having more memory compared with the stack memory. 4) Heap memory is also known as public memory. This is applicable all the objects. This memory is shared by all threads. 5)the objects are created in the heap memory with the help of new operator 3) Stack memory is very less memory when compared with the heap memory 4) Stack memory also known as private memory. This is applicable only for owners. 5) Destroy when the method is completed. Jvm is creating stack memory Constructor Constructor is a special type of method which has same as class that is used to initialize the object. Constructor is called at the time of object creation. It constructs the value or provides data for the object that is why it is known as constructor. Rules for creating constructor 1. Constructor name must be same as its class name. 2. Constructor must have no return type. Types of constructor 1. Default constructor. A Constructor that have no parameter is known as default constructor. Purpose of default constructor  Default constructor provide the default value to the object 0,null etc depending on the type. class Bike { public static void main(String args[]) { Bike b=new Bike(); } Bike() { System.out.println(“Default constructor is created”); } }
  • 33. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 33 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Constructor 2. Parameterized constructor. A Constructor that has parameter is known as parameterized constructor.  Why use parameterized Constructor  parameterized constructor provide the different values to the distinct object class Square { public static void main(String args[]) { Square b=new Square (5); } Square(int n) { System.out.println(n*n); } } this heyword:- This keyword is used to represent 1. Current class variables. 2. Current class methods. 3. Current class constructors. class Test { int a=10; int b=20; void add(int a,int b) { System.out.println(a+b); System.out.println(this.a+this.b); } public static void main(String[] args) { Test t=new Test(); t.add(100,200); } }
  • 34. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 34 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance INHERITANCE Inheritance is the capability of acquire property(variables) and behaviors(methods) of another class is called inheritance. 1. The main purpose of the inheritance is code extensibility whenever we are extending automatically the code is reused. 2. In inheritance one class giving the properties and behavior and another class is taking the properties and behavior. 3. Inheritance is also known as is-a relationship means two classes are belongs to the same hierarchy. 4. By using extends keyword we are achieving inheritance concept. 5. In the inheritance the person who is giving the properties is called parent the person who is taking the properties is called child. 6. To reduce length of the code and redundancy of the code sun peoples introducing inheritance concept. Types of Inheritance 1. Single Inheritance In this inheritance one derived class inherits from only one base class. It is the simplest form of inheritance. A Base class B Derived class
  • 35. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 35 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance 2. Multiple Inheritance In this type of inheritance a single derived class inherits from two or more than two base classes. 3. Multilevel Inheritance In this type of inheritance the derived class inherits from a class, which is turn inherits from some other class. The super class for one is sub class for another class. A Base class B Base class C Derived class B Derived class A Base class C Derived class
  • 36. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 36 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance 4. Hierarchical Inheritance In this type of inheritance multiple derived classes are inherits from a single base class. 5. Hybrid Inheritance Hybrid inheritance is combination of multiple and multilevel inheritance. Two or more type of inheritance are used to design called Hybrid inheritance. A Derived class B Derived class C Base class B Derived class C Derived class A Base class D Derived class
  • 37. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 37 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance 1. Single Inheritance public class Shap { int width; int height; void setdata(int w, int h) { width=w; height=h; } } class Rectangle extends Shap { int getArea() { return(width*height); } public static void main(String[] args) { Rectangle Rect; Rect.setdata(5,7); System.out.prinln(“Total Area="+Rect.getArea()); } 2. Multilevel publc class Student { int rollno; void read(int rollno) { this.rollno=rollno; } }
  • 38. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 38 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance class Marks extends Student { int m1, m2, m3; void getMarks(int m1,int m2,int m3) { this.m1=m1; this.m2=m2; this.m3=m3; } } class Result extends Marks { int total; void process() { total=m1+m2+m3; } void print() { System.out.prinln(“Total result="+total); } public static void main(String[] args) { Result R; R.read(); R.getMarks(); R.process(); R.print(); } } Output: Enter RollNo=234 Enter Marks in Sub1=20 Enter Marks in Sub2=30 Enter Marks in Sub3=40 Total result=90
  • 39. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 39 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Inheritance 3. Hierarchal public class Shap { int width; int height; void setdata(int w, int h) { width=w; height=h; } } public class Rectangle extends Shap { int getArea() { return width*height; } } public class Triangle extends Shap { int getArea() { return (width*height)/2; } public static void main(String[] args) { Rectangle rect; Triangle tri; rect.setdata(5,7); tri.setdata(5,8); System.out.println(“Area of Rectangle="+rect.getArea()); System.out.prinln(“Area of Triangle="+tri.getArea()); } }
  • 40. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 40 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Polymorphism POLYMORPHISM 1) One thing can exhibits more than one form called polymorphism. 2) The ability to appear in more forms. 3) Polymorphism is a Greek word poly means many and morphism means forms. Types of Polymorphism 1. Compile Time Polymorphism (Early binding, Static binding) 2. Run Time Polymorphism (Late binding, Dynamic binding) Ex:-Method Overloading Ex:-Method Overriding A. Method overloading ( Compile Time Polymorphism ,Early binding, Static binding)  If any class has multiple method with same name but different parameters then they are said to be overloaded.  Function overloading allows to use the same name for different function to performed either same or different action in the same class.  Method overloading is usually used to enhance the readability of the program. If you have to perform one single operation but with different number or types of arguments, then you can simply overload the method There are two types of method overloading in java 1. By Changing number of arguments Class Cal { void add(int a, int b) { System.out.prinln(a+b); } void add(int a, int b, int c) { System.out.prinln(a+b+c); } public static void main(String args[]) { Cal C1=new Cal(); C1.add(2,4); C1.add(2,3,4); } } 2. By having different types of arguments Class Cal { void add(int a, int b) { System.out.prinln(a+b); } void add(float a, float b)
  • 41. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 41 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Polymorphism { System.out.prinln(a+b); } public static void main(String args[]) { Cal C1=new Cal(); C1.add(2,4); C1.add(2.5f,3.4f); } } B. Constructor overloading  Just like Method constructor can be overloaded.  We can define multiple constructors with different parameters to overload. Class Cal { void Cal(int a, int b) { System.out.prinln(a+b); } void Cal(int a, int b, int c) { System.out.prinln(a+b+c); } public static void main(String args[]) { Cal C1=new Cal(2,3); Cal C2=new Cal(3,4,5); } } B. Method Overriding  If we inherit a class into the derived class and provide a definition for one of the base class’s method again. The method is said to be overriding.  Requirement for method overriding  Inheritance should be there. method overriding cannot be done within a class, for this we require a derived class and a base class.  method signature should be same in base class and derived class. class Base { void show() { System.out.prinln(“Base Class”+”t"); } }
  • 42. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 42 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Polymorphism class Derived extends Base { void show() { System.out.prinln("Derived Class"); } public static void main(String[]args) { Base B=new Base(); Derived D=new Derived(); B.show(); D.show(); } } Output: Base Class Derived Class  In the above example, we are calling the overridden function using Base Class and Derived Class object. Base class object call base class version of function and derived class’s object call Derived class version of function. Difference between method overloading and method overriding in java There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: No. Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.
  • 43. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 43 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Abstraction ABSTRACTION Hiding the internal implementation details and highlighting the essential functionality to the user this mechanism is called abstraction. Ex: a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of services like withdraw, money transfer, mobile registration). b. Mobile phones (The mobile persons are hiding the internal circuit implementation and highlighting touch screen). Abstraction concepts are implemented in java by abstract class and interface 1. Abstract Class Abstract class is a java class which contains at least one abstract method. To specify the particular class is abstract and particular method is abstract method by using abstract modifier. For the abstract classes it is not possible to create an object. Because it contains the unimplemented methods. For any class if we don’t want instantiation then we have to declare that class as abstract i.e., for abstract classes instantiation (creation of object) is not possible. abstract class Test { abstract void m3(); } Abstract class:- class Test { abstract void m1(); abstract void m2(); abstract void m3(); } abstract class Add { abstract void add(int a, int b); } class Cal extends Add { void add(int a, int b) { System.out.println(a+b); } public static void main(String[] args) { Cal C1=new Cal(); C1.add(3,4); } }
  • 44. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 44 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Abstraction Abstract methods:- The method which is having declaration but not implementations such type of methods are called abstract Method. Hence every abstract method should end with “;”. The child classes are responsible to provide implementation for parent class abstract methods. public abstract Add { abstract void add(int a, int b);//it is abstract method which has no definition } class Cal { void add(int a, int b) { System.out.println(a+b); } public static void main(String[] args) { Cal C1=new Cal(); C1.add(3,4); } } 2. Interface 1. Interface is also one of the type of class it contains only abstract methods. 2. For the interfaces also .class files will be generated. 3. Each and every interface by default abstract hence it is not possible to create an object. 4. Interfaces not alternative for abstract class it is extension for abstract classes. 5. 100 % pure abstract class is called interface. 6. The Interface contains only abstract methods means unimplemented methods. 7. Interfaces giving the information about the functionalities it are not giving the information about internal implementation. 8. To provide implementation for abstract methods we have to take separate class that class we can called it as implementation class for that interface. 9. Interface can be implemented by using implements keyword. 10. For the interfaces also the inheritance concept is applicable. Syntax:- Interface interface-name Ex:- interface it1 Note: - if we are declaring or not By default interface methods are public abstract interface it1 abstract interface it1 { { Void m1(); Both are same public abstract void m1(); Void m2(); public abstract void m2(); } }
  • 45. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 45 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Abstraction interface Cal { void add(int a, int b); void sub(int a, int b); } class Solution implements Cal { void add(int a, int b) { System.out.prinln(a+b); } void sub(int a, int b) { System.out.prinln(a-b); } public static void main(String[] args) { Solution S1=new Solution()’ S1.add(); S1.sub(); } } Adaptor class:- It is a intermefdiate class between the interface and user defined class. And it contains empty implementation of interface methods. Limitation of interface advantage of adaptor classes interface it { void m1(); void m2(); ; ; void m100() } Class Test implements it { Must provide implementation of 100 methods otherwise compiler raise compilation error } interface it { void m1(); void m2(); ; ; void m100() ; }
  • 46. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 46 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Abstraction class Adaptor implements it { void m1() { } void m2() { } ; ; void m100() { } }; class Test implements it { must provide the 100 methods implementation }; class Test extends Adaptor { provide the implementation of required methods. };
  • 47. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 47 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Encapsulation Encapsulation The process of binding the data and code as a single unit is called encapsulation. We are able to provide more encapsulations by taking the private data(variables) members. To get and set the values from private members use getters and setters to set the data and to get the data. Ex:- class Encapsulation { private int sid; private int sname; public void setSid(int x) { this.sid=sid; } public int getSid() { return sid; } public void setSname(String sname) { this.sname=sname; } public String getSname() { return sname; } } To access encapsulated use fallowing code:- class Test { public static void main(String[] args) { Encapsulation e=new Encapsulation(); e.setSid(100); e.setSname("ratan"); int num=e.getSid(); String name=e.getSname(); System.out.println(num); System.out.println(name); } }
  • 48. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 48 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Super key-word Super Key-word Super:- Super keyword is used to represent 1) Call the Super class variable. 2) Call the super class constructor. 3) Call the super class methods. Super keyword is not required class Parent { int a=10; int b=20; } class Child extends Parent { int x=100; int y=200; void add(int i,int j) { System.out.println(i+j); System.out.println(x+y); System.out.println(a+b); } public static void main(String[] args) { Child c=new Child(); c.add(1000,2000); } } Super keyword is required class Test1 { int a=10; int b=20; }; class Test extends Test1 { int a=100; int b=200; void add(int a,int b) { System.out.println(a+b); System.out.println(this.a+this.b); System.out.println(super.a+super.b); }
  • 49. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 49 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Super key-word public static void main(String[] args) { Test t=new Test(); t.add(1000,2000); } } Command Line Arguments:- The arguments which are passed from command prompt is called command line arguments. We are passing command line arguments at the time program execution. Ex1:- class Test { public static void main(String[] args) { System.out.println(args.length); System.out.println(args[0]); System.out.println(args[1]); } } Compilation : Javac Test.java Execution : java Test a b c //a,b,c are the command line arguments Output : 3 a b Modifiers Modifiers are the keyword which define the accessibility or scope of a variable , class method in the program. 1. Public  This is the modifier applicable for classes, methods and variables (only for instance and static variables but not for local variables).  If a class is declared with public modifier then we can access that class from anywhere (within the package and outside of the package).  If we declare a member(variable) as a public then we can access that member from anywhere but Corresponding class should be visible i.e., before checking member visibility we have to check class visibility. Ex:- public class Test // public class can access anywhere { public int a=10; //public variable can access any where public void m1() //public method can access any where { System.out.println("public method access in any package"); }
  • 50. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 50 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Modifiers public static void main(String[] args) { Test t=new Test(); t.m1(); System.out.println(t.a); } } 2. Default:-  This is the modifier applicable for classes, methods and variables (only for instance and static variables but not for local variables).  If a class is declared with <default> modifier then we can access that class only within that current package but not from outside of the package.  Default access also known as a package level access.  The default modifier in the java language is default. class Test { void m1() { System.out.println("m1-method"); } void m2() { System.out.println("m2-method"); } public static void main(String[] args) { Test t=new Test(); t.m1(); t.m2(); } } in the above program we are not providing any modifier for the methods and classes at that situation the default modifier is available for methods and classes that is default modifier. Hence we can access that methods and class with in the package. 3. Private:-  Private is a modifier applicable for methods and variables. If a member declared as private then we can access that member only from within the current class.  If a method declare as a private we can access that method only within the class. it is not possible to call even in the child classes also. class Test { private void m1() { System.out.println("we can access this method only with in this class"); }
  • 51. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 51 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Modifiers public static void main(String[] args) { Test t=new Test(); t.m1(); } } 4. Protected :-  If a member declared as protected then we can access that member with in the current package anywhere but outside package only in child classes.  But from outside package we can access protected members only by using child reference. If we try to use parent reference we will get compile time error.  Members can be accesses only from instance area directly i.e., from static area we can’t access instance members directly otherwise we will get compile time error. Ex:-demonstrate the user defined packages and imports. Aims project source file:- package calculator; public class Cal { protected void add(int a, int b) { System.out.println(a+b); } protected void sub(int a, int b) { System.out.println(a-b); } protected void multi(int a, int b) { System.out.println(a*b); } } import calculator.Cal; public class Solution extends Cal { public static void main(String[] args) { Solution S1=new Solution(); S1.add(3,4); S1.sub(3,2); S1.multi(3,5); } }
  • 52. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 52 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String String 1) String is a final class it is present in java.lang package. 2) String is nothing but a group of characters or character array. 3) Once we are creating String object it is not possible to do the modifications on existing object called immutability nature. Constructors of string class:- 1) String str=new String(java.lang.String); This constructor takes the String as a argument. Ex:- String str=new String(“Aims”); System.out.println(str);//Aims 2) Stirng str=new String(char[]); This constructor take the array of characters as a argument. Ex:- char[] ch={'a','b','c','d'}; String str1=new String(ch); System.out.println(str1); //abcd 3) String str=new String(char[] ,int ,int ); This contractor takes the array of characters with starting index and ending index. First int represent the starting position Second int represent the ending position. Ex:- char[] ch={'a','b','c','d'}; String str1=new String(ch,1,3); System.out.println(str1);//bcd Ex:- class Test { public static void main(String[] args) { String str="Manish"; System.out.println(str); //Manish String str1=new String("Manish"); System.out.println(str1); //Manish String str2=new String(str1); System.out.println(str2); char[] ch={'a','i','m','s'}; String str3=new String(ch); System.out.println(str3); //aims char[] ch1={'t','u','t','o','r','i','a',’l’}; String str4=new String(ch1,1,5); System.out.println(str4); //utorial } }
  • 53. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 53 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String String is immutability nature:- Once we are creating string object it is not possible to do the modifications on the existing object is called immutability nature. public class Test { public static void main(String[] args) { String str1=new String("Aims"); str1.concat("Tutorial”); System.out.println(str1); } } OUTPUT: Aims String class Methods Method Description 1 char charAt(int index) returns char value for the particular index 2 int length() returns string length 3 String concat(String str) concatenates specified string 4 int indexOf(int ch) returns specified char value index 5 String toLowerCase() returns string in lowercase. 6 String toUpperCase() returns string in uppercase. 7 String trim() removes beginning and ending spaces of this string. 8 static String valueOf(int value) converts given type into string. It is overloaded. String charAt() The java string charAt() method returns a char value at the given index number. The index number starts from 0 public class CharAtExample { public static void main(String args[]) { String name="AimsTutorial"; char ch=name.charAt(4); //returns the char value at the 4th index System.out.println(ch);
  • 54. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 54 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String } } String length() The java string length() method length of the string. It returns count of total number of characters. The length of java string is same as the unicode units of the string. public class LengthExample { public static void main(String args[]) { String s1="java"; String s2="python"; System.out.println("string length is: "+s1.length()); //10 is the length of javatpoint string System.out.println("string length is: "+s2.length()); //6 is the length of python string } } String concat() The java string concat() method combines specified string at the end of this string. It returns combined string. It is like appending another string. public class ConcatExample { public static void main(String args[]) { String s1="java string"; s1.concat("is immutable"); System.out.println(s1); s1=s1.concat(" is immutable so assign it explicitly"); System.out.println(s1); } } String indexOf() The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero. public class IndexOfExample { public static void main(String args[]) { int index4=s1.indexOf('s');//returns the index of s char value System.out.println(index4);//3 } }
  • 55. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 55 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String String toLowerCase() The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter. public class StringLowerExample { public static void main(String args[]) { String s1="AMIS TUTORIAL"; String s1lower=s1.toLowerCase(); System.out.println(s1lower); } } String toUpperCase The java string toUpperCase() method returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter. public class StringUpperExample { public static void main(String args[]) { String s1="hello string"; String s1upper=s1.toUpperCase(); System.out.println(s1upper); } } String trim The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is 'u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. public class StringTrimExample { public static void main(String args[]) { String s1=" hello student "; System.out.println(s1+"welcome");//without trim() System.out.println(s1.trim()+"in aims");//with trim() } }
  • 56. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 56 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String StringBuffer 1. String Buffer is a class present in the java.lang package. 2. StringBuffer is a final class so it can’t be inherited. 3. StringBuffer is a mutable class so it is possible to change the content in the same location. 4. StringBuffer .equals() method is used for reference comparison. What is mutable string A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. Constructors:- 1. StringBuffer sb=new StringBuffer(); 2. StringBuffer sb1=new StringBuffer(int capacity); 3. StringBuffer sb2=new StringBuffer(String str); 1) StringBuffer append() method The append() method concatenates the given argument with this string. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } 2) StringBuffer insert() method The insert() method inserts the given string with this string at the given position. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }
  • 57. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 57 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String 3) StringBuffer replace() method The replace() method replaces the given string from the specified beginIndex and endIndex. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo } } 4) StringBuffer delete() method The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3); System.out.println(sb);//prints Hlo } } 5) StringBuffer reverse() method The reverse() method of StringBuilder class reverses the current string. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
  • 58. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 58 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String 6) StringBuffer capacity() method The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34. class A { public static void main(String args[]) { StringBuffer sb=new StringBuffer(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 } } Java StringBuilder class Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5. Important Constructors of StringBuilder class 1. StringBuilder(): creates an empty string Builder with the initial capacity of 16. 2. StringBuilder(String str): creates a string Builder with the specified string. 3. StringBuilder(int length): creates an empty string Builder with the specified capacity as length. 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 when you concat too many strings because every time it creates new StringBuffer is fast and consumes less memory when you cancat
  • 59. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 59 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com String instance. strings. 3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class. Difference between StringBuffer and StringBuilder There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below: No. StringBuffer StringBuilder 1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. 2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer. Java toString() method If you want to represent any object as a string, toString() method comes into existence. The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation. class Student { int rollno; String name; String city; Student(int rollno, String name, String city) { this.rollno=rollno; this.name=name; this.city=city; } public static void main(String args[]) { Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println(s1.toString); System.out.println(s2);//compiler writes here s2.toString() } }
  • 60. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 60 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Wrapper Classes Wrapper classes 1) To represent primitive data types as a Object form we required some classes these classes are called wrapper classes. 2) All wrapper classes present in the java.lang package. 3) Int,byte…. Acts as a primitives we can make the primitives into the objects is called wrapper calless the the wrapper classes are Integer,Short-----. 4) We are having 8 primitive data types hence sun peoples are providing 8 wrapper classes. Data types and corresponding wrapper classes:- byte ----- Byte short ----- Short int ----- Integer long ----- Long float ----- Float double ----- Double boolean ----- Boolean char ------ Character 6) Byte,Short,Integer,Long,Float,Double these are child classes of Number class. Constructors of wrapper classes:- All most all wrapper classes contain two constructors:- 1. Integer i=new Integer(10); 2. Integer i=new Integer(“10”); Primitives Wrapper classes Fallowing constructor arguments byte short int long float double char Boolean Byte Short Integer Long Float Double Character Boolean Byte or String Short or String Int or String Long or String Float or double or String double or String Char Boolean or String
  • 61. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 61 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Wrapper Classes Wrapper classes hierarchy The main importance of wrapper classes:- 1. To convert a data types into the object means we are giving object from data types by using constructor. 2. To convert String into the data types by using parsexxx() method Utility methods:- 1. valueOf() 2. xxxValue() 3. parsexxx() 1) valueOf():- By using valueof() we are creating wrapper object and it is a alternative to the constructor. class Test { public static void main(String[] args) { //by using constructor converting String/primitive to wrapper object Integer i=new Integer(10); System.out.println(i); //by using valueOf() converting String/primitive to the wrapper object Boolean b=Boolean.valueOf("true"); System.out.println(b); } }
  • 62. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 62 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Wrapper Classes XxxValue():- by using XXXValue() method we are converting wrapper objects into the corresponding primitive values class Test { public static void main(String[] args) { Integer i=Integer.valueOf(150); System.out.println("byte value :"+i.byteValue());//-106 System.out.println("short value :"+i.shortValue());//150 System.out.println("int value :"+i.intValue());//150 System.out.println("long value :"+i.longValue());//150 System.out.println("float value :"+i.floatValue());//150.0 System.out.println("double value :"+i.doubleValue());//150.0 Character c=new Character('s'); char ch=c.charValue(); System.out.println(ch); Boolean b=new Boolean(false); boolean bb=b.booleanValue(); System.out.println(bb); } } parseXXX():- by using above method we are converting String into the corresponding primitive. class Test { public static void main(String[] args) { String str1="10"; String str2="20"; System.out.println(str1+str2);//1020 int a=Integer.parseInt(str1); float f=Float.parseFloat(str2); System.out.println(a+f);//30.0 } } Autoboxing and Autounboxing:-(introduced in the 1.5 version) Until 1.4 version we are not allowed to place primitive in the wrapper and wrapper in the place of primitive. The programmer is responsible person to do the explicit conversion primitive to the wrapper and wrapper to the primitive. Autoboxing:- Integer i=10; System.out.println(i); The above statement does not work on the 1.4 and below versions. The auto conversion of the primitive into the Wrapper object is called the autoboxing these conversions done by compiler at the time of compilation.
  • 63. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 63 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Wrapper Classes Autounboxing:- int a=new Integer(100); System.out.println(a); The auto conversion of the wrapper object to the primitive value is called autounboxing and these conversions are done by compiler at the time of compilation. Ex :- class Test { static Integer i=10;//i is wrapper object static int j;//j is primitive variable static void print(int i) { j=i; System.out.println(j); } public static void main(String[] args) { print(i); System.out.println(j); } } Automatic conversion of the primitive to wrapper and wrapper to the primitive:-
  • 64. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 64 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package Java.io package  Java io(input/output) is used to process to the input and produced the output.  Java uses the concept of stream and makes fast I/O operation.  The java.io package is the collection of classes which are requires to input and output.  We can perform file handling in java by Java I/O API. Stream A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. In java, 3 streams are created for us automatically. All these streams are attached with console. 1) System.out: standard output stream 2) System.in: standard input stream 3) System.err: standard error stream System.out.println("simple message"); System.err.println("error message"); int i=System.in.read();//returns ASCII code of 1st character System.out.println((char)i);//will print the character OutputStream Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. InputStream Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket. Let's understand working of Java OutputStream and InputStream by the figure given below.
  • 65. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 65 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package OutputStream class OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Useful methods of OutputStream Method Description 1) public void write(int)throws IOException is used to write a byte to the current output stream. 2) public void write(byte[])throws IOException is used to write an array of byte to the current output stream. 3) public void flush()throws IOException flushes the current output stream. 4) public void close()throws IOException is used to close the current output stream. OutputStream Hierarchy
  • 66. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 66 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package InputStream class InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes. Useful methods of InputStream Method Description 1) public abstract int read()throws IOException reads the next byte of data from the input stream. It returns -1 at the end of file. 2) public int available()throws IOException returns an estimate of the number of bytes that can be read from the current input stream. 3) public void close()throws IOException is used to close the current input stream. InputStream Hierarchy
  • 67. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 67 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package FileOutputStream Class Java FileOutputStream is an output stream used for writing data to a file. If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutStream. FileOutputStream class methods Method Description protected void finalize() It is sued to clean up the connection with the file output stream. void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output stream. void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the file output stream. void write(int b) It is used to write the specified byte to the file output stream. FileChannel getChannel() It is used to return the file channel object associated with the file output stream. FileDescriptor getFD() It is used to return the file descriptor associated with the stream. void close() It is used to closes the file output stream. Java FileOutputStream Example 1: write byte import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); fout.write(65); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } } Output: Success...(this is the output which show at consol after the execution of the program)
  • 68. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 68 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package The content of a text file testout.txt is set with the data A. testout.txt A (this is data which is written by the program in the testout.txt file) Java FileOutputStream example 2: write string import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); String s="Welcome to Aims Tutorial."; byte b[]=s.getBytes();//converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } } Output: Success... The content of a text file testout.txt is set with the data Welcome to Aims Tutorial. testout.txt Welcome to Aims Tutorial. FileInputStream Class Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character- stream data. But, for reading streams of characters, it is recommended to use FileReader class. Java FileInputStream class methods Method Description int available() It is used to return the estimated number of bytes that can be read from the input stream. int read() It is used to read the byte of data from the input stream. int read(byte[] b) It is used to read up to b.length bytes of data from the input stream. int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
  • 69. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 69 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package long skip(long x) It is used to skip over and discards x bytes of data from the input stream. FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream. FileDescriptor getFD() It is used to return the FileDescriptor object. protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream. void close() It is used to closes the stream. Java FileInputStream example 1: read single character import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=fin.read(); System.out.print((char)i); fin.close(); }catch(Exception e){System.out.println(e);} } } Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content: Welcome to Aims Tutorial. After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character. Output: Welcome to AimsTutorial
  • 70. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 70 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package Java FileInputStream example 2: read all characters package com.javatpoint; import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]){ try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=0; while((i=fin.read())!=-1){ System.out.print((char)i); } fin.close(); }catch(Exception e){System.out.println(e);} } } Output: Welcome to Aims Tutorial BufferedOutputStream Class Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream: OutputStream os= new BufferedOutputStream(new FileOutputStream("D:IO Packag etestout.txt")); Java BufferedOutputStream class constructors Constructor Description BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to the specified output stream. BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.
  • 71. Aims Tutorial Oriental Bank of Commerce H.No.:69/339 VT Road Ward 27, Mansarovar Jaipur (Rajasthan) 302020 Contact No: +91-8947920041 P a g e | 71 By: Manish Swarnkar 9887474850 Java Tutorial By:Manish Swarnkar Contact No:9887474850 manishsony4u@gmail.com Java.io package Java BufferedOutputStream class methods Method Description void write(int b) It writes the specified byte to the buffered output stream. void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset void flush() It flushes the buffered output stream. Example of BufferedOutputStream class: In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another. package com.javatpoint; import java.io.*; public class BufferedOutputStreamExample{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); BufferedOutputStream bout=new BufferedOutputStream(fout); String s="Welcome to Aims Tutorial."; byte b[]=s.getBytes(); bout.write(b); bout.flush(); bout.close(); fout.close(); System.out.println("success"); } } Output: Success testout.txt Welcome to Aims Tutorial.