---
tags: Programming_Languages
---
# Java
## Basic Syntax
### Basic Syntax
Case Sensitivity
Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.
### Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −
Access Modifiers − default, public , protected, private
Non-access Modifiers − final, abstract, strictfp
### Java Variables
Following are the types of variables in Java −
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)
### Java Arrays
Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.
## Class & Object
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Passing
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.
### variable
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.
### Singleton
The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.
Implementing Singletons
Example 1
The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance −
```typescript
// File Name: Singleton.java
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton() { }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
```
Here is the main program file where we will create a singleton object −
```typescript
// File Name: SingletonDemo.java
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}
This will produce the following result −
```
Output
demoMethod for singleton
Example 2
Following implementation shows a classic Singleton design pattern −
```typescript
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
```
The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.
Here, ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.
### Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
#### Declaration − A variable declaration with a variable name with an object type.
#### Instantiation − The 'new' keyword is used to create the object.
#### Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
### Source File Declaration Rules
As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.
There can be only one public class per source file.
A source file can have multiple non-public classes.
The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be the first statement in the source file.
If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.
Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.
## Constructor
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
*** Java allows two types of constructors namely −
No argument Constructors
Parameterized Constructors
## Basic Datatypes
Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the 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
byte
short
int
long
float
double
boolean
char
### Reference/Object Data Types
Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
## Variable type
There are three kinds of variables in Java −
Local variables
Instance variables
Class/Static variables
## Modifier Types
### Java Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
#### Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
```typescript
String version = "1.5.1";
boolean processOrder() {
return true;
}
```
#### Private Access Modifier - Private
Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
```typescript
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}
```
#### Public Access Modifier - Public
A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
```typescript
public static void main(String[] arguments) {
// ...
}
```
#### Protected Access Modifier - Protected
Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
```typescript
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
```
Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier.
##### Access Control and Inheritance
The following rules for inherited methods are enforced −
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
### Non Access Modifiers
Java provides a number of non-access modifiers to achieve many other functionalities.
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 keyword 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 keyword 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.
```typescript
public class 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");
}
}
```
#### 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.
```typescript
public class 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.
#### 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.
```typescript
abstract class 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 without 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();
```typescript
public abstract class SuperClass {
abstract void m(); // abstract method
}
class SubClass extends SuperClass {
// implements the abstract method
void m() {
.........
}
}
```
##### The Synchronized Modifier
The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.
##### 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
```typescript
public transient int limit = 55; // will not persist
public int b; // will persist
```
##### The Volatile Modifier
The volatile modifier 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.
```typescript
public class 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.
## Data Structures
The data structures consist of the following interface and classes −
Enumeration
BitSet
Vector
Stack
Dictionary
Hashtable
Properties
## Operator
### Arithmetic Operators

### Relational Operators

### Bitwise Operators
```typescript
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
```

### Logical Operators

### Assignment Operators

### Misc Operators(Miscellaneous Operators)
Conditional Operator ( ? : )
variable x = (expression) ? value if true : value if false
( Object reference variable ) instanceof (class/interface type)
boolean result = name instanceof String; //true
## Loop control

Loop Control Statements

```typescript
for(declaration : expression) {
// Statements
}
```
## Decision Making

```typescript
Exp1 ? Exp2 : Exp3;
```
## Numbers




## Character
```typescript
char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u039A';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
```


## String
```typescript
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
```
```typescript
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
```
```typescript
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
```
## Array
```typescript
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
```
```typescript
dataType[] arrayRefVar = new dataType[arraySize];
dataType[] arrayRefVar = {value0, value1, ..., valuek};
```
## Date
## Regular Expression
```typescript
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}else {
System.out.println("NO MATCH");
}
}
}
```
## Methods
## Files and I/O

## Inner Class