Introduction To Java Programming

Introduction To Java Programming

get started with java programming

The first question, what is this Java stuff anyway… well Java is an “Object Oriented Programming”(OOP) language. We will know about OOP in the next part, first of all we must know what is a programming language… It’s actually giving the computer instructions to carry out specific job, or “teaching the computer several ways to solve problems”. If you don’t have any programming experience, then let me tell you to write any program think how do you yourself will solve it in real world, then translate your thoughts in the programming language. So let’s start with Java…

History and Usage

The team which created Java was under James Gosling, and they worked for Sun Microsystems to create a platform-independent programming language. The first implementation was done in the fall of 1992, then it was called ‘Oak’ but the name was later changed to ‘Java’ due to some legal snags. The first public announcement of Java was done in 1995.
Since then Java turned out to be a global hit, it was a revolution in internet for its applets. Major companies like Google and Amazon extensively uses Java. Also java produced maximum number of jobs in 2013.


How Java works

Java Compiler Process

To work with Java you will need Java Development Kit (JDK) installed in your computer. We will work with Java SE(Standard Edition) 1.7 in this tutorial. Download JDK for free from here.
The legend of Java is in “Byte Code”. When we write a Java program we store it in a file with .Java extension, after compiling we get a file with .class extension. This is the portable file which holds the byte code, which can be taken to any computer with any platform and be run. The byte code is interpreted with JVM (Java Virtual Machine), which converts all the Java code to machine. Thus, Java is both compiled and interpreted language.
SOURCE CODE»javac(JAVA COMPILER)»BYTE CODE»JVM»MACHINE CODE.


Concepts Of OOP

If you are already versed with the concepts of OOP or done any other OOP language such as C++, you may skip this part.
The main concept of OOP is PIE, or Polymorphism Inheritance Encapsulation. We will now deal with these heavy looking terms.

Concepts Of OOP

Polymorphism

Lets take the word ‘cell’ we use it to define the structural and functional part of living things or a mobile phone or a jail room or intersection of rows and columns in excel. You can see that a same word is used to define many things, this is the concept of polymorphism. We can do the same in java, the practical part of this comes in the later tutorials.


Inheritance

A son has many characteristics of his parents and this is only the general idea of inheritance, the same applies to programming, its carrying common attributes or behaviours from one entity to another.


Encapsulation

Its packing several attributes or entities in an single entity, for example we have several words- Plant, Animal, digestion, stomata, stomach, transpiration, we can see the are jumbled words with plant and animal organs and processes. This is what happens in Procedure Oriented Programming, but in
OOP we don’t let them float around but we pack them. Animal{digestion(stomach)} Plant{transpiration(stomata)}. In programming terms Animal and Plant are classes, digestion and transpiration functions and stomach and stomata data members. We will discuss these terms later on in detail.


Java Classes, Functions and Objects

Before we start coding we must know what these are. Well class is a collection of data, functions, etc. actually it is the encapsulating entity. It is also called the object factory, a collection of classes is known as package.
Objects contains all the characteristics of a class, any function or data member of the class it belongs to can be accessed through it
(Though it depends on the visibility modes, about which we will discuss in later tutorials).
Functions are the code blocks in which the work is done, we write the code to be executed in functions.
We may take Car as a class, BMW and Ferrari can be considered its objects and driving its function.


The First Java Program


Let’s now start up with coding (finally..!!). Here is a very very simple Java program, have a look:
class CodeNirvana {
    public static void main(String h[]){
        System.out.print("Hello world from Code Nirvana");
    }
}


Output:

Hello World Output

Now let’s have a post-mortem of the program. We begin with the class keyword, it declares a class called CodeNirvana… Here’s the syntax- class<class name>. 
We may give any class name but it is the convention to begin the class name with a capital letter and start every new word with a capital letter.
Next we write a brace to begin defining the class in Java we start a code block with a { and end it with a }. The code block opened at last must be closed at first.
Then we write the word “public static void main(String h[])”, we will discuss these words in detail in our tutorial about functions. For now, you should know that these words are to define a function called “main” from which most of the Java programs starts to execute. Remember, when you code in general, then “main” method is must.
Then comes the important part of the System.out.print(); statement, this is the displaying statement of Java, whatever letters we want to write on the console we will write it in double quotes. System.out.print(); displays the content but dose not takes the cursor to the next line, whereas System.out.println(); displays the content and takes the cursor to the next line.
You may notice the “;” after the statement, the semicolon is used to terminate each statement, behold my friends!! This is the place where most programmers get their bugs.


