java

Synopsis

Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

Data Types

Data TypeSize
boolean1 bit
char2 byte
int4 byte
short2 byte
long8 byte
float4 byte
double8 byte

I/O Methods

Output Methods

	system.out.print("Hello World!"); //Will not move to the next line.
	system.out.println("Hello World!"); //Will move to the next line.

	// There is another type of output method, which is similar to C language.
	int a = 23;
	system.out.printf("value of a is : %d", a);

Input Methods

	import java.util.Scanner
	Scanner s = new Scanner(System.in);

	// input for an integer.
	int a = s.nextInt();

	// input for a string.
	String str = s.nextLine();
	String ss  = s.next();   // Takes input till 1st whitespace.

	// input for a double.
	double d = s.nextDouble();

Data Conversion

String to Number

        int i = Intege­r.p­ars­eInt(_str_);
 	double d = Double.pa­rse­Double(_str_);

Any Type to String

 	String s = String.va­lueOf(_value_);

Numeric Conver­sions

 	int i = (int) _numeric expression_;
        double i = (double) _numeric expression_;
        long i = (long) _numeric expression_;

Operators

Operator CategoryOperators
Arithmetic operators+, -, /, *, %
Relational operators<, >, <=, >=,==, !=
Logical operators&&, ||
Assignment operator=, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>=
Increment and Decrement operator++ , - -
Conditional operators?, :
Bitwise operators^, &, |
Special operators. (dot operator to access methods of class)

Statements

If Statement

if ( _expression_ ) {
­ _statements_
} else if ( _expression_ ) {
­ _statements_
} else {
­ _statements_
}

While Loop

while ( _expression_ ) {
­ _statements_
}

Do-While Loop

do {
­ _statements_
} while ( _expression_ );

For Loop

for ( int i = 0; i < _max_; ++i) {
­ _statements_
}

For Each Loop

for ( _var_ : _collection_ ) {
­ _statements_
}

Switch Statement

switch ( _expression_ ) {
­ case _value_:
­ ­ ­ _statements_
­ ­ ­ ­break;
­ case _value2_:
­ ­ ­ _statements_
­ ­ ­ ­break;
­ ­def­ault:
­ ­ ­ _statements_
}

Exception Handling

try {
­ ­sta­tem­ents;
} catch (_Except­ionType_  _e1_) {
­ ­sta­tem­ents;
} catch (Exception _e2_) {
­ ­cat­ch-all statem­ents;
} finally {
­ ­sta­tem­ents;
}

Comments

A comment is the code that is not executed by the compiler, and the programmer uses it to keep track of the code.

Single Line Comment

// This is a single line command

Multi-Line Comment

/*
This is a multi line comment
we can add multiple lines here
x=5
y=c
*/

Constants

Constants are like variables, except that their value never changes during program execution. Constants are declared using static and final keywords

static final float pi = 3.1415;

Escape Sequences

Tab

It gives a tab space

\t

Backslash

It adds a backslash

\\

Single quote

It adds a single quotation mark

\'

Question mark

It adds a question mark

\?

Type Casting

Type Casting is a process of converting one data type into another

Widening Type Casting (Automatically)

It means converting a lower data type into a higher

int x = 49;
double new_x = x;   // Outputs 49.0

Narrowing Type Casting (Manually)

It means converting a higher data type into a lower

double x = 99.2
int new_x = (int) x;  // Outputs 99

Arrays

Initialisation

For 1-D array

// datatype array_name[] = new datatype[Size];
int number[] = new int[10];           // An Integer Array
String characters[] = new String[10]; // A String array
int[] number = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

For 2-D array

// datatype array_name[][] = new datatype[row][column];
int number[][] = new int[10][10];            // An Integer Array of dimensions 10 x 10
String characters[][] = new String[10][10];  // A String Array of dimensions 10 x 10

Traversal

// Traditional for loop
for(int i=0;i<number.length;i++) //length gives the size of the array
{
System.out.println(number[i]);
}
// Advanced for loop
for(int i:number)
{
System.out.println(i);
}

Strings

“In Java, a string is basically an object that represents sequence of char values. An array of characters works same as Java string.” : Javatpoint

Ways to Initialise a string

Using String Literal

String s = "INPUT";
//Using the new keyword
String s = new String("INPUT");
//From a given character array
char ch[]={'I','N','P','U','T'};
String s=new String(ch);

The above mentioned methods creates a string that are immutable, to make strings mutable, we can use StringBuilder or StringBuffer

Using StringBuffer

“The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.” : GFG
//Create a StringBuffer Object, i.e., empty string buffer
//By default it can take upto a sequence of 16 characters
StringBuffer sb = new StringBuffer();
// Can be initialised with a string
StringBuffer sb2 = new StringBuffer("Input");
1) append(string_data) method : Used to concatenate the entered string and the strings in the buffer
sb.append("Input");  //Now the empty string has been modified to "Input"
2) insert(beginIndex, endIndex, string_data) method : Inserts a given string literal to the specified positions
sb.insert(2," A String");
//Now the string is "In A Stringput"
3) replace(beginIndex, endIndex, string_data) method : Use to replace a sequence of characters from the specified beginIndex and endIndex-1, with another sequence
sb.replace(11,14," Literal");
//Now the string is "In A string Literal"
4) delete(beginIndex, endIndex) method : Use to delete a sequence of characters from the specified beginIndex and endIndex-1
sb.delete(11,19);
//Now the string is "In A String"
5) reverse() method : Reverses the current string
sb.reverse();
// Now the string is "gnirtS A nI"

Using StringBuilder

