Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Java Language Basics

JAVA LANGUAGE BASICS

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

Features of Java:

Java is −

  • Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

  • Platform Independent −Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

  • Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.

  • Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

  • Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.

  • Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.

  • Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

  • Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.

  • Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.

  • High Performance − With the use of Just-In-Time compilers, Java enables high performance.

  • Distributed − Java is designed for the distributed environment of the internet.

  • Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

First Java Program:

public class MyProgram 

{

public static void main(String []args) 

{

       System.out.println("Hello World"); // prints Hello World

    }

}

class : class keyword is used to declare classes in Java

public : It is an access specifier. Public means this function is visible to all.

static : static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. The main() method here is called by JVM, without creating any object for class.

void : It is the return type, meaning this function will not return anything.

main : main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.

String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.

System.out.println : This is used to print anything on the console like printf in C language.


In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine. 

Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer.

Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

  • Open notepad and add the code as above.

  • Save the file as: MyProgram.java.

  • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.

  • Type javac MyProgram.java and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).

  • Now, type java MyFProgram to run your program.

  • You will be able to see ' Hello World ' printed on the window.


Output

C:\> javac MyProgram.java

C:\> java MyProgram 

Hello World

An overview of the software development process.

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. 

Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. 

This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code. 

Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS

Through the Java VM, the same application is capable of running on multiple platforms.

The Java Platform

A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: 

  • The Java Virtual Machine 

  • The Java Application Programming Interface (API) 

You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms. 

The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages

Figure showing MyProgram.java, API, Java Virtual Machine, and Hardware-Based Platform

The API and Java Virtual Machine insulate the program from the underlying hardware.

NOTE:Before running any java program set the path.

How to set path in Java

The path is required to be set for using tools such as javac, java etc.

If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the tools will be available in the current directory.

But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

  1. temporary

  2. permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

  • Open command prompt

  • copy the path of jdk/bin directory

  • write in command prompt: set path=copied_path

For Example:

set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:

  • Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Java Tokens

A token is the smallest element of a program that is meaningful to the compiler. These tokens define the structure of the Java language. When you submit a Java program to the Java compiler, the compiler parses the text and extracts individual tokens.

Java tokens can be broken into five categories: identifiers, keywords, literals, operators, and separators. The Java compiler also recognizes and subsequently removes comments and whitespaces.

Identifiers :

“Identifiers means a sequence of uppercase(A,B,C,……,Y,Z) and lowercase(a,b,c,…..,y,z) letters, numbers(0,1 ,2,……,9), or the underscore(_) and dollar-sign($) characters and must not begin with a number.” Identifiers are tokens that represent names. These names can be assigned to variables, methods, and classes to uniquely identify them to the compiler.

Keywords :

“It is a special type of reserved word for a specific purpose which can not be use as a identifier means cannot be used as names for a variable, class, or method.”

There are 49 reserved keywords currently defined in the Java language

Valid and invalid Java identifiers.

Valid

Invalid

HelloWorld

Hello World (uses a space)

Hi_JAVA

Hi JAVA! (uses a space and punctuation mark)

value3

3value(begins with a number)

Tall

short (this is a Java keyword)

$age

#age (does not begin with any other symbol except _ $ )

Separators :

Separators are used to inform the Java compiler of how things are grouped in the code. For example, items in a list are separated by commas much like lists of items in a sentence. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements. Java Seperator are ; , {} () [] .

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.

Type

Syntax

Usage

Example

Single-line

// comment

All characters after the // up to the end of the line are ignored.

//This is a Single-line style comment.

Multiline

/* comment */

All characters between /* and */ are ignored.

/* This is a Multiline style comment.

Documentation

/** comment */

Same as /* */, except that the comment can be used with the javadoc tool to create automatic documentation.

/** This is a javadoc style comment. */

Java - 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

  • Reference/Object Data Types

Primitive Data Types

There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a keyword. Let us now look into the eight primitive data types in detail.

datatype2.JPG