Using Numbers and Variables

We will discuss about all variable types in the next tutorial, here we will use only the “int” type. First of all, what is a variable? Well, they are named memory spaces to store data while running the program. 

Syntax to declare a variable: <data type> <variable name>;

Assign it a value: <variable name>=<value>;

lets join it..
<data type> <variable name>=<value>;
Example: int a=10;

Remember a variables value can be changed any time but the declaration has to be made only once.
We may declare multiple variables with same data type like this…
int a=0,b=1,c=9………z=7;

Every variable in Java has a data type, Here we use “int” it is to store an integer constant.


Few Operators with variables

Let’s use the basic mathematical operators now.
int a=10+5;
now, a=15
int b=a*10;
now b=150;
Simple, isn't it.
System.out.print() with variables.

To display any variable we don’t need to give the double quotes, let’s take an example

int a=25;
System.out.print(a);
Outpur: 25.

We may do a calculation:

int a=5;
int b=10;
System.out.print(a+b);
Output: 15

We may display a variable’s value along with letters using the ‘+’ operator like this:

int a=100;
System.out.print(“Hundred=”+a);
Output: Hundred=100

But to do a calculation along with displaying a string(Group of letters) needs another bracket:

int a=5,b=10;
System.out.println(“Sum=”+a+b);
System.out.print(“Sum=”+(a+b));
Output:
Sum=510
Sum=15

Beware of this mistake:
int a=10;
System.out.println(a);
System.out.print(“a”);
Output:
10
a

Remember whatever we write in double quotes will be displayed as it is(Except the escape sequences…don’t worry, this all ill come in the third tutorial)


Running the Java program

First we have to write the code in any text editor like notepad or notepad++, then save it with the class name as the file name and with .Java extension. Now where to save it? It should be saved in the bin folder of the jdk’s folder in your Java root directory. The path in Windows XP using jdk1.7 update 45 is:  C:\Program Files\Java\jdk1.7.0_45\bin
Or, you may change your “path” environment variable to the path of your bin folder like this in command prompt:  set path= “C:\Program Files\Java\jdk1.7.0_45\bin”


Best IDE for Java Programming: Visit Here

Next you must compile the program with javac command like this
javac “<file path>”
Example:
javac “C:\Program Files\Java\jdk1.7.0_45\bin\CodeNirvana.java”

If there is any syntax error it will be displayed else a .class file will be created. Now to run it we will use the Java command after navigating to the directory where the .class file is.

java <class name>
Example:
java CodeNirvana

Your program will now run successfully…

Conclusion

You now have the basic idea of Java, more will come in the next tutorials on Code Nirvana, if you have any problem in any part please feel free to comment and don't forget to subscribe to the Code Nirvana newsletter to get notifications about tutorials to your email  id for free. Keep coding...

NEXT: Data Types and Variables In Java

28 Comments Leave new

Hi please help me with logic of this problem where I have an array {1,2,3,4} and I want to make it as {1,1,2,2,3,3,4,4}

Reply

Hello!
Below is the logic required to do so:

public class Main {
    public static void main (String[] args){
            int A[] = new int[] {1,2,3,4};
            int B[] = new int[A.length*2];  //double the size of A[]
            for(int i=0,k=0;i<A.length;i++,k++){
                B[k]=A[i];
                B[++k]=A[i];
            }
            for(int i=0;i<B.length;i++)
                System.out.print(B[i]); //Print B[]
    }
}

Reply

Thank you for quick reply, Love this site :)
Could you please help me with logic of removing duplicate elements from an array

Reply

Glad to know you like Code Nirvana, you can also like us on Facebook to get in touch!

For your program, their are many approaches to do so......
I am doing it by storing the unique elements into an String first, using contains function and than splitting and converting it to an integer array!
Check the code:


class Main1 {
    public static int[] UniqueArray(int A[]){
        String unqElements="" , unqArray[];
        for( int i=0; i<A.length; i++ ){
            if( ! unqElements.contains( ""+A[i] ) ){
                unqElements+=A[i]+",";  //Storing unique elements in a String
            }
        }
        unqArray = unqElements.split(",");      //Spliting to String Array
        int B[] = new int[ unqArray.length ];   //New Array with desired size
        for( int i=0; i<unqArray.length; i++ ){
            B[i] = Integer.parseInt( unqArray[i] ); //String->Int conversion
        }
        return B;   //return new array with unique elements
    }
    public static void main(String Args[]) {
        int A[] = new int[] {1,2,3,3,2,1};
        A = UniqueArray(A); //calling function to return new array
        //printing new array
        for(int i=0;i<A.length;i++){
            System.out.print(A[i]);
        }
    }//end of main
}


If you have difficulty at any step, let us know!

Reply

Thank you for code Admin. I have request to make, please make a separate page/thread for Array & String related programs as they are most frequently asked questions in interviews. It will be great help for job seekers like me

Reply

Please wait for sometime, Code Nirvana will have a major makeover soon!
I will take care of your feedback!
Thanks, btw what you doing Rupesh :)

Reply

I am B Tech 2013 Passout, still looking for job..... :)

Reply

Ok, Best of luck.... hope you will get a good job soon!

Reply

Thank you sir :)
sorry to trouble you again. Please help me with logic of
1.sorting an array without using Arrays.sort()/nested For Loop & any API like Collections
2.program to check if a number is odd or even without using %, / and bitwise operators
Thanks in advance

Reply

for sorting what you want without using for loops as well? means all the sorting algorithms uses nested loops either for or while but you have to use loop...
and for your even-odd problem you can use * (multiply) operation e.g. even*5->ends with 0 but odd*5->ends with 5.
so you can check that whether it ends with 5 or 0.

Reply

for sorting you can take as many as loops you require but only single for loop

Reply

how to find length of string without using inbuild method??

Reply

count total no. of time reach alphabet appears in the string without using inbuild method??plzz also explain

Reply

count no. of words in the string without using inbuild function...also explain in detail

Reply

count no. of duplicate words in string without inbuild method.,,,,also explain.

Reply

Sorting can be done without using for loops because all the loops either while or for work same so we can use while as well to sort the array,
Below program uses the bubble sort algorithm which I made using while loop only!

class Main1 {
    public static int[] bubbleSort( int A[] ){
       int i=0 , j , temp , n=A.length ;
        while( i < n ){
            j=0;
            while( j < n-i-1 ){
                if( A[j] > A[j+1] ){    //change to < for descending sorting
                    temp = A[j];
                    A[j] = A[j+1];
                    A[j+1] = temp;
                }
                j++;
            }
            i++;
        }
        return A;
    }
    public static void main(String Args[]) {
        int A[] = new int[] {5,4,0,3,2,1};
        A = bubbleSort(A);
        //Array is sorted now!
        for(int i=0;i<A.length;i++)
            System.out.print(A[i]);
    }
}

Reply

sir plzz,,give answers of our all programmes,,my all friends are waiting for ur response,plzz sir,,,its urgent...

Reply

Hello Neeraj,
Please keep calm, you asked many questions and you need explanations as well so we are going to post all the programs within 2 days! We will try to solved at least 4-5 today only.
So, keep in touch and give us time.
Thanks and respect you and yours waiting!

Reply

You can check our latest post on the homepage feed for this problem!
We will post all the questions soon..... keep visiting

Reply

This one is done as well! do check the latest post.

Reply

This one is also done with a long explanation... hope you and your friends don't have any problem understanding this! check the latest post.

Reply

Hello Sir,
What is Singleton class in Java, How do we code one....?

Reply

y u did not find any job so far?

Reply

Actually I found one, I was hired in an MNC last december :)

Reply

Sir plz help me to short out this problem :
Find the sum of s
s = 1-2 + 3 cube 3/!3 - 4 to the power 4/!4 + 5 to the power 5/!5 ……….till nth term


Reply

hello i want a simple code to print number patter .when i enter a number,based on the number count only print the patter .
example if i gave my number as n=5,then
12345
12345
12345
12345
12345
i want like thius plz mail it or comment here.\

Reply
This comment has been removed by the author.

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.