Very similiar to the StringBuffer class but is not Synchronous and neither Thread-Safe. But high in performance, i.e., speedy
//Create a StringBuilder Object, i.e., StringBuilder with no characters
//By default it can take upto a sequence of 16 characters
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuffer("Input");
append(), insert(), replace(), delete(), reverse() are used in the same way as used in the StringBuffer
To convert the objects of either StringBuilder or StringBuffer to string, use : toString()
String str = sb.toString();
System.out.println(str);

Array Methods

The Arrays class of the java.util package contains several static methods that can be used to fill, sort, search, etc in arrays.

MethodsAction Performed
asList()Returns a fixed-size list backed by the specified Arrays
binarySearch()Searches for the specified element in the array
binarySearch(array, fromIndex, toIndex, key, Comparator)Searches a range of the specified array for the specified object using the Binary Search Algorithm
copyOf(originalArray, newLength)Copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length.
copyOfRange(originalArray, fromIndex, endIndex)Copies the specified range of the specified array into a new Arrays.
deepEquals(Object[] a1, Object[] a2)Returns true if the two specified arrays are deeply equal to one another.
deepHashCode(Object[] a)Returns a hash code based on the “deep contents” of the specified Arrays.
deepToString(Object[] a)Returns a string representation of the “deep contents” of the specified Arrays.
fill(originalArray, fillValue)Assigns this fill value to each index of this arrays.
hashCode(originalArray)Returns an integer hashCode of this array instance.
mismatch(array1, array2)Finds and returns the index of the first unmatched element between the two specified arrays.
parallelPrefix(originalArray, fromIndex, endIndex, functionalOperator)Performs parallelPrefix for the given range of the array with the specified functional operator.
parallelPrefix(originalArray, operator)Performs parallelPrefix for complete array with the specified functional operator.
parallelSetAll(originalArray, functionalGenerator)Sets all the elements of this array in parallel, using the provided generator function.
parallelSort(originalArray)Sorts the specified array using parallel sort.
setAll(originalArray, functionalGenerator)Sets all the elements of the specified array using the generator function provided.
sort(originalArray)Sorts the complete array in ascending order.
sort(originalArray, fromIndex, endIndex)Sorts the specified range of array in ascending order.
sort(T[] a, int fromIndex, int toIndex, Comparator< super T> c)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
sort(T[] a, Comparator< super T> c)Sorts the specified array of objects according to the order induced by the specified comparator.
spliterator(originalArray)Returns a Spliterator covering all of the specified Arrays.
spliterator(originalArray, fromIndex, endIndex)Returns a Spliterator of the type of the array covering the specified range of the specified arrays.
stream(originalArray)Returns a sequential stream with the specified array as its source.
toString(originalArray)Returns a string representation of the contents of this array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function.

String Methods

CommandDescription
lengthlength of string
charAt(i)extract _i_th character
subst­ring(start, end)substring from start to end-1
toUpp­erC­ase()returns copy of s in ALL CAPS
toLow­erC­ase()returns copy of s in lowercase
indexOf(x)index of first occurence of x
replace(old, new)search and replace
split(regex)splits string into tokens
trim()trims surrou­nding whitespace
equals(s2)true if s equals s2
compa­reTo(s2)0 if equal/+ if s > s2/- if s < s2

StringTokenizer

A class in java that is used to break a string into tokens based on given delimeter(s), by default breaks at whitespaces

Initialising

// To break the string at whitespaces, use the following code
StringTokenizer st = new StringTokenizer(string_value_or_variable);
// To break the string at multiple delimeters, use the following code
StringTokenizer st = new StringTokenizer(string_value_or_variable, delimiter_string);

Functions available in the StringTokeniser Class

CommandDescription
countTokens()Returns the number of tokens present
hasMoreToken()Checks if there are more tokens in the string
nextElement()Return the object of the next element in the stream
hasMoreElements()Checks if there are more elements in the string
nextToken()Returns the next token from the StringTokenizer.

Example to break the string at whitespaces

StringTokenizer st = new StringTokenizer("Hy there, how are you? Hoping you are doing great!");
while (st.hasMoreTokens())
{
	System.out.print(st.nextToken() + " ; ");
}

Output : Hy ; there, ; how ; are ; you? ; Hoping ; you ; are ; doing ; great! ;

The semi colon is used to seperate the tokens

Example to break the string at multiple delimeters

// The following scheme can be used to break a punctuated string, into words
StringTokenizer st = new StringTokenizer("Hy there, how are you? Hoping you are doing great!", ":,!? ");
while (st.hasMoreTokens())
{
	System.out.print(st.nextToken() + " ; ");
}

Output : Hy ; there ; how ; are ; you ; Hoping ; you ; are ; doing ; great ;

The semi colon is used to seperate the tokens

Collection

List

TypeDeclaration
ArrayListList arr = new ArrayList();
LinkedListList arr = new LinkedList();

Set

TypeDeclaration
HashSetSet set = new HashSet();
TreeSetSet set = new TreeSet();
LinkedHashSetSet set = new LinkedHashSet();

Operations on List and Set

MethodDescriptionDeclaration
addTo add an element into the listarr.add(element)
removeTo remove an element into the listarr.remove(element)
getTo get an element at particular indexarr.get(element)
setTo set the element at a particular indexarr.set(index, element)
sizeTo get size of the listarr.size()
containsTo check if the list contains the elementarr.contains(element)
indexOfTo get the index of the elementarr.indexOf(element)

Map

TypeDeclaration
LinkedHashMapLinkedHashMap linkedHashMap = new LinkedHashMap();
HashMapHashMap hashMap = new HashMap();
TreeMapTreeMap treeMap = new TreeMap();

Queue

TypeDeclaration
QueueQueue queue = new LinkedList();
PriorityQueuePriorityQueue priorityQueue = new PriorityQueue();
ArrayDequeArrayDeque arrayDeque = new ArrayDeque();