Data Type

Default Value

Default size

Range

boolean

false

1 bit

true and false

char

'\u0000'

2 byte

\u0000 to \uffff (0 to 65535)

byte

0

1 byte

-128 .. 127

short

0

2 byte

-32,768 .. 32,767

int

0

4 byte

-2,147,483,648 .. 2,147,483,647

long

0L

8 byte

-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807

float

0.0f

4 byte

3.40282347 x 1038, 1.40239846 x 10-45

double

0.0d

8 byte

1.7976931348623157 x 10308, 4.9406564584124654 x 10-324

Java - Variable Types


Variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

You must declare all variables before they can be used. Following is the basic form of a variable declaration −

data type variable [ = value][, variable [ = value] ...] ;

Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

Following are valid examples of variable declaration and initialization in Java −

int a, b, c;         // Declares three ints, a, b, and c.

int a = 10, b = 10;  // Example of initialization

byte B = 22;         // initializes a byte type variable B.

double pi = 3.14159; // declares and assigns a value of PI.

char a = 'a';        // the char variable a iis initialized with value 'a'

Java - Basic Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

  • Arithmetic Operators

  • Relational Operators

  • Bitwise Operators

  • Logical Operators

  • Assignment Operators

  • Misc Operators


The Arithmetic Operators

Operator

Description

Example

+ (Addition)

Adds values on either side of the operator.

A + B will give 30

- (Subtraction)

Subtracts right-hand operand from left-hand operand.

A - B will give -10

* (Multiplication)

Multiplies values on either side of the operator.

A * B will give 200

/ (Division)

Divides left-hand operand by right-hand operand.

B / A will give 2

% (Modulus)

Divides left-hand operand by right-hand operand and returns remainder.

B % A will give 0

++ (Increment)

Increases the value of operand by 1.

B++ gives 21

-- (Decrement)

Decreases the value of operand by 1.

B-- gives 19



public class Test1 {

   public static void main(String args[]) {

      int a = 10,b=20,c=25,d=25;

      System.out.println("a + b = " + (a + b) );

      System.out.println("a - b = " + (a - b) );

      System.out.println("a * b = " + (a * b) );

      System.out.println("b / a = " + (b / a) );

      System.out.println("b % a = " + (b % a) );

      System.out.println("c % a = " + (c % a) );

      System.out.println("a++   = " +  (a++) );

      System.out.println("b--   = " +  (a--) );

      System.out.println("d++   = " +  (d++) );

      System.out.println("++d   = " +  (++d) );

   }

}



Relational Operators


Operator

Description

Example

== (equal to)

Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!= (not equal to)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> (greater than)

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< (less than)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= (greater than or equal to)

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= (less than or equal to)

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.


public class Test2 {

   public static void main(String args[]) {

      int a = 10;

      int b = 20;

      System.out.println("a == b = " + (a == b) );

      System.out.println("a != b = " + (a != b) );

      System.out.println("a > b = " + (a > b) );

      System.out.println("a < b = " + (a < b) );

      System.out.println("b >= a = " + (b >= a) );

      System.out.println("b <= a = " + (b <= a) );

   }

}


Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Operator

Description

Example

& (bitwise and)

Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| (bitwise or)

Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^ (bitwise XOR)

Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.

<< (left shift)

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> (right shift)

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 1111

>>> (zero fill right shift)

Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

A >>>2 will give 15 which is 0000 1111

public class Test3 {

   public static void main(String args[]) {

      int a = 60; /* 60 = 0011 1100 */

      int b = 13; /* 13 = 0000 1101 */

      int c = 0;

      c = a & b;        /* 12 = 0000 1100 */

      System.out.println("a & b = " + c );


      c = a | b;        /* 61 = 0011 1101 */

      System.out.println("a | b = " + c );


      c = a ^ b;        /* 49 = 0011 0001 */

      System.out.println("a ^ b = " + c );


      c = ~a;           /*-61 = 1100 0011 */

      System.out.println("~a = " + c );


      c = a << 2;       /* 240 = 1111 0000 */

      System.out.println("a << 2 = " + c );


      c = a >> 2;       /* 15 = 1111 */

      System.out.println("a >> 2  = " + c );


      c = a >>> 2;      /* 15 = 0000 1111 */

      System.out.println("a >>> 2 = " + c );

   }

}

Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Operator

