Programming Language

Programming Language in Java

Pinterest LinkedIn Tumblr

Java is a general-purpose object-oriented programming language. It is a platform independent language which means, the application developed based on one platform can deploy and run on a different platform. If you develop an application on windows operating system, you can run the application on Linux operating system.

JVM, JRE and JDK

The java programming language requires java virtual machine (JVM) to run the application. The JVM is a platform which run the java bytecode. Java Runtime Environment (JRE) provides the language code libraries, java virtual machine, and other components which help to run the java application. Oracle provides different JVM/JDK for Mac OS, Solaris SPARC, Solaris, Windows operating system. Java Language and Virtual Machine build on top of Specifications. Many companies (Ex oracle, IBM, HP) develop the JDK based on the specification.

Java development kit (JDK) helps to develop and build the java application. It contains tools needed to develop the Java programs.

Java download location: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Little History

Java has been developed by James Gosling at Sun Microsystems on 1996. It released version JDK1.0. Oracle acquired Sun in 2010 and oracle maintain the current release and roadmap about the java programming language. The current stable version is Java SE 8.

Java version History: https://en.wikipedia.org/wiki/Java_version_history

Oracle maintain the time java timeline: http://oracle.com.edgesuite.net/timeline/java/

Develop Java program

Java source code is a plain text file with java extension. JDK provide the compiler to compile the source code. The developer can use a plain text editor to develop java program. We also have an open source Integrated development environment which provide develop, build and debug the java program. You can also use the commercial version of IDE like IntelliJ IDEA.

Download the open source development environment from the following location
https://eclipse.org/downloads
https://netbeans.org/downloads

Analysis of Hello World

The package uses to organize the java files and group logically. Each java source file should contain at least one public java class with same as file name. If you create java with a package, it should create under the package directory.

Java program starts with the main method and each program must have one main method. The static-access specifier helps to load a class without creating the object. So, the java program defines public and static main function. String[] args takes the argument from the command line. If the user wants pass some arguments to the program, the user can pass the arguments liketest arg1 arg2

the arg1 and arg2 pass to the args array which can be used later in the java program.

OOPS!

Java is an object-oriented programming. The object is software component with State and behavior. The class is a user-defined data type or the prototype which helps to create the object. Object oriented programming supports object oriented concepts.

  1. Encapsulation- hide the internal details of the class
  2. Polymorphism – gives multiple forms of the same functionality
  3. Inheritance – create the new class from existing class
  4. Abstraction-abstraction is the process hiding irrelevant details and expose only essential futures

Variables and operators

Variable names used for the memory space. Variable can change the value at any time. But the constant cannot change the value later.

Operators help to operate the variable with different values. The data structure and algorithm many uses the following operators.

Assignment Operator

Nooperdescriptionexplanation
1=Simple assignment operatorAssign value from right side to left side variable

Arithmetic Operators

Nooperdescriptionexplanation
1+Additive operatorAdd two values or variables
2Subtraction operatorSubtract two values
3*Multiplication operatorMultiply two values
4/Division operatorDivide two values
5%Remainder operatorGive the remainder of given two values

Unary Operators

Nooperdescriptionexplanation
1+Unary plus operatorShow positive number
2Unary minus operatorShow negative number
3++Increment operatorIncrement the value by 1
4Decrement operatorDecrement the value by 1
5!Logical complement operatorCheck the negative or positive value

Equality and Relational Operators

Nooperdescriptionexplanation
1==Equal tocompare two values
2!=Not equal toNot equal of two values
3>Greater thanCompare the greater than value
4>=Greater than or equal toCompare greater than or equal to value
5<Less thanCompare less than
6<=Less than or equal toCompare less than or equal to valu

Conditional Operators

Nooperdescriptionexplanation
1&&Conditional-ANDTrue only both condition is true
2||Conditional-ORTrue either one condition is true
3?:TernaryTernary operator to compare and assign value

Bitwise and Bit Shift Operators

Nooperdescriptionexplanation
1~Unary bitwise complementinverts a bit pattern
2<<Signed left shiftshifts a bit pattern to the left
3>>Signed right shiftshifts a bit pattern to the right
4>>>Unsigned right shiftshifts a zero into the leftmost position
5&Bitwise ANDperforms a bitwise AND operation
6^Bitwise exclusive ORperforms a bitwise exclusive OR operation
7|Bitwise inclusive ORperforms a bitwise inclusive OR operation

Control flow

Control flow statement uses to control the flow of execution, make decision and branching and looping.

The following statements helps to make decision

If – If the condition is true, it execute the branch of statements

