java introduction
Java is a platform-independent programming language used to create secure and robust application that may run on a single computer or may be distributed among servers and clients over a network.
Java features such as platform-independency and portability ensure that while developing Java EE enterprise applications, you do not face the problems related to hardware , network , and the operating system.
" Java s simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language."
History of Java
Java was started as a project called "Oak" by James Gosling, Patrick Naughton and Mike Sheridan in 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C like notation but with greater uniformity and simplicity than C/C++.The First publication of Java 1.0 was released by Sun Microsystems in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.
In 2006-2007 Sun released java as open source and platform independent software.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
What is JVM (Java Virtual Machine) & JRE( Java Run time Environment)
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
Features of Java & Characteristics of Java
The characteristics and features of java are as follows.1) Simple
Java provides bug free system due to the strong memory management.
2) Object-Oriented
Object Oriented Programming Language must have the following characteristics.
1)Encapsulation 2)Polymorphism 3)Inheritance 4)Abstraction
In java everything is an Object. Java can be easily extended since it is based on the Object model
3) Secure
All Program Run under the sandbox.
4) Robust
Memory management has been simplified java in two ways. First Java does not support direct pointer manipulation or arithmetic. This make it possible for a java program to overwrite memory or corrupt data.
Second , Java uses runtime garbage collection instead of instead of freeing of memory. In languages like c++, it Is necessary to delete or free memory once the program has finished with it.
5) Platform-independent.
6) Architecture neutral
It is not easy to write an application that can be used on Windows , UNIX
and a Macintosh. And its getting more complicated with the move of windows to
non Intel CPU architectures.Java takes a different approach. Because the Java compiler creates byte code instructions that are subsequently interpreted by the java interpreter, architecture neutrality is achieved in the implementation of the java interpreter for each new architecture.
7) Portable
In java, all primitive types(integers, longs, floats, doubles, and so on) are of defined sizes, regardless of the machine or operating system on which the program is run. This is in direct contrast to languages like C and C++ that leave the sized of primitive types up to the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.
8) Dynamic
At runtime, the java interpreter performs name resolution while linking in the necessary classes. The Java interpreter is also responsible for determining the placement of object in memory. These two features of the Java interpreter solve the problem of changing the definition of a class used by other classes.
9) Interpreted
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
10) High performance
11) Multithreaded
Synchronized threads are extremely useful in creating distributed, network-aware applications. Such as application may be communicating with a remote server in one thread while interacting with a user in a different thread.
12) Distributed.
Java facilitates the building of distributed application by a collection of
classes for use in networked applications. By using java's URL (Uniform
Resource Locator) class, an application can easily access a remote server.
Classes also are provided for establishing socket-level connections.Java - Basic Program
When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instance variables mean.
·
Object - Objects have states and
behaviors. Example: A dog has states-color, name, breed as well as behaviors
-wagging, barking, eating. An object is an instance of a class.
·
Class - A class can be defined as a
template/ blue print that describe the behaviors/states that object of its type
support.
·
Methods - A method is basically a
behavior. A class can contain many methods. It is in methods where the logics
are written, data is manipulated and all the actions are executed.
·
Instance Variables - Each object has its
unique set of instance variables. An object's state is created by the values
assigned to these instance variables
First Java Program:
Let us look at a simple code that would print the words Simple Test Program.
publicclass
SimpleProgram
{
public
static
void
main(
String
[]args
){
System
.out
.println("Simple Test Program");
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
·
Open notepad and add the code as above.
·
Save the file as : SimpleProgram.java.
·
Open a command prompt window and go o the
directory where you saved the class. Assume its D:\.
·
Type ' javac SimpleProgram.java ' and press
enter to compile your code. If there are no errors in your code the command
prompt will take you to the next line.( Assumption : The path variable is set).
·
Now type ' java SimpleProgram' to run your
program.
·
You will be able to see ' Simple Test Program '
printed on the window.
C : > javac SimpleProgram.java
C : > java SimpleProgram
Simple Test Program
Explain public static void main (String args[])…..
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed.
Java - Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:- Arithmetic Operators
- Relational Operators
- Bitwise Operators
- Logical Operators
- Assignment Operators
Arithmetic operators are used in mathematical like addition, subtraction etc. The following table lists the arithmetic operators:
Assume that int X = 10 and int Y = 20
Operators
|
Description
|
+ | Addition – Adds values on either side of the operator |
- | Subtraction – Subtracts right hand operand from left hand operand |
* | Multiplication – Multiplies values on either side of the operand |
/ | Division - Divides left hand operand by right hand operand |
% | Modulus - Divides left hand operand by right hand operand and returns remainder |
Increment and
Decrement Operator
++ | Increment - Increase the value of operand by 1 |
-- | Decrement - Decrease the value of operand by 1 |
publicclass
Main{
public
static
void
main(
String args
[]{
Int X
= 10;
Int Y
= 20;
System
.out
.println("Addition (X+Y) = "+(X
+Y
)); // return 30
System
.out
.println("Subtraction (X-Y) = "+(X
-Y
)); // return -10
System
.out
.println("Multiplication (X*Y) = "+(X
*Y
)); // return 200
System
.out
.println("Division (Y/X) = "+(Y
/X
)); // return 2
System
.out
.println("Addition (Y%X) = "+(Y
%X
)); // return 0
Y
++;
System
.out
.println("Increment Y = "+Y
); // return 21
X
--;
System
.out
.println("Decrement X = "+X
); // return 9
}
}
Relational Operators
There are following relational operators supported by Java language like ==,
! = etc.Assume variable X=10 and variable Y=20 then:
Operator
|
Description
|
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 10;
int
Y
= 20;
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
));
}
}
Bitwise Operators
Java defines several bitwise operators like &, | etc which can be applied to the integer types(long, int, short, char, and byte).
Bitwise operator works on bits(0 or 1) and perform bit by bit operation. Assume if x = 60; and y = 13; Now in binary format they will be as follows:
x = 0011 1100
y = 0000 1101
-----------------
x&y = 0000 1100
x|y = 0011 1101
x^y = 0011 0001
~x = 1100 0011
The following table lists the
bitwise operators:
Assume integer variable X=60 and
variable Y=13 then:
Operator
|
Description
|
& | Binary AND Operator copies a bit to the result if it exists in both operands. |
| | Binary OR Operator copies a bit if it exists in either operand. |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
>>> | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
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
<< 2));
System
.out
.println("(X >> Y) = "+(X >>
3));
System
.out
.println("(X >>> Y) = "+(X >>>
1));
}
}
Logical Operators
The following table lists the logical operators like &&, || etc. This logical operator use for join two condition.
Assume Boolean variables X=true and variable Y=false then:
Operator
|
Description
|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
if((
X
==Y
)&&
(
X
!=Y
)){
System
.out
.println("True");
}else{
System
.out
.println("False");
}
if((
X
==Y
)||
(
X
!=Y
)){
System
.out
.println("True");
}
else{
System
.out
.println("False");
}
}
}
Assignment Operators
There are following assignment operators supported by Java language:
Operator
|
Description
|
= | Simple assignment operator, Assigns values from right side operands to left side operand |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
<<= | Left shift AND assignment operator |
>>= | Right shift AND assignment operator |
&= | Bitwise AND assignment operator |
^= | Bitwise exclusive OR and assignment operator |
|= | Bitwise inclusive OR and assignment operator |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
X
+= 1;
System
.out
.println("X+=1 : "+X
);
Y
<<=1;
System
.out
.println("Y<<=1 : "+Y
);
/* Return 26 : 13(binary - 00001101) shift one bit left means 26(00011010) */
}
}
Java - Basic Data Type
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
- Primitive Data Types
- Reference/Object Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
- Byte data type is a 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 int.
- Example : byte a = 100 , byte b = -50
- 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 int
- Default value is 0.
- Example : short s= 10000 , short r = -20000
- 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)
- int 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 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, int b = -200000L
- 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 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 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 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'
In Java SE 7 and later, any number of underscore characters (
_
) can appear anywhere between digits in
a numerical literal. This feature enables you, for example, to separate groups
of digits in numeric literals, which can improve the readability of your code.For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
The following example shows other ways you can use the underscore in numeric literals:
longcreditCardNumber
=1234_5678_9012_3456L
;
longsocialSecurityNumber
=999_99_9999L
;
floatpi
=3.
14_15F
;
longhexBytes
=0xFF_EC_DE_5E
;
longhexWords
=0xCAFE_BABE
;
longmaxLong
=0x7fff_ffff_ffff_ffffL
;
bytenybbles
=0b0010_0101
;
longbytes
=0b11010010_01101001_10010100_10010010
;
You can place underscores only between digits; you cannot place underscores in the following places:
- At the beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an
F
orL
suffix - In positions where a string of digits is expected
- 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 data type.
- Default value of any reference variable is null.
- A reference variable can be used to refer to any object of the declared type or any compatible type.
- Example : Animal animal = new Animal("giraffe");
Java - Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
·
Java Access Modifiers
·
Non Access Modifiers
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
private
If a method or variable is marked as private, then only code inside the same
class can access the variable, or call the method. Code inside subclasses
cannot access the variable or method, nor can code from any external class.If a class is marked as private then no external class an access the class. This doesn't really make so much sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.
Example :
publicclass
Clock
{
private
long
time
= 0;
}
Mostly private access modifier use for fields and make
getter, setter method to access these fields.
default
The default access level is declared by not writing any access modifier at
all. Default access levels means that code inside the class itself + code
inside classes in the same package as this class, can access the class, field,
constructor or method. Therefore, the default access modifier is also sometimes
called a package access modifier.Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.
publicclass
Clock
{
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
protected
The protected access modifier does the same as the default access, except
subclasses can also access protected methods and member variables of the super
class. This is true even if the subclass is not located in the same package as
the super class.
publicclass
Clock
{
protected
long
time
= 0; // time in milliseconds
}
publicclass
SmartClock()
extends
Clock
{
public
long
getTimeInSeconds()
{
return
this.
time
/ 1000;
}
}
public
The public access modifier means that all code can access the class, field,
constructor or method, regardless of where the accessing code is located.Example:
publicclass
Clock
{
public
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
·
The static modifier for creating class
methods and variables
·
The final modifier for finalizing the
implementations of classes, methods, and variables.
·
The abstract modifier for creating
abstract classes and methods.
·
The synchronized and volatile
modifiers, which are used for threads.
The static Modifier:
Static Variables:
The static key word is used to create variables that will exist independently
of any instances created for the class. Only one copy of the static variable
exists regardless of the number of instances of the class.Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods:
The static key word is used to create methods that will exist independently
of any instances created for the class.Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example:
The static modifier is used to create class methods and variables, as in the
following example:
publicclass
InstanceCounter
{
private
static
int
numInstances
= 0;
protected
static
int
getCount()
{
return
numInstances
;
}
private
static
void
addInstance()
{
numInstances
++;
}
InstanceCounter()
{
InstanceCounter
.addInstance();
}
public
static
void
main(
String
[]arguments
){
System
.out
.println("Starting with "+
InstanceCounter
.getCount()+
" instances");
for
(int
i
= 0;i
< 500;++
i
){
new
InstanceCounter();
}
System
.out
.println("Created "+
InstanceCounter
.getCount()+
" instances");
}
}
This would produce following result:
Started with 0 instances
Created 500 instances
The final Modifier:
final Variables:
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an different
object.However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
publicclass
Test{
final
int
value
= 10;
// The following are examples of declaring constants:
public
static
final
int
BOXWIDTH
= 6;
static
final
String TITLE
="Manager";
public
void
changeValue(){
value
= 12; //will give an error
}
}
final Methods:
A final method cannot be overridden by any subclasses. As mentioned
previously the final modifier prevents a method from being modified in a
subclass.The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Example:
You declare methods using the final modifier in the class
declaration, as in the following example:
publicclass
Test{
public
final
void
changeName(){
// body of method
}
}
final Classes:
The main purpose of using a class being declared as final is to
prevent the class from being subclassed. If a class is marked as final then no
class can inherit any feature from the final class.
Example:
publicfinal
class
Test
{
// body of class
}
The abstract Modifier:
abstract Class:
An abstract class can never be instantiated. If a class is declared as
abstract then the sole purpose is for the class to be extended.A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example:
abstractclass
Caravan{
private
double
price
;
private
String model
;
private
String year
;
public
abstract
void
goFast(); //an abstract method
public
abstract
void
changeColor();
}
abstract Methods:
An abstract method is a method declared with out any implementation. The
methods body(implementation) is provided by the subclass. Abstract methods can
never be final or strict.Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
Example:
publicabstract
class
SuperClass{
abstract
void
m(); //abstract method
}
classSubClass
extends
SuperClass{
// implements the abstract method
void
m(){
.........
}
}
The synchronized Modifier:
Example:
publicsynchronized
void
showDetails(){
.......
}
The transient Modifier:
An instance variable is marked transient to indicate the JVM to skip the
particular variable when serializing the object containing it.This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
Example:
publictransient
int
limit
= 55;// will not persist
publicint
b
; // will persist
The volatile Modifier:
The volatile is used to let the JVM know that a thread accessing the
variable must always merge its own private copy of the variable with the master
copy in the memory.Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables which are of type object or private. A volatile object reference can be null.
Example:
publicclass
MyRunnable
implements
Runnable
{
private
volatile
boolean
active
;
public
void
run()
{
active
=true;
while
(
active
) // line 1
{
// some code here
}
}
public
void
stop()
{
active
=false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile.
Java - Loop control
Loop is very common control flow statement in programming languages such as java. We are going to describe the basics of “java loop”. In this post, we will learn various ways to use loop in day-to-day programming habits.There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop
There are four types of loops:
- for loop
- for each loop
- while loop
- do..While loop
It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.
Syntax:
for(
initialization
;conditional expression
;increment expression
)
{
//repetition code here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
for(int
x
= 50;x
< 55;x
++){
System
.out
.println("Value of x : "+
x
);
}
}
}
Output:
Value of x : 50;
Value of x : 51;
Value of x : 52;
Value of x : 53;
Value of x : 54;
For each Loop
This loop is supported from Java 5.
For each loop is mainly used for iterate the Array, List etc.
Syntax:
for(
declaration
:expression
)
{
//Code Here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
List list
=new
ArrayList();
list
.add(10
);
list
.add(20
);
list
.add(30
);
System
.out
.print("List Value = ");
for(int
x
:list
){
System
.out
.print(x
);
System
.out
.print(",");
}
String
[]names
={"abc","xyz",
"test",
"example"};
System
.out
.println("String Array value = ");
for(
String name
:names
){
System
.out
.print(name
);
System
.out
.print(",");
}
}
}
Output:List Value = 10,20,30
String Array value = abc,xyz,test,example
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you don’t want to repeat your code a specific number of times, rather, you want to keep looping through your code until a certain condition is met.
Syntax:
while(
Boolean_expression
)
{
//Repetition Code Here
}
Example:
publicclass
Example
{
public
static
void
main(
String args
[]){
int
x
= 50;
while(
x
< 55)
{
System
.out
.println("Value of x : "+
x
);
x
++;
}
}
}
Output:
Value of x : 50
Value of x : 51
Value of x : 52
Value of x : 53
Value of x : 54
do..while Loop
This type of loop is used in very rare cases because it does the same thing as a while loop does, except that a do..while loop is guaranteed to execute at least on time.
Syntax:
do
{
//Code Here
}while(
Boolean_expression
);
Example:
publicclass
Test
{
public
static
void
main(
String args
[]){
int
x
= 50;
do{
System
.out
.println("Value of x : "+
x
);
x
++;
}while(
x
< 50);
}
}
Output:
Value of x : 50
Above example first execute code inside loop and then check condition that’s why it’s display 50.
Java - Decision Making
If statement:The if statement is Java’s conditional branch statement.
Syntax:
If(Boolean expression
){
// Code here
}
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println("a is greater than b");
}
if(
b
<a
){
System
.out
.println("b is less than a");
}
}
}
Output:
a is greater than b
b is less than a
if else :
Syntax:
if(Boolean condition
){
// statement1
}else{
// statement2
}
This if else work like : if condition is true than statement1 is executed otherwise statement2 is executed.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println(?a is greater than b
?);
}else{
System
.out
.println(?b is greater than a
?);
}
}
}
Output:
b is greater than a
If-else-if-ladder:
Syntax:
if(Boolean condition
){
// statement1
}elseif(
Boolean condition
){
// statement2
}elseif(
Boolean condition
){
// statement3
}
........
else{
// else statement
}
The if statement executed from top to down. As soon as one of the condition is true, statement associated with that if statement executed.
If none of the condition is true than else statement will be executed, only one of the statement executed from list of else if statements.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
percentage
= 65;
if(
percentage >
= 70){
System
.out
.println(?First
classwith
Distinction
?);
}else
If(
percentage >
= 60){
System
.out
.println(?First Class
?);
}else
If(
percentage >
= 48){
System
.out
.println(?Second Class
?);
}else
If(
percentage >
= 36){
System
.out
.println(?Pass Class
?);
}else{
System
.out
.println(?Fail
?);
}
}
}
Output:
First Class
switch statement:
The switch statement is multi way branch statement in java programming. It is use to replace multilevel if-else-if statement.
Syntax:
switch(expression
){
casevalue
1:
// statement 1
break;
casevalue
2:
// statement 2
break;
casevalue n
:
// statement n
break;
default:
//statements
break;
}
The expression type must be the byte, short, int and char.
Each case value must be a unique literal(constant not a variable). Duplicate case value not allowed.
The each case value compare with expression if match found than corresponding statement will be executed. If no match is found than default statement will be executed. Default case if optional.
The break statement use to terminate statement sequence, if break statement is not written than all statement execute after match statement.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
day
= 1;
switch(
day
){
case 0:
System
.out
.println("Sunday");
break;
case 1:
System
.out
.println("Monday");
break;
case 3:
System
.out
.println("Tuesday");
break;
case 4:
System
.out
.println("Wednesday");
break;
case 5:
System
.out
.println("Thursday");
break;
case 6:
System
.out
.println("Friday");
break;
case 7:
System
.out
.println("Saturday");
break;
default:
System
.out
.println("Invalid Day");
break;
}
}
}
Output:
Monday
Note : switch statement support string from Java 7, means use string object in the switch expression.
Java is a platform-independent programming language used to create secure and robust application that may run on a single computer or may be distributed among servers and clients over a network.
Java features such as platform-independency and portability ensure that while developing Java EE enterprise applications, you do not face the problems related to hardware , network , and the operating system.
" Java s simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language."
History of Java
Java was started as a project called "Oak" by James Gosling, Patrick Naughton and Mike Sheridan in 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C like notation but with greater uniformity and simplicity than C/C++.The First publication of Java 1.0 was released by Sun Microsystems in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.
In 2006-2007 Sun released java as open source and platform independent software.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
What is JVM (Java Virtual Machine) & JRE( Java Run time Environment)
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
Features of Java & Characteristics of Java
The characteristics and features of java are as follows.1) Simple
Java provides bug free system due to the strong memory management.
2) Object-Oriented
Object Oriented Programming Language must have the following characteristics.
1)Encapsulation 2)Polymorphism 3)Inheritance 4)Abstraction
In java everything is an Object. Java can be easily extended since it is based on the Object model
3) Secure
All Program Run under the sandbox.
4) Robust
Memory management has been simplified java in two ways. First Java does not support direct pointer manipulation or arithmetic. This make it possible for a java program to overwrite memory or corrupt data.
Second , Java uses runtime garbage collection instead of instead of freeing of memory. In languages like c++, it Is necessary to delete or free memory once the program has finished with it.
5) Platform-independent.
6) Architecture neutral
It is not easy to write an application that can be used on Windows , UNIX
and a Macintosh. And its getting more complicated with the move of windows to
non Intel CPU architectures.Java takes a different approach. Because the Java compiler creates byte code instructions that are subsequently interpreted by the java interpreter, architecture neutrality is achieved in the implementation of the java interpreter for each new architecture.
7) Portable
In java, all primitive types(integers, longs, floats, doubles, and so on) are of defined sizes, regardless of the machine or operating system on which the program is run. This is in direct contrast to languages like C and C++ that leave the sized of primitive types up to the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.
8) Dynamic
At runtime, the java interpreter performs name resolution while linking in the necessary classes. The Java interpreter is also responsible for determining the placement of object in memory. These two features of the Java interpreter solve the problem of changing the definition of a class used by other classes.
9) Interpreted
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
10) High performance
11) Multithreaded
Synchronized threads are extremely useful in creating distributed, network-aware applications. Such as application may be communicating with a remote server in one thread while interacting with a user in a different thread.
12) Distributed.
Java facilitates the building of distributed application by a collection of
classes for use in networked applications. By using java's URL (Uniform
Resource Locator) class, an application can easily access a remote server.
Classes also are provided for establishing socket-level connections.Java - Basic Program
When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instance variables mean.
·
Object - Objects have states and
behaviors. Example: A dog has states-color, name, breed as well as behaviors
-wagging, barking, eating. An object is an instance of a class.
·
Class - A class can be defined as a
template/ blue print that describe the behaviors/states that object of its type
support.
·
Methods - A method is basically a
behavior. A class can contain many methods. It is in methods where the logics
are written, data is manipulated and all the actions are executed.
·
Instance Variables - Each object has its
unique set of instance variables. An object's state is created by the values
assigned to these instance variables
First Java Program:
Let us look at a simple code that would print the words Simple Test Program.
publicclass
SimpleProgram
{
public
static
void
main(
String
[]args
){
System
.out
.println("Simple Test Program");
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
·
Open notepad and add the code as above.
·
Save the file as : SimpleProgram.java.
·
Open a command prompt window and go o the
directory where you saved the class. Assume its D:\.
·
Type ' javac SimpleProgram.java ' and press
enter to compile your code. If there are no errors in your code the command
prompt will take you to the next line.( Assumption : The path variable is set).
·
Now type ' java SimpleProgram' to run your
program.
·
You will be able to see ' Simple Test Program '
printed on the window.
C : > javac SimpleProgram.java
C : > java SimpleProgram
Simple Test Program
Explain public static void main (String args[])…..
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed.
Java - Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:- Arithmetic Operators
- Relational Operators
- Bitwise Operators
- Logical Operators
- Assignment Operators
Arithmetic operators are used in mathematical like addition, subtraction etc. The following table lists the arithmetic operators:
Assume that int X = 10 and int Y = 20
Operators
|
Description
|
+ | Addition – Adds values on either side of the operator |
- | Subtraction – Subtracts right hand operand from left hand operand |
* | Multiplication – Multiplies values on either side of the operand |
/ | Division - Divides left hand operand by right hand operand |
% | Modulus - Divides left hand operand by right hand operand and returns remainder |
Increment and
Decrement Operator
++ | Increment - Increase the value of operand by 1 |
-- | Decrement - Decrease the value of operand by 1 |
publicclass
Main{
public
static
void
main(
String args
[]{
Int X
= 10;
Int Y
= 20;
System
.out
.println("Addition (X+Y) = "+(X
+Y
)); // return 30
System
.out
.println("Subtraction (X-Y) = "+(X
-Y
)); // return -10
System
.out
.println("Multiplication (X*Y) = "+(X
*Y
)); // return 200
System
.out
.println("Division (Y/X) = "+(Y
/X
)); // return 2
System
.out
.println("Addition (Y%X) = "+(Y
%X
)); // return 0
Y
++;
System
.out
.println("Increment Y = "+Y
); // return 21
X
--;
System
.out
.println("Decrement X = "+X
); // return 9
}
}
Relational Operators
There are following relational operators supported by Java language like ==,
! = etc.Assume variable X=10 and variable Y=20 then:
Operator
|
Description
|
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 10;
int
Y
= 20;
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
));
}
}
Bitwise Operators
Java defines several bitwise operators like &, | etc which can be applied to the integer types(long, int, short, char, and byte).
Bitwise operator works on bits(0 or 1) and perform bit by bit operation. Assume if x = 60; and y = 13; Now in binary format they will be as follows:
x = 0011 1100
y = 0000 1101
-----------------
x&y = 0000 1100
x|y = 0011 1101
x^y = 0011 0001
~x = 1100 0011
The following table lists the
bitwise operators:
Assume integer variable X=60 and
variable Y=13 then:
Operator
|
Description
|
& | Binary AND Operator copies a bit to the result if it exists in both operands. |
| | Binary OR Operator copies a bit if it exists in either operand. |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
>>> | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
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
<< 2));
System
.out
.println("(X >> Y) = "+(X >>
3));
System
.out
.println("(X >>> Y) = "+(X >>>
1));
}
}
Logical Operators
The following table lists the logical operators like &&, || etc. This logical operator use for join two condition.
Assume Boolean variables X=true and variable Y=false then:
Operator
|
Description
|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
if((
X
==Y
)&&
(
X
!=Y
)){
System
.out
.println("True");
}else{
System
.out
.println("False");
}
if((
X
==Y
)||
(
X
!=Y
)){
System
.out
.println("True");
}
else{
System
.out
.println("False");
}
}
}
Assignment Operators
There are following assignment operators supported by Java language:
Operator
|
Description
|
= | Simple assignment operator, Assigns values from right side operands to left side operand |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
<<= | Left shift AND assignment operator |
>>= | Right shift AND assignment operator |
&= | Bitwise AND assignment operator |
^= | Bitwise exclusive OR and assignment operator |
|= | Bitwise inclusive OR and assignment operator |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
X
+= 1;
System
.out
.println("X+=1 : "+X
);
Y
<<=1;
System
.out
.println("Y<<=1 : "+Y
);
/* Return 26 : 13(binary - 00001101) shift one bit left means 26(00011010) */
}
}
Java - Basic Data Type
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
- Primitive Data Types
- Reference/Object Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
- Byte data type is a 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 int.
- Example : byte a = 100 , byte b = -50
- 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 int
- Default value is 0.
- Example : short s= 10000 , short r = -20000
- 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)
- int 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 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, int b = -200000L
- 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 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 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 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'
In Java SE 7 and later, any number of underscore characters (
_
) can appear anywhere between digits in
a numerical literal. This feature enables you, for example, to separate groups
of digits in numeric literals, which can improve the readability of your code.For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
The following example shows other ways you can use the underscore in numeric literals:
longcreditCardNumber
=1234_5678_9012_3456L
;
longsocialSecurityNumber
=999_99_9999L
;
floatpi
=3.
14_15F
;
longhexBytes
=0xFF_EC_DE_5E
;
longhexWords
=0xCAFE_BABE
;
longmaxLong
=0x7fff_ffff_ffff_ffffL
;
bytenybbles
=0b0010_0101
;
longbytes
=0b11010010_01101001_10010100_10010010
;
You can place underscores only between digits; you cannot place underscores in the following places:
- At the beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an
F
orL
suffix - In positions where a string of digits is expected
- 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 data type.
- Default value of any reference variable is null.
- A reference variable can be used to refer to any object of the declared type or any compatible type.
- Example : Animal animal = new Animal("giraffe");
Java - Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
·
Java Access Modifiers
·
Non Access Modifiers
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
private
If a method or variable is marked as private, then only code inside the same
class can access the variable, or call the method. Code inside subclasses
cannot access the variable or method, nor can code from any external class.If a class is marked as private then no external class an access the class. This doesn't really make so much sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.
Example :
publicclass
Clock
{
private
long
time
= 0;
}
Mostly private access modifier use for fields and make
getter, setter method to access these fields.
default
The default access level is declared by not writing any access modifier at
all. Default access levels means that code inside the class itself + code
inside classes in the same package as this class, can access the class, field,
constructor or method. Therefore, the default access modifier is also sometimes
called a package access modifier.Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.
publicclass
Clock
{
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
protected
The protected access modifier does the same as the default access, except
subclasses can also access protected methods and member variables of the super
class. This is true even if the subclass is not located in the same package as
the super class.
publicclass
Clock
{
protected
long
time
= 0; // time in milliseconds
}
publicclass
SmartClock()
extends
Clock
{
public
long
getTimeInSeconds()
{
return
this.
time
/ 1000;
}
}
public
The public access modifier means that all code can access the class, field,
constructor or method, regardless of where the accessing code is located.Example:
publicclass
Clock
{
public
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
·
The static modifier for creating class
methods and variables
·
The final modifier for finalizing the
implementations of classes, methods, and variables.
·
The abstract modifier for creating
abstract classes and methods.
·
The synchronized and volatile
modifiers, which are used for threads.
The static Modifier:
Static Variables:
The static key word is used to create variables that will exist independently
of any instances created for the class. Only one copy of the static variable
exists regardless of the number of instances of the class.Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods:
The static key word is used to create methods that will exist independently
of any instances created for the class.Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example:
The static modifier is used to create class methods and variables, as in the
following example:
publicclass
InstanceCounter
{
private
static
int
numInstances
= 0;
protected
static
int
getCount()
{
return
numInstances
;
}
private
static
void
addInstance()
{
numInstances
++;
}
InstanceCounter()
{
InstanceCounter
.addInstance();
}
public
static
void
main(
String
[]arguments
){
System
.out
.println("Starting with "+
InstanceCounter
.getCount()+
" instances");
for
(int
i
= 0;i
< 500;++
i
){
new
InstanceCounter();
}
System
.out
.println("Created "+
InstanceCounter
.getCount()+
" instances");
}
}
This would produce following result:
Started with 0 instances
Created 500 instances
The final Modifier:
final Variables:
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an different
object.However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
publicclass
Test{
final
int
value
= 10;
// The following are examples of declaring constants:
public
static
final
int
BOXWIDTH
= 6;
static
final
String TITLE
="Manager";
public
void
changeValue(){
value
= 12; //will give an error
}
}
final Methods:
A final method cannot be overridden by any subclasses. As mentioned
previously the final modifier prevents a method from being modified in a
subclass.The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Example:
You declare methods using the final modifier in the class
declaration, as in the following example:
publicclass
Test{
public
final
void
changeName(){
// body of method
}
}
final Classes:
The main purpose of using a class being declared as final is to
prevent the class from being subclassed. If a class is marked as final then no
class can inherit any feature from the final class.
Example:
publicfinal
class
Test
{
// body of class
}
The abstract Modifier:
abstract Class:
An abstract class can never be instantiated. If a class is declared as
abstract then the sole purpose is for the class to be extended.A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example:
abstractclass
Caravan{
private
double
price
;
private
String model
;
private
String year
;
public
abstract
void
goFast(); //an abstract method
public
abstract
void
changeColor();
}
abstract Methods:
An abstract method is a method declared with out any implementation. The
methods body(implementation) is provided by the subclass. Abstract methods can
never be final or strict.Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
Example:
publicabstract
class
SuperClass{
abstract
void
m(); //abstract method
}
classSubClass
extends
SuperClass{
// implements the abstract method
void
m(){
.........
}
}
The synchronized Modifier:
Example:
publicsynchronized
void
showDetails(){
.......
}
The transient Modifier:
An instance variable is marked transient to indicate the JVM to skip the
particular variable when serializing the object containing it.This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
Example:
publictransient
int
limit
= 55;// will not persist
publicint
b
; // will persist
The volatile Modifier:
The volatile is used to let the JVM know that a thread accessing the
variable must always merge its own private copy of the variable with the master
copy in the memory.Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables which are of type object or private. A volatile object reference can be null.
Example:
publicclass
MyRunnable
implements
Runnable
{
private
volatile
boolean
active
;
public
void
run()
{
active
=true;
while
(
active
) // line 1
{
// some code here
}
}
public
void
stop()
{
active
=false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile.
Java - Loop control
Loop is very common control flow statement in programming languages such as java. We are going to describe the basics of “java loop”. In this post, we will learn various ways to use loop in day-to-day programming habits.There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop
There are four types of loops:
- for loop
- for each loop
- while loop
- do..While loop
It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.
Syntax:
for(
initialization
;conditional expression
;increment expression
)
{
//repetition code here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
for(int
x
= 50;x
< 55;x
++){
System
.out
.println("Value of x : "+
x
);
}
}
}
Output:
Value of x : 50;
Value of x : 51;
Value of x : 52;
Value of x : 53;
Value of x : 54;
For each Loop
This loop is supported from Java 5.
For each loop is mainly used for iterate the Array, List etc.
Syntax:
for(
declaration
:expression
)
{
//Code Here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
List list
=new
ArrayList();
list
.add(10
);
list
.add(20
);
list
.add(30
);
System
.out
.print("List Value = ");
for(int
x
:list
){
System
.out
.print(x
);
System
.out
.print(",");
}
String
[]names
={"abc","xyz",
"test",
"example"};
System
.out
.println("String Array value = ");
for(
String name
:names
){
System
.out
.print(name
);
System
.out
.print(",");
}
}
}
Output:List Value = 10,20,30
String Array value = abc,xyz,test,example
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you don’t want to repeat your code a specific number of times, rather, you want to keep looping through your code until a certain condition is met.
Syntax:
while(
Boolean_expression
)
{
//Repetition Code Here
}
Example:
publicclass
Example
{
public
static
void
main(
String args
[]){
int
x
= 50;
while(
x
< 55)
{
System
.out
.println("Value of x : "+
x
);
x
++;
}
}
}
Output:
Value of x : 50
Value of x : 51
Value of x : 52
Value of x : 53
Value of x : 54
do..while Loop
This type of loop is used in very rare cases because it does the same thing as a while loop does, except that a do..while loop is guaranteed to execute at least on time.
Syntax:
do
{
//Code Here
}while(
Boolean_expression
);
Example:
publicclass
Test
{
public
static
void
main(
String args
[]){
int
x
= 50;
do{
System
.out
.println("Value of x : "+
x
);
x
++;
}while(
x
< 50);
}
}
Output:
Value of x : 50
Above example first execute code inside loop and then check condition that’s why it’s display 50.
Java - Decision Making
If statement:The if statement is Java’s conditional branch statement.
Syntax:
If(Boolean expression
){
// Code here
}
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println("a is greater than b");
}
if(
b
<a
){
System
.out
.println("b is less than a");
}
}
}
Output:
a is greater than b
b is less than a
if else :
Syntax:
if(Boolean condition
){
// statement1
}else{
// statement2
}
This if else work like : if condition is true than statement1 is executed otherwise statement2 is executed.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println(?a is greater than b
?);
}else{
System
.out
.println(?b is greater than a
?);
}
}
}
Output:
b is greater than a
If-else-if-ladder:
Syntax:
if(Boolean condition
){
// statement1
}elseif(
Boolean condition
){
// statement2
}elseif(
Boolean condition
){
// statement3
}
........
else{
// else statement
}
The if statement executed from top to down. As soon as one of the condition is true, statement associated with that if statement executed.
If none of the condition is true than else statement will be executed, only one of the statement executed from list of else if statements.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
percentage
= 65;
if(
percentage >
= 70){
System
.out
.println(?First
classwith
Distinction
?);
}else
If(
percentage >
= 60){
System
.out
.println(?First Class
?);
}else
If(
percentage >
= 48){
System
.out
.println(?Second Class
?);
}else
If(
percentage >
= 36){
System
.out
.println(?Pass Class
?);
}else{
System
.out
.println(?Fail
?);
}
}
}
Output:
First Class
switch statement:
The switch statement is multi way branch statement in java programming. It is use to replace multilevel if-else-if statement.
Syntax:
switch(expression
){
casevalue
1:
// statement 1
break;
casevalue
2:
// statement 2
break;
casevalue n
:
// statement n
break;
default:
//statements
break;
}
The expression type must be the byte, short, int and char.
Each case value must be a unique literal(constant not a variable). Duplicate case value not allowed.
The each case value compare with expression if match found than corresponding statement will be executed. If no match is found than default statement will be executed. Default case if optional.
The break statement use to terminate statement sequence, if break statement is not written than all statement execute after match statement.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
day
= 1;
switch(
day
){
case 0:
System
.out
.println("Sunday");
break;
case 1:
System
.out
.println("Monday");
break;
case 3:
System
.out
.println("Tuesday");
break;
case 4:
System
.out
.println("Wednesday");
break;
case 5:
System
.out
.println("Thursday");
break;
case 6:
System
.out
.println("Friday");
break;
case 7:
System
.out
.println("Saturday");
break;
default:
System
.out
.println("Invalid Day");
break;
}
}
}
Output:
Monday
Note : switch statement support string from Java 7, means use string object in the switch expression.
Java is a platform-independent programming language used to create secure and robust application that may run on a single computer or may be distributed among servers and clients over a network.
Java features such as platform-independency and portability ensure that while developing Java EE enterprise applications, you do not face the problems related to hardware , network , and the operating system.
" Java s simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language."
History of Java
Java was started as a project called "Oak" by James Gosling, Patrick Naughton and Mike Sheridan in 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C like notation but with greater uniformity and simplicity than C/C++.The First publication of Java 1.0 was released by Sun Microsystems in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.
In 2006-2007 Sun released java as open source and platform independent software.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
What is JVM (Java Virtual Machine) & JRE( Java Run time Environment)
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
Features of Java & Characteristics of Java
The characteristics and features of java are as follows.1) Simple
Java provides bug free system due to the strong memory management.
2) Object-Oriented
Object Oriented Programming Language must have the following characteristics.
1)Encapsulation 2)Polymorphism 3)Inheritance 4)Abstraction
In java everything is an Object. Java can be easily extended since it is based on the Object model
3) Secure
All Program Run under the sandbox.
4) Robust
Memory management has been simplified java in two ways. First Java does not support direct pointer manipulation or arithmetic. This make it possible for a java program to overwrite memory or corrupt data.
Second , Java uses runtime garbage collection instead of instead of freeing of memory. In languages like c++, it Is necessary to delete or free memory once the program has finished with it.
5) Platform-independent.
6) Architecture neutral
It is not easy to write an application that can be used on Windows , UNIX
and a Macintosh. And its getting more complicated with the move of windows to
non Intel CPU architectures.Java takes a different approach. Because the Java compiler creates byte code instructions that are subsequently interpreted by the java interpreter, architecture neutrality is achieved in the implementation of the java interpreter for each new architecture.
7) Portable
In java, all primitive types(integers, longs, floats, doubles, and so on) are of defined sizes, regardless of the machine or operating system on which the program is run. This is in direct contrast to languages like C and C++ that leave the sized of primitive types up to the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.
8) Dynamic
At runtime, the java interpreter performs name resolution while linking in the necessary classes. The Java interpreter is also responsible for determining the placement of object in memory. These two features of the Java interpreter solve the problem of changing the definition of a class used by other classes.
9) Interpreted
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
10) High performance
11) Multithreaded
Synchronized threads are extremely useful in creating distributed, network-aware applications. Such as application may be communicating with a remote server in one thread while interacting with a user in a different thread.
12) Distributed.
Java facilitates the building of distributed application by a collection of
classes for use in networked applications. By using java's URL (Uniform
Resource Locator) class, an application can easily access a remote server.
Classes also are provided for establishing socket-level connections.Java - Basic Program
When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instance variables mean.
·
Object - Objects have states and
behaviors. Example: A dog has states-color, name, breed as well as behaviors
-wagging, barking, eating. An object is an instance of a class.
·
Class - A class can be defined as a
template/ blue print that describe the behaviors/states that object of its type
support.
·
Methods - A method is basically a
behavior. A class can contain many methods. It is in methods where the logics
are written, data is manipulated and all the actions are executed.
·
Instance Variables - Each object has its
unique set of instance variables. An object's state is created by the values
assigned to these instance variables
First Java Program:
Let us look at a simple code that would print the words Simple Test Program.
publicclass
SimpleProgram
{
public
static
void
main(
String
[]args
){
System
.out
.println("Simple Test Program");
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
·
Open notepad and add the code as above.
·
Save the file as : SimpleProgram.java.
·
Open a command prompt window and go o the
directory where you saved the class. Assume its D:\.
·
Type ' javac SimpleProgram.java ' and press
enter to compile your code. If there are no errors in your code the command
prompt will take you to the next line.( Assumption : The path variable is set).
·
Now type ' java SimpleProgram' to run your
program.
·
You will be able to see ' Simple Test Program '
printed on the window.
C : > javac SimpleProgram.java
C : > java SimpleProgram
Simple Test Program
Explain public static void main (String args[])…..
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed.
Java - Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:- Arithmetic Operators
- Relational Operators
- Bitwise Operators
- Logical Operators
- Assignment Operators
Arithmetic operators are used in mathematical like addition, subtraction etc. The following table lists the arithmetic operators:
Assume that int X = 10 and int Y = 20
Operators
|
Description
|
+ | Addition – Adds values on either side of the operator |
- | Subtraction – Subtracts right hand operand from left hand operand |
* | Multiplication – Multiplies values on either side of the operand |
/ | Division - Divides left hand operand by right hand operand |
% | Modulus - Divides left hand operand by right hand operand and returns remainder |
Increment and
Decrement Operator
++ | Increment - Increase the value of operand by 1 |
-- | Decrement - Decrease the value of operand by 1 |
publicclass
Main{
public
static
void
main(
String args
[]{
Int X
= 10;
Int Y
= 20;
System
.out
.println("Addition (X+Y) = "+(X
+Y
)); // return 30
System
.out
.println("Subtraction (X-Y) = "+(X
-Y
)); // return -10
System
.out
.println("Multiplication (X*Y) = "+(X
*Y
)); // return 200
System
.out
.println("Division (Y/X) = "+(Y
/X
)); // return 2
System
.out
.println("Addition (Y%X) = "+(Y
%X
)); // return 0
Y
++;
System
.out
.println("Increment Y = "+Y
); // return 21
X
--;
System
.out
.println("Decrement X = "+X
); // return 9
}
}
Relational Operators
There are following relational operators supported by Java language like ==,
! = etc.Assume variable X=10 and variable Y=20 then:
Operator
|
Description
|
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 10;
int
Y
= 20;
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
));
}
}
Bitwise Operators
Java defines several bitwise operators like &, | etc which can be applied to the integer types(long, int, short, char, and byte).
Bitwise operator works on bits(0 or 1) and perform bit by bit operation. Assume if x = 60; and y = 13; Now in binary format they will be as follows:
x = 0011 1100
y = 0000 1101
-----------------
x&y = 0000 1100
x|y = 0011 1101
x^y = 0011 0001
~x = 1100 0011
The following table lists the
bitwise operators:
Assume integer variable X=60 and
variable Y=13 then:
Operator
|
Description
|
& | Binary AND Operator copies a bit to the result if it exists in both operands. |
| | Binary OR Operator copies a bit if it exists in either operand. |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
>>> | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
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
<< 2));
System
.out
.println("(X >> Y) = "+(X >>
3));
System
.out
.println("(X >>> Y) = "+(X >>>
1));
}
}
Logical Operators
The following table lists the logical operators like &&, || etc. This logical operator use for join two condition.
Assume Boolean variables X=true and variable Y=false then:
Operator
|
Description
|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
if((
X
==Y
)&&
(
X
!=Y
)){
System
.out
.println("True");
}else{
System
.out
.println("False");
}
if((
X
==Y
)||
(
X
!=Y
)){
System
.out
.println("True");
}
else{
System
.out
.println("False");
}
}
}
Assignment Operators
There are following assignment operators supported by Java language:
Operator
|
Description
|
= | Simple assignment operator, Assigns values from right side operands to left side operand |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
<<= | Left shift AND assignment operator |
>>= | Right shift AND assignment operator |
&= | Bitwise AND assignment operator |
^= | Bitwise exclusive OR and assignment operator |
|= | Bitwise inclusive OR and assignment operator |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
X
+= 1;
System
.out
.println("X+=1 : "+X
);
Y
<<=1;
System
.out
.println("Y<<=1 : "+Y
);
/* Return 26 : 13(binary - 00001101) shift one bit left means 26(00011010) */
}
}
Java - Basic Data Type
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
- Primitive Data Types
- Reference/Object Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
- Byte data type is a 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 int.
- Example : byte a = 100 , byte b = -50
- 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 int
- Default value is 0.
- Example : short s= 10000 , short r = -20000
- 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)
- int 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 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, int b = -200000L
- 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 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 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 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'
In Java SE 7 and later, any number of underscore characters (
_
) can appear anywhere between digits in
a numerical literal. This feature enables you, for example, to separate groups
of digits in numeric literals, which can improve the readability of your code.For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
The following example shows other ways you can use the underscore in numeric literals:
longcreditCardNumber
=1234_5678_9012_3456L
;
longsocialSecurityNumber
=999_99_9999L
;
floatpi
=3.
14_15F
;
longhexBytes
=0xFF_EC_DE_5E
;
longhexWords
=0xCAFE_BABE
;
longmaxLong
=0x7fff_ffff_ffff_ffffL
;
bytenybbles
=0b0010_0101
;
longbytes
=0b11010010_01101001_10010100_10010010
;
You can place underscores only between digits; you cannot place underscores in the following places:
- At the beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an
F
orL
suffix - In positions where a string of digits is expected
- 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 data type.
- Default value of any reference variable is null.
- A reference variable can be used to refer to any object of the declared type or any compatible type.
- Example : Animal animal = new Animal("giraffe");
Java - Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
·
Java Access Modifiers
·
Non Access Modifiers
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
private
If a method or variable is marked as private, then only code inside the same
class can access the variable, or call the method. Code inside subclasses
cannot access the variable or method, nor can code from any external class.If a class is marked as private then no external class an access the class. This doesn't really make so much sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.
Example :
publicclass
Clock
{
private
long
time
= 0;
}
Mostly private access modifier use for fields and make
getter, setter method to access these fields.
default
The default access level is declared by not writing any access modifier at
all. Default access levels means that code inside the class itself + code
inside classes in the same package as this class, can access the class, field,
constructor or method. Therefore, the default access modifier is also sometimes
called a package access modifier.Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.
publicclass
Clock
{
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
protected
The protected access modifier does the same as the default access, except
subclasses can also access protected methods and member variables of the super
class. This is true even if the subclass is not located in the same package as
the super class.
publicclass
Clock
{
protected
long
time
= 0; // time in milliseconds
}
publicclass
SmartClock()
extends
Clock
{
public
long
getTimeInSeconds()
{
return
this.
time
/ 1000;
}
}
public
The public access modifier means that all code can access the class, field,
constructor or method, regardless of where the accessing code is located.Example:
publicclass
Clock
{
public
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
·
The static modifier for creating class
methods and variables
·
The final modifier for finalizing the
implementations of classes, methods, and variables.
·
The abstract modifier for creating
abstract classes and methods.
·
The synchronized and volatile
modifiers, which are used for threads.
The static Modifier:
Static Variables:
The static key word is used to create variables that will exist independently
of any instances created for the class. Only one copy of the static variable
exists regardless of the number of instances of the class.Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods:
The static key word is used to create methods that will exist independently
of any instances created for the class.Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example:
The static modifier is used to create class methods and variables, as in the
following example:
publicclass
InstanceCounter
{
private
static
int
numInstances
= 0;
protected
static
int
getCount()
{
return
numInstances
;
}
private
static
void
addInstance()
{
numInstances
++;
}
InstanceCounter()
{
InstanceCounter
.addInstance();
}
public
static
void
main(
String
[]arguments
){
System
.out
.println("Starting with "+
InstanceCounter
.getCount()+
" instances");
for
(int
i
= 0;i
< 500;++
i
){
new
InstanceCounter();
}
System
.out
.println("Created "+
InstanceCounter
.getCount()+
" instances");
}
}
This would produce following result:
Started with 0 instances
Created 500 instances
The final Modifier:
final Variables:
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an different
object.However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
publicclass
Test{
final
int
value
= 10;
// The following are examples of declaring constants:
public
static
final
int
BOXWIDTH
= 6;
static
final
String TITLE
="Manager";
public
void
changeValue(){
value
= 12; //will give an error
}
}
final Methods:
A final method cannot be overridden by any subclasses. As mentioned
previously the final modifier prevents a method from being modified in a
subclass.The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Example:
You declare methods using the final modifier in the class
declaration, as in the following example:
publicclass
Test{
public
final
void
changeName(){
// body of method
}
}
final Classes:
The main purpose of using a class being declared as final is to
prevent the class from being subclassed. If a class is marked as final then no
class can inherit any feature from the final class.
Example:
publicfinal
class
Test
{
// body of class
}
The abstract Modifier:
abstract Class:
An abstract class can never be instantiated. If a class is declared as
abstract then the sole purpose is for the class to be extended.A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example:
abstractclass
Caravan{
private
double
price
;
private
String model
;
private
String year
;
public
abstract
void
goFast(); //an abstract method
public
abstract
void
changeColor();
}
abstract Methods:
An abstract method is a method declared with out any implementation. The
methods body(implementation) is provided by the subclass. Abstract methods can
never be final or strict.Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
Example:
publicabstract
class
SuperClass{
abstract
void
m(); //abstract method
}
classSubClass
extends
SuperClass{
// implements the abstract method
void
m(){
.........
}
}
The synchronized Modifier:
Example:
publicsynchronized
void
showDetails(){
.......
}
The transient Modifier:
An instance variable is marked transient to indicate the JVM to skip the
particular variable when serializing the object containing it.This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
Example:
publictransient
int
limit
= 55;// will not persist
publicint
b
; // will persist
The volatile Modifier:
The volatile is used to let the JVM know that a thread accessing the
variable must always merge its own private copy of the variable with the master
copy in the memory.Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables which are of type object or private. A volatile object reference can be null.
Example:
publicclass
MyRunnable
implements
Runnable
{
private
volatile
boolean
active
;
public
void
run()
{
active
=true;
while
(
active
) // line 1
{
// some code here
}
}
public
void
stop()
{
active
=false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile.
Java - Loop control
Loop is very common control flow statement in programming languages such as java. We are going to describe the basics of “java loop”. In this post, we will learn various ways to use loop in day-to-day programming habits.There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop
There are four types of loops:
- for loop
- for each loop
- while loop
- do..While loop
It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.
Syntax:
for(
initialization
;conditional expression
;increment expression
)
{
//repetition code here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
for(int
x
= 50;x
< 55;x
++){
System
.out
.println("Value of x : "+
x
);
}
}
}
Output:
Value of x : 50;
Value of x : 51;
Value of x : 52;
Value of x : 53;
Value of x : 54;
For each Loop
This loop is supported from Java 5.
For each loop is mainly used for iterate the Array, List etc.
Syntax:
for(
declaration
:expression
)
{
//Code Here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
List list
=new
ArrayList();
list
.add(10
);
list
.add(20
);
list
.add(30
);
System
.out
.print("List Value = ");
for(int
x
:list
){
System
.out
.print(x
);
System
.out
.print(",");
}
String
[]names
={"abc","xyz",
"test",
"example"};
System
.out
.println("String Array value = ");
for(
String name
:names
){
System
.out
.print(name
);
System
.out
.print(",");
}
}
}
Output:List Value = 10,20,30
String Array value = abc,xyz,test,example
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you don’t want to repeat your code a specific number of times, rather, you want to keep looping through your code until a certain condition is met.
Syntax:
while(
Boolean_expression
)
{
//Repetition Code Here
}
Example:
publicclass
Example
{
public
static
void
main(
String args
[]){
int
x
= 50;
while(
x
< 55)
{
System
.out
.println("Value of x : "+
x
);
x
++;
}
}
}
Output:
Value of x : 50
Value of x : 51
Value of x : 52
Value of x : 53
Value of x : 54
do..while Loop
This type of loop is used in very rare cases because it does the same thing as a while loop does, except that a do..while loop is guaranteed to execute at least on time.
Syntax:
do
{
//Code Here
}while(
Boolean_expression
);
Example:
publicclass
Test
{
public
static
void
main(
String args
[]){
int
x
= 50;
do{
System
.out
.println("Value of x : "+
x
);
x
++;
}while(
x
< 50);
}
}
Output:
Value of x : 50
Above example first execute code inside loop and then check condition that’s why it’s display 50.
Java - Decision Making
If statement:The if statement is Java’s conditional branch statement.
Syntax:
If(Boolean expression
){
// Code here
}
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println("a is greater than b");
}
if(
b
<a
){
System
.out
.println("b is less than a");
}
}
}
Output:
a is greater than b
b is less than a
if else :
Syntax:
if(Boolean condition
){
// statement1
}else{
// statement2
}
This if else work like : if condition is true than statement1 is executed otherwise statement2 is executed.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println(?a is greater than b
?);
}else{
System
.out
.println(?b is greater than a
?);
}
}
}
Output:
b is greater than a
If-else-if-ladder:
Syntax:
if(Boolean condition
){
// statement1
}elseif(
Boolean condition
){
// statement2
}elseif(
Boolean condition
){
// statement3
}
........
else{
// else statement
}
The if statement executed from top to down. As soon as one of the condition is true, statement associated with that if statement executed.
If none of the condition is true than else statement will be executed, only one of the statement executed from list of else if statements.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
percentage
= 65;
if(
percentage >
= 70){
System
.out
.println(?First
classwith
Distinction
?);
}else
If(
percentage >
= 60){
System
.out
.println(?First Class
?);
}else
If(
percentage >
= 48){
System
.out
.println(?Second Class
?);
}else
If(
percentage >
= 36){
System
.out
.println(?Pass Class
?);
}else{
System
.out
.println(?Fail
?);
}
}
}
Output:
First Class
switch statement:
The switch statement is multi way branch statement in java programming. It is use to replace multilevel if-else-if statement.
Syntax:
switch(expression
){
casevalue
1:
// statement 1
break;
casevalue
2:
// statement 2
break;
casevalue n
:
// statement n
break;
default:
//statements
break;
}
The expression type must be the byte, short, int and char.
Each case value must be a unique literal(constant not a variable). Duplicate case value not allowed.
The each case value compare with expression if match found than corresponding statement will be executed. If no match is found than default statement will be executed. Default case if optional.
The break statement use to terminate statement sequence, if break statement is not written than all statement execute after match statement.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
day
= 1;
switch(
day
){
case 0:
System
.out
.println("Sunday");
break;
case 1:
System
.out
.println("Monday");
break;
case 3:
System
.out
.println("Tuesday");
break;
case 4:
System
.out
.println("Wednesday");
break;
case 5:
System
.out
.println("Thursday");
break;
case 6:
System
.out
.println("Friday");
break;
case 7:
System
.out
.println("Saturday");
break;
default:
System
.out
.println("Invalid Day");
break;
}
}
}
Output:
Monday
Note : switch statement support string from Java 7, means use string object in the switch expression.
Java is a platform-independent programming language used to create secure and robust application that may run on a single computer or may be distributed among servers and clients over a network.
Java features such as platform-independency and portability ensure that while developing Java EE enterprise applications, you do not face the problems related to hardware , network , and the operating system.
" Java s simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language."
History of Java
Java was started as a project called "Oak" by James Gosling, Patrick Naughton and Mike Sheridan in 1991. Gosling's goals were to implement a virtual machine and a language that had a familiar C like notation but with greater uniformity and simplicity than C/C++.The First publication of Java 1.0 was released by Sun Microsystems in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.
In 2006-2007 Sun released java as open source and platform independent software.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
What is JVM (Java Virtual Machine) & JRE( Java Run time Environment)
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
Features of Java & Characteristics of Java
The characteristics and features of java are as follows.1) Simple
Java provides bug free system due to the strong memory management.
2) Object-Oriented
Object Oriented Programming Language must have the following characteristics.
1)Encapsulation 2)Polymorphism 3)Inheritance 4)Abstraction
In java everything is an Object. Java can be easily extended since it is based on the Object model
3) Secure
All Program Run under the sandbox.
4) Robust
Memory management has been simplified java in two ways. First Java does not support direct pointer manipulation or arithmetic. This make it possible for a java program to overwrite memory or corrupt data.
Second , Java uses runtime garbage collection instead of instead of freeing of memory. In languages like c++, it Is necessary to delete or free memory once the program has finished with it.
5) Platform-independent.
6) Architecture neutral
It is not easy to write an application that can be used on Windows , UNIX
and a Macintosh. And its getting more complicated with the move of windows to
non Intel CPU architectures.Java takes a different approach. Because the Java compiler creates byte code instructions that are subsequently interpreted by the java interpreter, architecture neutrality is achieved in the implementation of the java interpreter for each new architecture.
7) Portable
In java, all primitive types(integers, longs, floats, doubles, and so on) are of defined sizes, regardless of the machine or operating system on which the program is run. This is in direct contrast to languages like C and C++ that leave the sized of primitive types up to the compiler and developer.
Additionally, Java is portable because the compiler itself is written in Java.
8) Dynamic
At runtime, the java interpreter performs name resolution while linking in the necessary classes. The Java interpreter is also responsible for determining the placement of object in memory. These two features of the Java interpreter solve the problem of changing the definition of a class used by other classes.
9) Interpreted
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
10) High performance
11) Multithreaded
Synchronized threads are extremely useful in creating distributed, network-aware applications. Such as application may be communicating with a remote server in one thread while interacting with a user in a different thread.
12) Distributed.
Java facilitates the building of distributed application by a collection of
classes for use in networked applications. By using java's URL (Uniform
Resource Locator) class, an application can easily access a remote server.
Classes also are provided for establishing socket-level connections.Java - Basic Program
When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instance variables mean.
·
Object - Objects have states and
behaviors. Example: A dog has states-color, name, breed as well as behaviors
-wagging, barking, eating. An object is an instance of a class.
·
Class - A class can be defined as a
template/ blue print that describe the behaviors/states that object of its type
support.
·
Methods - A method is basically a
behavior. A class can contain many methods. It is in methods where the logics
are written, data is manipulated and all the actions are executed.
·
Instance Variables - Each object has its
unique set of instance variables. An object's state is created by the values
assigned to these instance variables
First Java Program:
Let us look at a simple code that would print the words Simple Test Program.
publicclass
SimpleProgram
{
public
static
void
main(
String
[]args
){
System
.out
.println("Simple Test Program");
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
·
Open notepad and add the code as above.
·
Save the file as : SimpleProgram.java.
·
Open a command prompt window and go o the
directory where you saved the class. Assume its D:\.
·
Type ' javac SimpleProgram.java ' and press
enter to compile your code. If there are no errors in your code the command
prompt will take you to the next line.( Assumption : The path variable is set).
·
Now type ' java SimpleProgram' to run your
program.
·
You will be able to see ' Simple Test Program '
printed on the window.
C : > javac SimpleProgram.java
C : > java SimpleProgram
Simple Test Program
Explain public static void main (String args[])…..
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values.As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main( ) method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If there are no parameters required for a given method, you still need to include the empty parentheses. In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. In this case, args receives any command-line arguments present when the program is executed.
Java - Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:- Arithmetic Operators
- Relational Operators
- Bitwise Operators
- Logical Operators
- Assignment Operators
Arithmetic operators are used in mathematical like addition, subtraction etc. The following table lists the arithmetic operators:
Assume that int X = 10 and int Y = 20
Operators
|
Description
|
+ | Addition – Adds values on either side of the operator |
- | Subtraction – Subtracts right hand operand from left hand operand |
* | Multiplication – Multiplies values on either side of the operand |
/ | Division - Divides left hand operand by right hand operand |
% | Modulus - Divides left hand operand by right hand operand and returns remainder |
Increment and
Decrement Operator
++ | Increment - Increase the value of operand by 1 |
-- | Decrement - Decrease the value of operand by 1 |
publicclass
Main{
public
static
void
main(
String args
[]{
Int X
= 10;
Int Y
= 20;
System
.out
.println("Addition (X+Y) = "+(X
+Y
)); // return 30
System
.out
.println("Subtraction (X-Y) = "+(X
-Y
)); // return -10
System
.out
.println("Multiplication (X*Y) = "+(X
*Y
)); // return 200
System
.out
.println("Division (Y/X) = "+(Y
/X
)); // return 2
System
.out
.println("Addition (Y%X) = "+(Y
%X
)); // return 0
Y
++;
System
.out
.println("Increment Y = "+Y
); // return 21
X
--;
System
.out
.println("Decrement X = "+X
); // return 9
}
}
Relational Operators
There are following relational operators supported by Java language like ==,
! = etc.Assume variable X=10 and variable Y=20 then:
Operator
|
Description
|
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 10;
int
Y
= 20;
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
));
}
}
Bitwise Operators
Java defines several bitwise operators like &, | etc which can be applied to the integer types(long, int, short, char, and byte).
Bitwise operator works on bits(0 or 1) and perform bit by bit operation. Assume if x = 60; and y = 13; Now in binary format they will be as follows:
x = 0011 1100
y = 0000 1101
-----------------
x&y = 0000 1100
x|y = 0011 1101
x^y = 0011 0001
~x = 1100 0011
The following table lists the
bitwise operators:
Assume integer variable X=60 and
variable Y=13 then:
Operator
|
Description
|
& | Binary AND Operator copies a bit to the result if it exists in both operands. |
| | Binary OR Operator copies a bit if it exists in either operand. |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. |
~ | Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
>>> | Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
Example :
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
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
<< 2));
System
.out
.println("(X >> Y) = "+(X >>
3));
System
.out
.println("(X >>> Y) = "+(X >>>
1));
}
}
Logical Operators
The following table lists the logical operators like &&, || etc. This logical operator use for join two condition.
Assume Boolean variables X=true and variable Y=false then:
Operator
|
Description
|
&& | Called Logical AND operator. If both the operands are non zero then condition becomes true. |
|| | Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
if((
X
==Y
)&&
(
X
!=Y
)){
System
.out
.println("True");
}else{
System
.out
.println("False");
}
if((
X
==Y
)||
(
X
!=Y
)){
System
.out
.println("True");
}
else{
System
.out
.println("False");
}
}
}
Assignment Operators
There are following assignment operators supported by Java language:
Operator
|
Description
|
= | Simple assignment operator, Assigns values from right side operands to left side operand |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
<<= | Left shift AND assignment operator |
>>= | Right shift AND assignment operator |
&= | Bitwise AND assignment operator |
^= | Bitwise exclusive OR and assignment operator |
|= | Bitwise inclusive OR and assignment operator |
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
X
= 60;
int
Y
= 13;
X
+= 1;
System
.out
.println("X+=1 : "+X
);
Y
<<=1;
System
.out
.println("Y<<=1 : "+Y
);
/* Return 26 : 13(binary - 00001101) shift one bit left means 26(00011010) */
}
}
Java - Basic Data Type
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java:
- Primitive Data Types
- Reference/Object Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
- Byte data type is a 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 int.
- Example : byte a = 100 , byte b = -50
- 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 int
- Default value is 0.
- Example : short s= 10000 , short r = -20000
- 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)
- int 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 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, int b = -200000L
- 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 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 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 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'
In Java SE 7 and later, any number of underscore characters (
_
) can appear anywhere between digits in
a numerical literal. This feature enables you, for example, to separate groups
of digits in numeric literals, which can improve the readability of your code.For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.
The following example shows other ways you can use the underscore in numeric literals:
longcreditCardNumber
=1234_5678_9012_3456L
;
longsocialSecurityNumber
=999_99_9999L
;
floatpi
=3.
14_15F
;
longhexBytes
=0xFF_EC_DE_5E
;
longhexWords
=0xCAFE_BABE
;
longmaxLong
=0x7fff_ffff_ffff_ffffL
;
bytenybbles
=0b0010_0101
;
longbytes
=0b11010010_01101001_10010100_10010010
;
You can place underscores only between digits; you cannot place underscores in the following places:
- At the beginning or end of a number
- Adjacent to a decimal point in a floating point literal
- Prior to an
F
orL
suffix - In positions where a string of digits is expected
- 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 data type.
- Default value of any reference variable is null.
- A reference variable can be used to refer to any object of the declared type or any compatible type.
- Example : Animal animal = new Animal("giraffe");
Java - Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
·
Java Access Modifiers
·
Non Access Modifiers
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
private
If a method or variable is marked as private, then only code inside the same
class can access the variable, or call the method. Code inside subclasses
cannot access the variable or method, nor can code from any external class.If a class is marked as private then no external class an access the class. This doesn't really make so much sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.
Example :
publicclass
Clock
{
private
long
time
= 0;
}
Mostly private access modifier use for fields and make
getter, setter method to access these fields.
default
The default access level is declared by not writing any access modifier at
all. Default access levels means that code inside the class itself + code
inside classes in the same package as this class, can access the class, field,
constructor or method. Therefore, the default access modifier is also sometimes
called a package access modifier.Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.
publicclass
Clock
{
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
protected
The protected access modifier does the same as the default access, except
subclasses can also access protected methods and member variables of the super
class. This is true even if the subclass is not located in the same package as
the super class.
publicclass
Clock
{
protected
long
time
= 0; // time in milliseconds
}
publicclass
SmartClock()
extends
Clock
{
public
long
getTimeInSeconds()
{
return
this.
time
/ 1000;
}
}
public
The public access modifier means that all code can access the class, field,
constructor or method, regardless of where the accessing code is located.Example:
publicclass
Clock
{
public
long
time
= 0;
}
publicclass
ClockReader
{
Clock clock
=new
Clock();
public
long
readClock
{
return
clock
.time
;
}
}
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
·
The static modifier for creating class
methods and variables
·
The final modifier for finalizing the
implementations of classes, methods, and variables.
·
The abstract modifier for creating
abstract classes and methods.
·
The synchronized and volatile
modifiers, which are used for threads.
The static Modifier:
Static Variables:
The static key word is used to create variables that will exist independently
of any instances created for the class. Only one copy of the static variable
exists regardless of the number of instances of the class.Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods:
The static key word is used to create methods that will exist independently
of any instances created for the class.Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
Example:
The static modifier is used to create class methods and variables, as in the
following example:
publicclass
InstanceCounter
{
private
static
int
numInstances
= 0;
protected
static
int
getCount()
{
return
numInstances
;
}
private
static
void
addInstance()
{
numInstances
++;
}
InstanceCounter()
{
InstanceCounter
.addInstance();
}
public
static
void
main(
String
[]arguments
){
System
.out
.println("Starting with "+
InstanceCounter
.getCount()+
" instances");
for
(int
i
= 0;i
< 500;++
i
){
new
InstanceCounter();
}
System
.out
.println("Created "+
InstanceCounter
.getCount()+
" instances");
}
}
This would produce following result:
Started with 0 instances
Created 500 instances
The final Modifier:
final Variables:
A final variable can be explicitly initialized only once. A reference
variable declared final can never be reassigned to refer to an different
object.However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
publicclass
Test{
final
int
value
= 10;
// The following are examples of declaring constants:
public
static
final
int
BOXWIDTH
= 6;
static
final
String TITLE
="Manager";
public
void
changeValue(){
value
= 12; //will give an error
}
}
final Methods:
A final method cannot be overridden by any subclasses. As mentioned
previously the final modifier prevents a method from being modified in a
subclass.The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Example:
You declare methods using the final modifier in the class
declaration, as in the following example:
publicclass
Test{
public
final
void
changeName(){
// body of method
}
}
final Classes:
The main purpose of using a class being declared as final is to
prevent the class from being subclassed. If a class is marked as final then no
class can inherit any feature from the final class.
Example:
publicfinal
class
Test
{
// body of class
}
The abstract Modifier:
abstract Class:
An abstract class can never be instantiated. If a class is declared as
abstract then the sole purpose is for the class to be extended.A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example:
abstractclass
Caravan{
private
double
price
;
private
String model
;
private
String year
;
public
abstract
void
goFast(); //an abstract method
public
abstract
void
changeColor();
}
abstract Methods:
An abstract method is a method declared with out any implementation. The
methods body(implementation) is provided by the subclass. Abstract methods can
never be final or strict.Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();
Example:
publicabstract
class
SuperClass{
abstract
void
m(); //abstract method
}
classSubClass
extends
SuperClass{
// implements the abstract method
void
m(){
.........
}
}
The synchronized Modifier:
Example:
publicsynchronized
void
showDetails(){
.......
}
The transient Modifier:
An instance variable is marked transient to indicate the JVM to skip the
particular variable when serializing the object containing it.This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.
Example:
publictransient
int
limit
= 55;// will not persist
publicint
b
; // will persist
The volatile Modifier:
The volatile is used to let the JVM know that a thread accessing the
variable must always merge its own private copy of the variable with the master
copy in the memory.Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables which are of type object or private. A volatile object reference can be null.
Example:
publicclass
MyRunnable
implements
Runnable
{
private
volatile
boolean
active
;
public
void
run()
{
active
=true;
while
(
active
) // line 1
{
// some code here
}
}
public
void
stop()
{
active
=false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called from another thread. If in line 1 the cached value of active is used, the loop may not stop when you set active to false in line 2. That's when you want to use volatile.
Java - Loop control
Loop is very common control flow statement in programming languages such as java. We are going to describe the basics of “java loop”. In this post, we will learn various ways to use loop in day-to-day programming habits.There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop
There are four types of loops:
- for loop
- for each loop
- while loop
- do..While loop
It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.
Syntax:
for(
initialization
;conditional expression
;increment expression
)
{
//repetition code here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
for(int
x
= 50;x
< 55;x
++){
System
.out
.println("Value of x : "+
x
);
}
}
}
Output:
Value of x : 50;
Value of x : 51;
Value of x : 52;
Value of x : 53;
Value of x : 54;
For each Loop
This loop is supported from Java 5.
For each loop is mainly used for iterate the Array, List etc.
Syntax:
for(
declaration
:expression
)
{
//Code Here
}
Example:
public
class
Example
{
public
static
void
main(
String args
[]){
List list
=new
ArrayList();
list
.add(10
);
list
.add(20
);
list
.add(30
);
System
.out
.print("List Value = ");
for(int
x
:list
){
System
.out
.print(x
);
System
.out
.print(",");
}
String
[]names
={"abc","xyz",
"test",
"example"};
System
.out
.println("String Array value = ");
for(
String name
:names
){
System
.out
.print(name
);
System
.out
.print(",");
}
}
}
Output:List Value = 10,20,30
String Array value = abc,xyz,test,example
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you don’t want to repeat your code a specific number of times, rather, you want to keep looping through your code until a certain condition is met.
Syntax:
while(
Boolean_expression
)
{
//Repetition Code Here
}
Example:
publicclass
Example
{
public
static
void
main(
String args
[]){
int
x
= 50;
while(
x
< 55)
{
System
.out
.println("Value of x : "+
x
);
x
++;
}
}
}
Output:
Value of x : 50
Value of x : 51
Value of x : 52
Value of x : 53
Value of x : 54
do..while Loop
This type of loop is used in very rare cases because it does the same thing as a while loop does, except that a do..while loop is guaranteed to execute at least on time.
Syntax:
do
{
//Code Here
}while(
Boolean_expression
);
Example:
publicclass
Test
{
public
static
void
main(
String args
[]){
int
x
= 50;
do{
System
.out
.println("Value of x : "+
x
);
x
++;
}while(
x
< 50);
}
}
Output:
Value of x : 50
Above example first execute code inside loop and then check condition that’s why it’s display 50.
Java - Decision Making
If statement:The if statement is Java’s conditional branch statement.
Syntax:
If(Boolean expression
){
// Code here
}
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println("a is greater than b");
}
if(
b
<a
){
System
.out
.println("b is less than a");
}
}
}
Output:
a is greater than b
b is less than a
if else :
Syntax:
if(Boolean condition
){
// statement1
}else{
// statement2
}
This if else work like : if condition is true than statement1 is executed otherwise statement2 is executed.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
a
= 10;
int
b
= 20;
if(
a>b
){
System
.out
.println(?a is greater than b
?);
}else{
System
.out
.println(?b is greater than a
?);
}
}
}
Output:
b is greater than a
If-else-if-ladder:
Syntax:
if(Boolean condition
){
// statement1
}elseif(
Boolean condition
){
// statement2
}elseif(
Boolean condition
){
// statement3
}
........
else{
// else statement
}
The if statement executed from top to down. As soon as one of the condition is true, statement associated with that if statement executed.
If none of the condition is true than else statement will be executed, only one of the statement executed from list of else if statements.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
percentage
= 65;
if(
percentage >
= 70){
System
.out
.println(?First
classwith
Distinction
?);
}else
If(
percentage >
= 60){
System
.out
.println(?First Class
?);
}else
If(
percentage >
= 48){
System
.out
.println(?Second Class
?);
}else
If(
percentage >
= 36){
System
.out
.println(?Pass Class
?);
}else{
System
.out
.println(?Fail
?);
}
}
}
Output:
First Class
switch statement:
The switch statement is multi way branch statement in java programming. It is use to replace multilevel if-else-if statement.
Syntax:
switch(expression
){
casevalue
1:
// statement 1
break;
casevalue
2:
// statement 2
break;
casevalue n
:
// statement n
break;
default:
//statements
break;
}
The expression type must be the byte, short, int and char.
Each case value must be a unique literal(constant not a variable). Duplicate case value not allowed.
The each case value compare with expression if match found than corresponding statement will be executed. If no match is found than default statement will be executed. Default case if optional.
The break statement use to terminate statement sequence, if break statement is not written than all statement execute after match statement.
Example:
publicclass
Main{
public
static
void
main(
String args
[]){
int
day
= 1;
switch(
day
){
case 0:
System
.out
.println("Sunday");
break;
case 1:
System
.out
.println("Monday");
break;
case 3:
System
.out
.println("Tuesday");
break;
case 4:
System
.out
.println("Wednesday");
break;
case 5:
System
.out
.println("Thursday");
break;
case 6:
System
.out
.println("Friday");
break;
case 7:
System
.out
.println("Saturday");
break;
default:
System
.out
.println("Invalid Day");
break;
}
}
}
Output:
Monday
Note : switch statement support string from Java 7, means use string object in the switch expression.
Comments
Post a Comment