Description

Example

&& (logical and)

Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false

|| (logical or)

Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.

(A || B) is true

! (logical not)

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true

public class Test4 {


   public static void main(String args[]) {

      boolean a = true;

      boolean b = false;


      System.out.println("a && b = " + (a&&b));

      System.out.println("a || b = " + (a||b) );

      System.out.println("!(a && b) = " + !(a && b));

   }

}

Assignment Operators

Following are the assignment operators supported by Java language −

Operator

Description

Example

=

Simple assignment operator. Assigns values from right side operands to left side operand.

C = A + B will assign value of A + B into C

+=

Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.

C -= A is equivalent to C = C – A

*=

Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.

C %= A is equivalent to C = C % A

<<=

Left shift AND assignment operator.

C <<= 2 is same as C = C << 2

>>=

Right shift AND assignment operator.

C >>= 2 is same as C = C >> 2

&=

Bitwise AND assignment operator.

C &= 2 is same as C = C & 2

^=

bitwise exclusive OR and assignment operator.

C ^= 2 is same as C = C ^ 2

|=

bitwise inclusive OR and assignment operator.

C |= 2 is same as C = C | 2


The ? : Operator

We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

To determine the value of the whole expression, initially exp1 is evaluated.

  • If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression.

  • If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

Operator Precedence

Finally let's add the &&, ||, &, | and ? operators to the precedence table 

  1. *, /, % Multiplicative operators 

  2. +, - Additive operators 

  3. <, >, >=, <= Relational operators 

  4. ==, != Then do any comparisons for equality and inequality 

  5. & Bitwise and 

  6. | Bitwise or 

  7. && Logical and 

  8. || Logical or 

  9. ? : Conditional operator 

  10. = Assignment operator 

Java - Decision Making

Java programming language provides following types of decision making statements. 

Sr.No.

Statement & Description

1

if statement

An if statement consists of a boolean expression followed by one or more statements.

if(condition) {

   // Statements will execute if the Boolean expression is true

}

2

if...else statement

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

if(condition) {

   // Executes when the Boolean expression is true

}else {

   // Executes when the Boolean expression is false

}

3

nested if statement

You can use one if or else if statement inside another if or else ifstatement(s).

if(condition) {

   // Executes when the Boolean expression 1 is true

   if(condition 2) {

      // Executes when the Boolean expression 2 is true

   }

}

4

if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the if-else if..else ladder. It looks like this:

if(condition)

statement;

else if(condition)

statement;

else if(condition)

statement;

.

.

.

else

statement;

5

switch statement

switch statement allows a variable to be tested for equality against a list of values.

switch(expression) {

   case value :

      // Statements

      break; // optional

   

   case value :

      // Statements

      break; // optional

   

   // You can have any number of case statements.

   default : // Optional

      // Statements

}


Java - Loop Control

Java programming language provides the following types of loop to handle looping requirements. 

Sr.No.

Loop & Description

1

while loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

The syntax of a while loop is −

while(condition) {

   // Statements

}

2

for loop

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

for(initialization; condition; update) {

   // Statements

}

3

do...while loop

Like a while statement, except that it tests the condition at the end of the loop body.

do {

   // Statements

}while(condition);



Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.  Java supports the following control statements. 

Sr.No.

Control Statement & Description

1

break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

The syntax of a break is a single statement inside any loop −

break;

2

continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

The syntax of a continue is a single statement inside any loop −

continue;



Java Language Basics Java Language Basics Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 13, 2022 Rating: 5

No comments:

Powered by Blogger.