If(i < 10{
    System.out.println(" I value is less than 10");
}

If-else – If the condition is true to execute a set of the statement from one block. Otherwise, it executes another set of the statement.

If(i < 10{
    System.out.println(" I value is less than 10");
}else{
    System.out.println(" else part");
}

If-elseif-else – If the condition is true to execute the set of the statement from one block. Otherwise, it executes another set of the statement.

If(i < 10{
    System.out.println(" I value is less than 10");
}else if( i>10){
    System.out.println(" I greater than 10");
}else if(i==10){
    System.out.println(" I ==10");
}else{
    System.out.println(" else part");
}

Switch statement

Switch statement selects the appropriate value based on the month name. The break statement allows to choose the only one-month number. If we do not add break statement, it executes all the remaining switch statements.

The following example shows month number from the string description.

switch (month.toLowerCase()) {
    case "january":
        monthNumber = 1;
        break;
    case "february":
        monthNumber = 2;
        break;
    case "march":
        monthNumber = 3;
        break;
}

The following statement loop the statements.

For loop

The for loop executes from beginning to till meet the condition.

For(int i=0;i<10;i++) {
    System.out.println(" I value : " + i);
}

For-while-dowhile

While and do-while loop are the looping statements. While loop checks the condition first before executing the code. The do-while execute the statement first and check the condition. The while loop does not execute without meet the condition. Do-while executes at least once.

While(i <10){
    System.out.println(" I value : " + i);
}
do{
    System.out.println(" I value : " + i);
} While(I <10);

Break-continue-return

The break statement breaks the current control loop and executes the next statement after the loop statement. The continue breaks the current remaining statement in the loop and continues from next iteration onwards. The return statement returns the value to callee function from the caller.

Difference between the break and continue
System.out.println ("starting loop:");
for (int n = 0; n < 7; ++n)
{
    System.out.println ("in loop: " + n);
    if (n == 2) {
        continue;
    }
    System.out.println ("   survived first guard");
    if (n == 4) {
        break;
    }
    System.out.println ("   survived second guard");
    // continue at head of loop
}
// break out of loop
System.out.println ("end of loop or exit via break");
 
 
Return from the function
Public int add (int a, int b){
    Return a+b;
}

Generics

Generics are generic programming support like the template in C++. It introduced in J2SE 5.0 and main future in java collection. Generics added to verify type safety and validate the type during compile time itself rather than run time. The compiler translates all type information into Object type and removes all the information related to the type parameter. Type erasure makes sure the binary compatibility with java libraries and applications created before generics.

List< String> list = new ArrayList< String>();
list.add("Hello");
list.add("World");
Generics validate the type during compile time itself. We do not have to cast between the types.
public interface Pair< K, V > {
    public K getKey();
    public V getValue();
}

More about the generics: http://docs.oracle.com/javase/tutorial/java/generics/index.html

Exceptions

Exceptions are abnormal conditions and java provide a set of API to handle the exceptional conditions. Java supports (1) Checked exceptions (2) Run time exceptions (3) Errors. The Exceptions and Errors are derived from Throwable class.

Checked exceptions are user error and should catch by appropriate exception. The system expects the developer should try/catch/finally the exception. Example IOException

Runtime exceptions are an exception which throw by java runtime. The developer no need catch the runtime exception. Example IllegalArgumentException, ArithmeticException, BufferOverflowException, BufferUnderflowException, NoSuchElementException

Errors are not exceptions. The developer no need catch or throw error. Example StackoverflowError java.lang.OutOfMemoryError, Java.lang.NoClassDefFoundError, java.lang.UnSupportedClassVersionError.

try{
    fis = new FileInputStream("B:/myfile.txt");
}catch(FileNotFoundException fnfe){
    System.out.println("The specified file is not " +
            "present at the given path");
}

File system

The file operations use to read and write the files. It supports byte stream, character streams, buffer streams, data stream and object stream. The byte stream helps to read and write the byte array information to file and read back. The character stream store character values using Unicode conventions. If the user wants sort large file, they can store all the values in the file and start use.

FileReader inputStream = null;
try {
    inputStream = new FileReader("c:/a.txt");
    int c;
    while ((c = inputStream.read()) != -1) {
        System.out.println(c);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Collections

Collections build on top of generics. All the collections use wrapper classes and not support primitive types. Java collections framework is a set of classes and interfaces that implement reusable data structure and algorithms. Most of the collection classes are derived from Collection interface.

Java tutorials explain well about the collection classes.

https://docs.oracle.com/javase/tutorial/collections

List of collection classes

Collection interface
  • Set-cannot contains duplicate elements
  • List-ordered Collection
  • Queue- Queue is a collection with First in first out order
  • Deque – linear collection of elements that supports the insertion and removal of elements at both end points
  • Map-contain key and value. Value can be duplicate but not keys
Implementations
  • HashSet – HashSet is much faster than TreeSet, guarantee duplicate-free collection of elements, makes no guarantees as to the iteration order, permit null
  • TreeSet-guarantees that elements of set will be sorted
  • LinkedHashSet-provides ordering support by keep elements in the order
  • ArrayList-offers constant-time positional access, Positional access requires constant time
  • LinkedList-Positional access requires linear-time
  • ArrayDeque-Resizable-array implementation of the Deque
  • HashMap-maximum speed and don’t care about iteration order
  • TreeMap-doesn’t allow null keys, SortedMap operations or key-ordered Collection-view iteration
  • LinkedHashMap- near-HashMap performance and insertion-order iteration
Algorithms
  • Sorting- sort the items in the containers in ascending or descending order
  • Shuffling – shuffle the element (do not maintain any order)
  • Routine Data Manipulation-the normal data manipulation like fill, addAll, reverse, copy, swap
  • Searching- Search particular item in the list
  • Composition-contain frequency and disjoint algorithms
  • Finding Extreme Values – finding the minimum and maximum values from the list

Careerdrill explains the collection framework with an example.

Missing!

We didn’t cover each and every topic from java programming language. We didn’t cover Network programming, Interposes communication, Security, Reflection, JAXP, JNDI, JDBC, Java Bean, Internalization, GUI, deployment, J2EE topics and Regular expression. We covered the basic programming language syntax which helps to understand the Data structure and algorithm point of view.

You can always learn the topics from recommended books and useful links.

Write A Comment