Introduction - Programming: Java, JavaScript Coding For Beginners – Learn In A Day (2015)

Programming: Java, JavaScript Coding For Beginners – Learn In A Day (2015)


Introduction to Java

Java – one of the most popular programming languages of the internet age was conceived and developed in 1991 at Sun Microsystems. The evolution of any programming language is driven by necessity that arises due to development in the computing ecosystem – and java was no exception.

Though code written in C or C++, the powerful predecessors of Java could also run on all devices, the effort required to compile them each time to make it work on specific devices was very expensive.

Java overcame this by simply taking the text source code(.java) and compiling it to an intermediate byte code (.class) file, which can then be interpreted by any device running an interpreter - Java Virtual machine (JVM). The idea of byte code meant the code became architecture neutral, needs to be compiled only once and can be interpreted on any device which can run a JVM on it.

Today, Java has grown into an important programming language and it is become almost imperative for anyone interested in programming to know at least the basics of Java. This book has been written exactly for this purpose. I want to help anyone with little or no prior programming experience get an easy and effective introduction to java programming.

Getting started


Before anything else, we need to get our development environment ready. Beginners can use online development environment ( ) to execute small snippets of code, but if the code to be executed is a full-fledged program, then one must install java to their system and setup their own offline development environment. Java comes in three types –

· The Micro Edition (J2ME)

· Standard Edition (J2SE)

· Enterprise Edition (J2EE)

For personal use, one can download .exe of latest SE version corresponding to their operating system from the download page. After installing, check that the PATH variable points to the java installation. Executing “javac” from the terminal window will display the version of java installed on the screen.

Code Structure

Every java code is saved with the extension “.java”. Each java program contains one or more classes. Each of these classes contains one or more method definitions and each method carries a few statements in it.

Syntax and meanings of keywords:


public class MyFirstProgram {

public static void main(String[] args) {

//This is my first java program

System.out.println(“ Hello World !”);



import*; - The keyword “import” is used for including java libraries called “packages” which contain pre-defined functions that can be used in the program.

Public class MyFirstProgram - this is the class definition, the key word “public” indicates that this class is available to all and “class” denotes to be a class definition.

MyFirstProgram – This is the name of a class. Name of the class having the main() function should be the same as the source file name.

The class definition is enclosed within the parenthesis {}

Public static void main (String args[]) : This is the main part of the program. Since main() is the driver function, it should always be “public”.

Static: You need to keep in mind that main() method should always be “static” because it makes the program memory efficient.

Void: This is the return type of the method. This means that the main() method will not return anything.

Main: name of the method. The interpreter starts execution from the main() method only. Running a program means instructing the JVM to “load “ the .class file which was compiled from the source code and start executing from the main() method.

The two uses of the main method can be summarized as:

1. To Test all the other methods of the program

2. To Start execution of the program.

String[] args : is the argument that is passed to the “main” method. This method always takes an array of strings as its input parameter, and the array name should always be “args”.

Note that the data type starts with a upper case “S”, this is because “Strings” is a class in Java and all class names start with upper case.

The definition of the method is enclosed within flower braces{}, in this case, the only thing that we want our program to do is print “Hello World!”

Toprint a statement to standard output console, “System.out.println(“”) ;”is used. Note that all statements must end with a semi-colon (;)

You can also use System.out.print () to display output, the difference is that print”ln” introduces a new line at the end of each statement it prints.

The other statement within the main() method in our program is called a “comment” statement. These are not compiled, the purpose of these statements which are preceded by “//” are only to give the programmer more information about code.

Java doesn’t have the concept of global variables at all, the same is achieved using keywords such as “fina;, “static”, “public”.

Object Oriented Programming

Java, has its syntaxes similar to C while programming philosophy from C++ - that is, java is an object oriented language.

In the first example that we saw, we had a class declaration and said that the main() function takes care what gets done in our program, well, that doesn’t make java a OOP language, let’s see an example of to understand OOP - objects and classes better.

Procedural Approach

It is not that simple, because the previous shapes were definite and animation code could have assumed a centre point and rotated the shape, while in case of an indefinite shape like amoeba, it’ll not rotate using the code for other shapes, instead the API needs to take couple of more arguments o define the co-ordinates on which the shape should rotate.

Object Oriented Approach

So you can write one class file each for the shapes, so adding amoeba or modifying to rotate method is done without disturbing existing code, by simple adding a new class. You need to test only the new class, any new issue introduced can be easily tracked to the new changes made.

Example 1:

class Movie{

//variable Declaration


}m1; //m1 isan object of classtype “Movie”

Example 2:

class Movie{

//variable Declaration



class TestMovie{

public static void main(String[] args){

Movie m1 = new Movie(); // m1 is an object of type “Movie”

m1.variable = value;




Variable Declaration & Data Types

The next most important and fundamental concept to learn is about “variables” and “data types” to create useful programs. Variables are basically named memory location, which are used to hold values. Java is a strongly typed language, so the variable of type “x” can hold a value of type “x” only.

For example:

int n;

Here a variable “n” is declared to hold value of type “int”. Declaring variable type ensure “type-safety” feature of java which in turn contributes to “security”.

Variables in java can be either

· Local Variables ( primitive data types like int, float, double, Boolean etc)

· Reference Variables ( objects – user defined instances of class)

Assume that you declared a variable of type int, you can probably use it to save a short value. If done otherwise, it’ll overflow.

Also note that java thinks anything with decimal point is by default a “double”, therefore it’s important to append a “f” at the end of a given decimal number to make it a double.

float f = 1.56f;

Rules for declaring variable names:

· Do not use any predefined reserved words as variable names.

· Variable names cannot start with a number.

Some popular Java keywords that one should know :


String is declared as a class. Some of the commonly used operations on string are:

String str = “Hello World”; //declaration

int len = str.length() ; // Givesthe length of the string

int len = “hello Wolrd”.length(); // also gives length of the string

String concatStr = “hello”+”world”; // the + operator can be overloaded to perform concatenation of two strings.

String str1 = “Heloo”;

String str2 = “World”;

if (str1 == str2) //compare two strings

System.out.println(“strings are equal”);

Reference Variable

Movie m1 = new Movie()

To the left is the declaration which instructs the JVM to reserve space for the reference variable which holds the data to reach the actual object.

int[] n; // declare an array of integers

n = new int[5]; //creates an array of 5 integers

Note that even if its an array of primitive data type values, an array becomes an object.

Movie[] mArray; // declarean array of objects oftype “Movie”

Size: There is no predefined size for reference variables like primitive types.

Equals Operation

We know that comparison operators like == and != can be used on primitive operators, but in order to perform comparison operation on objects, one cannot use the default operators, instead java provides keywords “equals”.

Array List

This is available in the java.util.ArrayList package.

ArrayList<String> myList = new ArrayList<String>();

It allows the declaration of an array with different data types. It offers multiple methods to perform common array operations like add(elem) remove(index) to add/remove elements from the arrayList. Also API’s like size() to find the length of array, to find if isEmpty() or if the arrayList contains() a given element.

Let’s see an example using the concepts learnt so far,

Class MyProgram{

public static void main(Strings[] args)


//declare and assign variables

int num = 10;

float fNum = 10.5;

//print statements to output consoles

System.out.println(“The value of integer num is : ”+num);

System.out.println(“The Value of integer fNum is : ”+fNum);

num = num/2;

fNum = fNum+num;

System.out.println(“The value of integer num after operation is : ”+num);

System.out.println(“The Value of integer fNum after operation is : ”+fNum);



Output :

The value of integer num is : 10

The value of integer fNum is : 10.5

The value of integer num after operation is : 5

The value of integer fNum after operation is : 20.5

You just have to use + operator in the SoP ( System.out.println) statement.

Control Statements

The control statements in a program, as the name itself suggests, control the general flow of every program. It includes conditional statements like if else, or iteration statements like while (), do while() etc.

If else :

Syntax :


do action1;


do action2;

An action is taken when the ‘condition’ is true, or else the action in the else part is taken.

Switch case

This operation comes in handy if you had to check for multiple conditions. Switch case takes action based on a given value.

Syntax :



Case id1:



Case id2:







While ()

This is an iteration statement, which performs action as long as the condition is true.




Do something while condition is true;


Do - while ()

This too is an iteration operation, quite similar to the while() loop, the difference being that the loop will execute at least once irrespective of the validity of the condition, because the condition is evaluated only after the “do” statement.



do Something;


For loop

Syntax: for ( initialization ;condition; counter updation);

Example : for (int i=0; i<5; i++)

This will now execute the statement for exactly 5 times. The first part declares and initializes a value to the counter variable, the second part checks the condition, if true, it enters loop. On completion of loop, it performs the increment. Then it again checks the condition and continues the same steps till the condition turns false. Once the condition is false, it exits out of the loop.


Class MyProgram{

public static void main(Strings[] args){

//declare and assign variables

int num = 5, i;

while( num > 0){

System.out.println(“The Value of integer Num is : ”+num);



for(i =0;i<5;i++)

System.out.println(“The Value of integer Num is : ”+num);




The Value of integer Num is : 5

The Value of integer Num is :4

The Value of integer Num is :3

The Value of integer Num is :2

The Value of integer Num is :1

The Value of integer Num is :5

The Value of integer Num is :5

The Value of integer Num is :5

The Value of integer Num is :5

The Value of integer Num is :5

The above stated program used two looping statements to perform the operations.


Encapsulation, as the name suggests, capsules the data. In simpler words, it hides the dada, thereby providing data security.

Arguments passed can be either by value or reference. The data type is declared after determining which one to use.

A method of the class is accessed by the object using the dot (.) operator.

Movie m1 = new Movie()

M1.printName(); //print the name of the movie

Or; //play the movie n times

In the following example, a getter is used to read the value of a class variable and then set a value to the variable.

public class GetterSetter{

//Declaring instance variables

private String name;

private int age;


public int getAge(){

return age;


public String getName(){

return name;



public void setAge( int newAge){

age = newAge;


public void setName(String newName){

name = newName;



//class to test the getter and setter methods

public class TestGetterSetter{

public static void main(String args[]){

TestGetterSetter gs = new TestGetterSetter();



System.out.println("Your name is: "+gs.getName());

System.out.println("Your age is: "+getAge());



Output :

Your name is: John

Your age is: 3

Introduction to JavaScript

JavaScript is an object based dynamic scripting language. Netscape is the developer of this language. This language is used for the development of server applications and web pages. It is the most widely used scripting language in the world.

The only thing similar in Java and JavaScript is their similar sounding names. Rest, the languages are completely different with regard to their functions and concepts. What makes JavaScript stand out from the object oriented programming languages like Java and C++ is that its objects can be created or modified during the run time. For doing this, Methods and properties are added to the empty objects. An object once created can be used like a prototype in the process of creating other similar objects.

Variable parameter lists, source-code recovery, dynamic script creation, dynamic object creation function variables etc are the dynamic capabilities that JavaScript has.