What are the major features of Java programming?
Object Oriented
In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
Simple Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific machines
while Java is a write once, run anywhere language. A platform is the hardware
or software environment in which a program runs.
There are two types of platforms software-based and
hardware-based. Java provides a software-based platform.
Java code can be run on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler
and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop
virus-free systems. Java is secured because:No explicit pointer.
Robust
Robust simply means strong. Java is robust because:
oIt uses strong memory management.
oThere are exception handling and the type checking mechanism in
Java. All these points make Java robust.
Portable
Java is portable because it facilitates you to carry the Java
bytecode to any platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.
Distributed
Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
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.
Dynamic
Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand. It also supports functions from
its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory
management (garbage collection).
C++ vs Java
C++
|
Java
|
C++
is platform-dependent.
|
Java
is platform-independent.
|
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.
|
C++
supports the goto statement.
|
Java
doesn't support the goto statement.
|
C++
supports multiple inheritance.
|
Java
doesn't support multiple inheritance through class. It can be achieved
by interfaces in
java.
|
C++
supports operator
overloading.
|
Java
doesn't support operator overloading.
|
C++
supports pointers.
You can write pointer program in C++.
|
Java
supports pointer internally. However, you can't write the pointer program in
java. It means java has restricted pointer support in java.
|
C++
uses compiler only. C++ is compiled and run using the compiler which converts
source code into machine code so, C++ is platform dependent.
|
Java
uses compiler and interpreter both. Java source code is converted into
bytecode at compilation time. The interpreter executes this bytecode at
runtime and produces output. Java is interpreted that is why it is platform
independent.
|
C++
supports both call by value and call by reference.
|
Java
supports call by value only. There is no call by reference in java.
|
C++
supports structures and unions.
|
Java
doesn't support structures and unions.
|
C++
doesn't have built-in support for threads. It relies on third-party libraries
for thread support.
|
Java
has built-in thread support.
|
C++
doesn't support documentation comment.
|
Java
supports documentation comment (/** ... */) to create documentation for java
source code.
|
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.
|
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.
|
C++
creates a new inheritance tree always.
|
Java
uses a single inheritance tree always because all classes are the child of
Object class in java. The object class is the root of the inheritance tree
in java.
|
C++
is nearer to hardware.
|
Java
is not so interactive with hardware.
|
C++
is an object-oriented language. However, in C language, single root hierarchy
is not possible.
|
Java
is also an object-oriented language.
However, everything (except fundamental types) is an object in Java. It is a
single root hierarchy as everything gets derived from java.lang.Object.
|
JDK: Java Development Kit
JDK is an acronym for Java Development Kit. The
Java Development Kit (JDK) is a software development environment which is used
to develop java applications and applets. It physically exists. It contains JRE
+ development tools.
JDK is an implementation of any one of the below
given Java Platforms released by Oracle corporation:
- Standard
Edition Java Platform
- Enterprise
Edition Java Platform
- Micro
Edition Java Platform
The JDK contains a private Java Virtual Machine
(JVM) and a few other resources such as an interpreter/loader (Java), a
compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc.
to complete the development of a Java Application
Components of JDK
Following is a list of
primary components of JDK:
appletviewer:
|
This tool is used to run and debug Java
applets without a web browser.
|
java:
|
The loader for Java applications. This tool is
an interpreter and can interpret the class files generated by the javac
compiler. Now a single launcher is used for both development and deployment.
The old deployment launcher, jre, no longer comes with Sun JDK, and instead
it has been replaced by this new java loader.
|
javac:
|
It specifies the Java compiler, which converts
source code into Java bytecode.
|
javadoc:
|
The documentation generator, which
automatically generates documentation from source code comments
|
jar:
|
The specifies the archiver, which packages
related class libraries into a single JAR file. This tool also helps manage
JAR files.
|
javap:
|
the class file disassembler.
|
jdb:
|
the debugger.
|
OOPs (Object-Oriented Programming System)
Object
Any entity that has
state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be
defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of
each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
Example: A dog is an
object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
Class
Collection of objects
is called class. It is a logical entity.
A class can also be
defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
Inheritance
When one object
acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
If one task is
performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.
In Java, we use method
overloading and method overriding to achieve polymorphism.
Another example can be
to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal
details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
In Java, we use abstract
class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping)
code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the
example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Java Structure:-
public class Simple
{
public static void main(String args[])
{
System.out.println("hello");
}
}
save this file as Simple.java
To compile:javac Simple.java
To execute:java Simple
Compilation Flow:
When we compile Java program using javac tool, java compiler
converts the source code into byte code.
Parameters used in First Java Program
class keyword
is used to declare a class in java.
public keyword
is an access modifier which represents visibility. It means it is visible to
all.
static is a
keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an
object to invoke the static method.
The main method is executed by the JVM, so
it doesn't require to create an object to invoke the main method. So it saves memory.
void is the
return type of the method. It means it doesn't return any value.
main
represents the starting point of the program.
String[] args is used
for command line argument.
.System.out.println() is used
to print statement. Here, System is a class, out is the object of PrintStream
class, println() is the method of PrintStream class.
Java
Comments
The
java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation
about the variable, method, class or any statement. It can also be used to hide
program code for specific time.
Types
of Java Comments
There
are 3 types of comments in java.
1.Single
Line Comment
public
class CommentExample1
{
public
static void main(String[] args)
{
int
i=10;//Here, i is a variable
System.out.println(i);
}
}
2.Multi
Line Comment
public
class CommentExample2
{
public
static void main(String[] args)
{
/*
Let's declare and
print
variable in java. */
int
i=10;
System.out.println(i);
}
}
3.Documentation
Comment
/**
The Calculator class provides methods to get addition and subtraction of given
2 numbers.*/
public
class Calculator
{
/**
The add() method returns addition of given numbers.*/
public
static int add(int a, int b)
{
return
a+b;
}
/**
The sub() method returns subtraction of given numbers.*/
public
static int sub(int a, int b)
{
return
a-b;
}
}
What are tokens in Java?
Java tokens are smallest elements of a
program which are identified by the compiler. Tokens in java include
identifiers, keywords, literals, operators and, separators.
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
Java Naming conventions:-
Java
naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.
Class:-
It
should start with the uppercase letter.
It
should be a noun such as Color, Button, System, Thread, etc.
Use
appropriate words, instead of acronyms
public
class Employee
{
//code
snippet
}
Interface:-
It
should start with the uppercase letter.
It
should be an adjective such as Runnable, Remote, ActionListener.
Use
appropriate words, instead of acronyms.
Example:
-
interface
Printable
{
//code
snippet
}
Method:-
It
should start with lowercase letter.
It
should be a verb such as main(), print(), println().
If
the name contains multiple words, start it with a lowercase letter followed by
an uppercase letter such as actionPerformed().
Example:-
class Employee
{
//method
void
draw()
{
//code
snippet
}
}
Variable:-
It
should start with a lowercase letter such as id, name.
It
should not start with the special characters like & (ampersand), $
(dollar), _ (underscore).
If
the name contains multiple words, start it with the lowercase letter followed
by an uppercase letter such as firstName, lastName.
Avoid
using one-character variables such as x, y, z.
Example
:-
class Employee
{
//variable
int
id;
//code
snippet
}
Package:-
It
should be a lowercase letter such as java, lang.
If
the name contains multiple words, it should be separated by dots (.) such as
java.util, java.lang.
Example
:-
package
com.javatpoint; //package
class
Employee
{
//code
snippet
}
Constant:-
It
should be in uppercase letters such as RED, YELLOW.
If
the name contains multiple words, it should be separated by an underscore(_)
such as MAX_PRIORITY.
It
may contain digits but not as the first letter.
Example
:-
class
Employee
{
//constant
static final int MIN_AGE = 18;
//code
snippet
}
Data Types
in Java
Data types
specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1.Primitive
data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2.Non-primitive
data types: The non-primitive data types include Classes, Interfaces, and
Arrays
Primitive
Data Types
•Byte data
type is an 8-bit signed two's complement integer
•Minimum
value is -128 and Maximum value is 127
•Default
value is 0
short
•Short data
type is a 16-bit signed two's complement integer
•Minimum
value is -32,768 (-2^15) and Maximum value is 32,767 (inclusive) (2^15 -1)
•Default
value is 0.
int
•Int data
type is a 32-bit signed two's complement integer.
•Minimum
value is - 2,147,483,648 (-2^31) and Maximum value is 2,147,483,647(inclusive)
(2^31 -1)
•The default
value is 0
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
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
•Default
value is 0.0d
boolean
•boolean
data type represents one bit of information
•There are
only two possible values: true and false
•Default
value is false
char
•char data
type is a single 16-bit Unicode character
•Char data
type is used to store any character
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");
Rules of declaring variables in java
•A variable name can
consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two
special characters such as underscore and dollar Sign.
•The first character
must be a letter.
•Blank spaces cannot be
used in variable names.
•Java keywords cannot be
used as variable names.
•Variable names are
case-sensitive.
Scope of Variables
Local Variables
A variable that is
declared within the method that is called local variables. It is defined in
method or other statements, such as defined and used within the cache block,
and outside the block or method, the variable cannot be used.
Instance variables
A non-static variable
that is declared within the class but not in the method is called instance
variable. Instance variables are related to a specific object; they can access
class variables.
Class/Static variables
A variable that is
declared with static keyword in a class but not in the method is called static
or class variable.
class A
{
int amount = 100; //instance variable
static int pin = 2315; //static variable
public static void main(String[] args)
{
int age = 35; //local variable
}
}
Constants in java are
fixed values those are not changed during the Execution of program java
supports several types of Constants those are :
1.Integer Constants
2.Real Constants
3.Single Character
Constants
4.String Constants
5.Backslash Character
Constants
Integer Constants
Integer Constants
refers to a Sequence of digits which Includes only negative or positive Values
and many other things those are as follows
Example
1.Ocatal Integer
Constants
2.Hexadecimal Integer
Constants
Decimal Integer Constants
Decimal constant
consists of a set of digits 0 through 9, preceded by an optional –or + sign.
Eg. 1,3,7,8
Octal Integer
Constants
An octal integer
constant consists of any combination of digits from the set 0 through 7, with
an leading 0. Eg.038,320,0456
Hexadecimal Integer
Constants
An octal integer
constant consists of any combination of digits from the set 0 through F, with
an leading 0x or 0X. eg. 0x4,0x456
Real Constants
Integer numbers are
unable to represent distance, height, temperature, price, and so on. These
informations are contaning fractional parts or real parts like 56.890. Such
numbers are called Real or Floating Point Contants
Example
•A Real Constant must have at Least one Digit
•it must have a Decimal value
•it could be either
positive or Negative
•if no sign is
Specified then it should be treated as Positive
•No Spaces and Commas
are allowed in Name
Like 251, 234.890 etc
are Real Constants
In The Exponential
Form of Representation the Real Constant is Represented in the two Parts The
part before appearing e is called mantissa whereas the part following e is
called Exponent.
•In Real Constant The
Mantissa and Exponent Part should be Separated by letter e
•The Mantissa Part
have may have either positive or Negative Sign
•Default Sign is
Positive
Single Character
Constants
A Character is Single
Alphabet a single digit or a Single Symbol that is enclosed within Single
inverted commas.
1.Character Constant
Can hold Single character at a time.
2.Contains Single
Character Closed within a pair of Single Quote Marks
3.Single Character is
smallest Character Data Type in C.
4.Integer
Representation: Character Constant reprent by Unicode
5.It is Possible to
Perform Arithmetic Operations on Character Constants
String Constants
String is a Sequence
of Characters Enclosed between double Quotes These Characters may be digits,
Alphabets Like "Hello", "1234" etc.
1.The string is "Sequence
of Characters".
2.String Constant is
written in Pair of Double Quotes.
3.The string is
declared as Array of Characters.
4.In C, String data
type is not available.
5.Single Character
String Does not have Equivalent unicode Value
Example
"a"
->String with Single Character
"Ali"->
String With Multiple Characters
“123"-> String
With Digits
Backslash Character
Constants
Java Also Supports
Backslash Constants those are used in output methods For Example \n is used for
new line Character These are also Called as escape Sequence or backslash
character Constants For Example :
1.Although it consists
of two characters, it represents a single character.
2.Each escape sequence
has unicode value.
3.Each and Every
combination starts with back slash()
4.They are
non-printable characters.
5.It can also be
expressed in terms of octal digits or hexadecimal sequence.
StringBuffer
class
Java
StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it
can be changed.
Constructors
of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial
capacity of 16.
StringBuffer(String
str) creates a string buffer with
the specified string.
StringBuffer(int
capacity) creates an empty string
buffer with the specified capacity as length.
StringBuffer
append() method
The append()
method concatenates the given argument with this string.
class
StringBufferExample
{
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
}
}
StringBuffer
insert() method
The insert()
method inserts the given string with this string at the given position.
class
StringBufferExample2
{
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
}
}
StringBuffer
replace() method
The
replace() method replaces the given string from the specified beginIndex and
endIndex.
class
StringBufferExample3
{
public
static void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints
HJavalo
}
}
StringBuffer
delete() method
The delete()
method of StringBuffer class deletes the string from the specified beginIndex
to endIndex.
class
StringBufferExample4
{
public
static void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints
Hlo
}
}
StringBuffer
reverse() method
The
reverse() method of StringBuilder class reverses the current string.
class
StringBufferExample5
{
public static
void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints
olleH
}
}
Java String
class methods
The
java.lang.String class provides a lot of methods to work on string. By the help
of these methods, we can perform operations on string such as trimming,
concatenating, converting, comparing, replacing strings etc.
Java String
toUpperCase() and toLowerCase() method
The java
string toUpperCase() method converts this string into uppercase letter and
string toLowerCase() method into lowercase letter.
public class
Testmethodofstringclass
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no
change in original)
}
}
Java String
trim() method
The string
trim() method eliminates white spaces before and after string.
public class
Testmethodofstringclass1
{
public
static void main(String args[]){
String
s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
Java String
charAt() method
The string
charAt() method returns a character at specified index.
public class
Testmethodofstringclass3
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Java String length()
method
The string
length() method returns length of the string.
public class
Testmethodofstringclass4
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.length());//6
}
}
Java Arrays
Normally, an
array is a collection of similar type of elements which have a contiguous
memory location.
Java array
is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in
Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Types of
Array in java
There are
two types of array.
oSingle
Dimensional Array
oMultidimensional
Array
Single
Dimensional Array in Java
class
Testarray
{
public
static void main(String args[])
{
int a[]=new
int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing
array
for(int
i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Compile by:
javac Testarray.java
Run by: java
Testarray
10
20
70
40
50
Multidimensional
Array in Java
In such
case, data is stored in row and column based index (also known as matrix form).
class
Testarray3
{
public
static void main(String args[])
{
//declaring
and initializing 2D array
int
arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing
2D array
for(int
i=0;i<3;i++)
{
for(int
j=0;j<3;j++)
{
System.out.print(arr[i][j]+"
");
}
System.out.println();
}
}
}
Compile by:
javac Testarray3.java
Run by: java
Testarray3
1 2 3
2 4 5
4 4 5
Declaration,
Instantiation and Initialization of Java Array
We can
declare, instantiate and initialize the java array together by:
int
a[]={33,3,4,5};//declaration, instantiation and initialization
class
Testarray1
{
public
static void main(String args[])
{
int
a[]={33,3,4,5};//declaration, instantiation and initialization
//printing
array
for(int
i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Compile by:
javac Testarray1.java
Run by: java
Testarray1
33
3
4
5
Control
statement
Java If-else
Statement
The Java if
statement is used to test the condition. It checks boolean condition: true or
false.
Java if
Statement
The Java if
statement tests the condition. It executes the if block if condition is true.
public class
IfExample
{
public
static void main(String[] args)
{
int
age=20;
if(age>18)
{
System.out.print("Age
is greater than 18");
}
}
}
Compile by:
javac IfExample.java
Run by: java
IfExample
Age is
greater than 18
Java if-else
Statement
The Java
if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
public class
IfElseExample
{
public
static void main(String[] args)
{
int
number=13;
if(number%2==0)
{
System.out.println("even
number");
}
else
{
System.out.println("odd
number");
}
}
}
Compile by:
javac IfElseExample.java
Run by: java
IfElseExample
odd number
Java Switch
Statement
The Java
switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement. The switch statement works with byte, short, int,
long, enum types, String and some wrapper types like Byte, Short, Int, and
Long. Since Java 7, you can use strings in the switch statement.
public class
SwitchExample
{
public
static void main(String[] args)
{
int
number=20;
switch(number)
{
case 10:
System.out.println("10");break;
case 20:
System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not
in 10, 20 or 30");
}
}
}
Compile by:
javac SwitchExample.java
Run by: java
SwitchExample
20
Loops in
Java
In
programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true. There are
three types of loops in java.
ofor loop
owhile loop
odo-while
loop
For loop
The Java for
loop is a control flow statement that iterates a part of the programs multiple
times.
When to
use:- If the number of iteration is fixed, it is recommended to use for loop.
Syntax:-for(init;condition;incr/decr)
{ // code to be executed }
public class
ForExample
{
public
static void main(String[] args)
{
for(int
i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Compile by:
javac ForExample.java
Run by: java
ForExample
1
2
3
4
5
6
7
8
9
10
while loop
The Java
while loop is a control flow statement that executes a part of the programs
repeatedly on the basis of given boolean condition.
When to use
:-If the number of iteration is not fixed, it is recommended to use while loop.
Syntax
:-while(condition)
{
//code to be
executed
}
public class
WhileExample
{
public
static void main(String[] args)
{
int
i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Compile by:
javac WhileExample.java
Run by: java
WhileExample
1
2
3
4
5
6
7
8
9
10
do while
loop
The Java do
while loop is a control flow statement that executes a part of the programs at
least once and the further execution depends upon the given boolean condition.
When to
use:- If the number of iteration is not fixed and you must have to execute the
loop at least once, it is recommended to use the do-while loop.
Synax:-
do{
//code to be
executed
}while(condition);
public class
DoWhileExample
{
public
static void main(String[] args)
{
int
i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Compile by:
javac DoWhileExample.java
Run by: java
DoWhileExample
1
2
3
4
5
6
7
8
9
10
public class Simple
{
public static void main(String args[])
{
System.out.println("hello");
}
}
save this file as Simple.java
To compile:javac Simple.java
To execute:java Simple
Compilation Flow:
When we compile Java program using javac tool, java compiler
converts the source code into byte code.
Parameters used in First Java Program
class keyword
is used to declare a class in java.
public keyword
is an access modifier which represents visibility. It means it is visible to
all.
static is a
keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an
object to invoke the static method.
The main method is executed by the JVM, so
it doesn't require to create an object to invoke the main method. So it saves memory.
void is the
return type of the method. It means it doesn't return any value.
main
represents the starting point of the program.
String[] args is used
for command line argument.
.System.out.println() is used
to print statement. Here, System is a class, out is the object of PrintStream
class, println() is the method of PrintStream class.
Java
Comments
The
java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation
about the variable, method, class or any statement. It can also be used to hide
program code for specific time.
Types
of Java Comments
There
are 3 types of comments in java.
1.Single
Line Comment
public
class CommentExample1
{
public
static void main(String[] args)
{
int
i=10;//Here, i is a variable
System.out.println(i);
}
}
2.Multi
Line Comment
public
class CommentExample2
{
public
static void main(String[] args)
{
/*
Let's declare and
print
variable in java. */
int
i=10;
System.out.println(i);
}
}
3.Documentation
Comment
/**
The Calculator class provides methods to get addition and subtraction of given
2 numbers.*/
public
class Calculator
{
/**
The add() method returns addition of given numbers.*/
public
static int add(int a, int b)
{
return
a+b;
}
/**
The sub() method returns subtraction of given numbers.*/
public
static int sub(int a, int b)
{
return
a-b;
}
}
What are tokens in Java?
Java tokens are smallest elements of a
program which are identified by the compiler. Tokens in java include
identifiers, keywords, literals, operators and, separators.
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
Java Naming conventions:-
Class/Static variables
Java
naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.
Class:-
It
should start with the uppercase letter.
It
should be a noun such as Color, Button, System, Thread, etc.
Use
appropriate words, instead of acronyms
public
class Employee
{
//code
snippet
}
Interface:-
It
should start with the uppercase letter.
It
should be an adjective such as Runnable, Remote, ActionListener.
Use
appropriate words, instead of acronyms.
Example:
-
interface
Printable
{
//code
snippet
}
Method:-
It
should start with lowercase letter.
It
should be a verb such as main(), print(), println().
If
the name contains multiple words, start it with a lowercase letter followed by
an uppercase letter such as actionPerformed().
Example:-
class Employee
{
//method
void
draw()
{
//code
snippet
}
}
Variable:-
It
should start with a lowercase letter such as id, name.
It
should not start with the special characters like & (ampersand), $
(dollar), _ (underscore).
If
the name contains multiple words, start it with the lowercase letter followed
by an uppercase letter such as firstName, lastName.
Avoid
using one-character variables such as x, y, z.
Example
:-
class Employee
{
//variable
int
id;
//code
snippet
}
Package:-
It
should be a lowercase letter such as java, lang.
If
the name contains multiple words, it should be separated by dots (.) such as
java.util, java.lang.
Example
:-
package
com.javatpoint; //package
class
Employee
{
//code
snippet
}
Constant:-
It
should be in uppercase letters such as RED, YELLOW.
If
the name contains multiple words, it should be separated by an underscore(_)
such as MAX_PRIORITY.
It
may contain digits but not as the first letter.
Example
:-
class
Employee
{
//constant
static final int MIN_AGE = 18;
//code
snippet
}
Data Types
in Java
Data types
specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1.Primitive
data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2.Non-primitive
data types: The non-primitive data types include Classes, Interfaces, and
Arrays
Primitive
Data Types
•Byte data
type is an 8-bit signed two's complement integer
•Minimum
value is -128 and Maximum value is 127
•Default
value is 0
short
•Short data
type is a 16-bit signed two's complement integer
•Minimum
value is -32,768 (-2^15) and Maximum value is 32,767 (inclusive) (2^15 -1)
•Default
value is 0.
int
•Int data
type is a 32-bit signed two's complement integer.
•Minimum
value is - 2,147,483,648 (-2^31) and Maximum value is 2,147,483,647(inclusive)
(2^31 -1)
•The default
value is 0
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
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
•Default
value is 0.0d
boolean
•boolean
data type represents one bit of information
•There are
only two possible values: true and false
•Default
value is false
char
•char data
type is a single 16-bit Unicode character
•Char data
type is used to store any character
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");
Rules of declaring variables in java
•A variable name can
consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and two
special characters such as underscore and dollar Sign.
•The first character
must be a letter.
•Blank spaces cannot be
used in variable names.
•Java keywords cannot be
used as variable names.
•Variable names are
case-sensitive.
Scope of Variables
Local Variables
A variable that is
declared within the method that is called local variables. It is defined in
method or other statements, such as defined and used within the cache block,
and outside the block or method, the variable cannot be used.
Instance variables
A non-static variable
that is declared within the class but not in the method is called instance
variable. Instance variables are related to a specific object; they can access
class variables.
Class/Static variables
A variable that is
declared with static keyword in a class but not in the method is called static
or class variable.
class A
{
int amount = 100; //instance variable
static int pin = 2315; //static variable
public static void main(String[] args)
{
{
int age = 35; //local variable
}
}
Constants in java are
fixed values those are not changed during the Execution of program java
supports several types of Constants those are :
1.Integer Constants
2.Real Constants
3.Single Character
Constants
4.String Constants
5.Backslash Character
Constants
Integer Constants
Integer Constants
refers to a Sequence of digits which Includes only negative or positive Values
and many other things those are as follows
Example
1.Ocatal Integer
Constants
2.Hexadecimal Integer
Constants
Decimal Integer Constants
Decimal constant
consists of a set of digits 0 through 9, preceded by an optional –or + sign.
Eg. 1,3,7,8
Octal Integer
Constants
An octal integer
constant consists of any combination of digits from the set 0 through 7, with
an leading 0. Eg.038,320,0456
Hexadecimal Integer
Constants
An octal integer
constant consists of any combination of digits from the set 0 through F, with
an leading 0x or 0X. eg. 0x4,0x456
Real Constants
Integer numbers are
unable to represent distance, height, temperature, price, and so on. These
informations are contaning fractional parts or real parts like 56.890. Such
numbers are called Real or Floating Point Contants
Example
•A Real Constant must have at Least one Digit
•it must have a Decimal value
•it could be either
positive or Negative
•if no sign is
Specified then it should be treated as Positive
•No Spaces and Commas
are allowed in Name
Like 251, 234.890 etc
are Real Constants
In The Exponential
Form of Representation the Real Constant is Represented in the two Parts The
part before appearing e is called mantissa whereas the part following e is
called Exponent.
•In Real Constant The
Mantissa and Exponent Part should be Separated by letter e
•The Mantissa Part
have may have either positive or Negative Sign
•Default Sign is
Positive
Single Character
Constants
A Character is Single
Alphabet a single digit or a Single Symbol that is enclosed within Single
inverted commas.
1.Character Constant
Can hold Single character at a time.
2.Contains Single
Character Closed within a pair of Single Quote Marks
3.Single Character is
smallest Character Data Type in C.
4.Integer
Representation: Character Constant reprent by Unicode
5.It is Possible to
Perform Arithmetic Operations on Character Constants
String Constants
String is a Sequence
of Characters Enclosed between double Quotes These Characters may be digits,
Alphabets Like "Hello", "1234" etc.
1.The string is "Sequence
of Characters".
2.String Constant is
written in Pair of Double Quotes.
3.The string is
declared as Array of Characters.
4.In C, String data
type is not available.
5.Single Character
String Does not have Equivalent unicode Value
Example
"a"
->String with Single Character
"Ali"->
String With Multiple Characters
“123"-> String
With Digits
Backslash Character
Constants
Java Also Supports
Backslash Constants those are used in output methods For Example \n is used for
new line Character These are also Called as escape Sequence or backslash
character Constants For Example :
1.Although it consists
of two characters, it represents a single character.
2.Each escape sequence
has unicode value.
3.Each and Every
combination starts with back slash()
4.They are
non-printable characters.
5.It can also be
expressed in terms of octal digits or hexadecimal sequence.
StringBuffer
class
Java
StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it
can be changed.
Constructors
of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial
capacity of 16.
StringBuffer(String
str) creates a string buffer with
the specified string.
StringBuffer(int
capacity) creates an empty string
buffer with the specified capacity as length.
StringBuffer
append() method
The append()
method concatenates the given argument with this string.
class
StringBufferExample
{
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
}
}
StringBuffer
insert() method
The insert()
method inserts the given string with this string at the given position.
class
StringBufferExample2
{
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
}
}
StringBuffer
replace() method
The
replace() method replaces the given string from the specified beginIndex and
endIndex.
class
StringBufferExample3
{
public
static void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints
HJavalo
}
}
StringBuffer
delete() method
The delete()
method of StringBuffer class deletes the string from the specified beginIndex
to endIndex.
class
StringBufferExample4
{
public
static void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints
Hlo
}
}
StringBuffer
reverse() method
The
reverse() method of StringBuilder class reverses the current string.
class
StringBufferExample5
{
public static
void main(String args[])
{
StringBuffer
sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints
olleH
}
}
Java String
class methods
The
java.lang.String class provides a lot of methods to work on string. By the help
of these methods, we can perform operations on string such as trimming,
concatenating, converting, comparing, replacing strings etc.
Java String
toUpperCase() and toLowerCase() method
The java
string toUpperCase() method converts this string into uppercase letter and
string toLowerCase() method into lowercase letter.
public class
Testmethodofstringclass
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no
change in original)
}
}
Java String
trim() method
The string
trim() method eliminates white spaces before and after string.
public class
Testmethodofstringclass1
{
public
static void main(String args[]){
String
s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
Java String
charAt() method
The string
charAt() method returns a character at specified index.
public class
Testmethodofstringclass3
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Java String length()
method
The string
length() method returns length of the string.
public class
Testmethodofstringclass4
{
public
static void main(String args[])
{
String
s="Sachin";
System.out.println(s.length());//6
}
}
Java Arrays
Normally, an
array is a collection of similar type of elements which have a contiguous
memory location.
Java array
is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in
Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Types of
Array in java
There are
two types of array.
oSingle
Dimensional Array
oMultidimensional
Array
Single
Dimensional Array in Java
class
Testarray
{
public
static void main(String args[])
{
int a[]=new
int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing
array
for(int
i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Compile by:
javac Testarray.java
Run by: java
Testarray
10
20
70
40
50
Multidimensional
Array in Java
In such
case, data is stored in row and column based index (also known as matrix form).
class
Testarray3
{
public
static void main(String args[])
{
//declaring
and initializing 2D array
int
arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing
2D array
for(int
i=0;i<3;i++)
{
for(int
j=0;j<3;j++)
{
System.out.print(arr[i][j]+"
");
}
System.out.println();
}
}
}
Compile by:
javac Testarray3.java
Run by: java
Testarray3
1 2 3
2 4 5
4 4 5
Declaration,
Instantiation and Initialization of Java Array
We can
declare, instantiate and initialize the java array together by:
int
a[]={33,3,4,5};//declaration, instantiation and initialization
class
Testarray1
{
public
static void main(String args[])
{
int
a[]={33,3,4,5};//declaration, instantiation and initialization
//printing
array
for(int
i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Compile by:
javac Testarray1.java
Run by: java
Testarray1
33
3
4
5
Control
statement
Java If-else
Statement
The Java if
statement is used to test the condition. It checks boolean condition: true or
false.
Java if
Statement
The Java if
statement tests the condition. It executes the if block if condition is true.
public class
IfExample
{
public
static void main(String[] args)
{
int
age=20;
if(age>18)
{
System.out.print("Age
is greater than 18");
}
}
}
Compile by:
javac IfExample.java
Run by: java
IfExample
Age is
greater than 18
Java if-else
Statement
The Java
if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
public class
IfElseExample
{
public
static void main(String[] args)
{
int
number=13;
if(number%2==0)
{
System.out.println("even
number");
}
else
{
System.out.println("odd
number");
}
}
}
Compile by:
javac IfElseExample.java
Run by: java
IfElseExample
odd number
Java Switch
Statement
The Java
switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement. The switch statement works with byte, short, int,
long, enum types, String and some wrapper types like Byte, Short, Int, and
Long. Since Java 7, you can use strings in the switch statement.
public class
SwitchExample
{
public
static void main(String[] args)
{
int
number=20;
switch(number)
{
case 10:
System.out.println("10");break;
case 20:
System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not
in 10, 20 or 30");
}
}
}
Compile by:
javac SwitchExample.java
Run by: java
SwitchExample
20
Loops in
Java
In
programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true. There are
three types of loops in java.
ofor loop
owhile loop
odo-while
loop
For loop
The Java for
loop is a control flow statement that iterates a part of the programs multiple
times.
When to
use:- If the number of iteration is fixed, it is recommended to use for loop.
Syntax:-for(init;condition;incr/decr)
{ // code to be executed }
public class
ForExample
{
public
static void main(String[] args)
{
for(int
i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Compile by:
javac ForExample.java
Run by: java
ForExample
1
2
3
4
5
6
7
8
9
10
while loop
The Java
while loop is a control flow statement that executes a part of the programs
repeatedly on the basis of given boolean condition.
When to use
:-If the number of iteration is not fixed, it is recommended to use while loop.
Syntax
:-while(condition)
{
//code to be
executed
}
public class
WhileExample
{
public
static void main(String[] args)
{
int
i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Compile by:
javac WhileExample.java
Run by: java
WhileExample
1
2
3
4
5
6
7
8
9
10
do while
loop
The Java do
while loop is a control flow statement that executes a part of the programs at
least once and the further execution depends upon the given boolean condition.
When to
use:- If the number of iteration is not fixed and you must have to execute the
loop at least once, it is recommended to use the do-while loop.
Synax:-
do{
//code to be
executed
}while(condition);
public class
DoWhileExample
{
public
static void main(String[] args)
{
int
i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Compile by:
javac DoWhileExample.java
Run by: java
DoWhileExample
1
2
3
4
5
6
7
8
9
10