Saturday, 2 March 2013

Operators in Java

In any language operators are the basic building blocks to carry out any operation Variables.

Operators in java fall into 7 different categories:

Java operators fall into seven different categories:
  • assignment
  • arithmetic
  • relational
  • logical
  • bitwise
  • compound assignment
  • conditional

Following are the operators belonging to categories mentioned above. 



 Do not worry about usage of some complex operators like Conditional operators we will cover all of the above in subsequent tutorials. Just keep in mind these types of operators. I will reference them frequently in further tutorials.

Java Basic Language Elements

In this post I am going to cover keywords, comments, variables and data types in Java.

Keywords in Java

     There are certain words which are reserved which helps the java compiler to figure out what it is suppose to do.Keywords cannot be used as names for class,variable or function.As mentioned previously Java is a case sensitive language and all keywords are in lower case.Specially if you have worked in C you write NULL but in java it is null. Following is the list of keywords in Java.


Comments in Java

     Comments in java are very similar to comments in C. For a single line comment we use 
//this is a single line comment where as in multi line comment we do the following
/*
This is multiline comment.
 This is part of Java Tuts.
*/
Comments are used for better understanding of Code.When compiler encounters these comments it just ignores them and goes ahead with compilation.

There are another type of comments. They are called JavaDocs comments.Syntax for that is as following
/**
@param someParameter
This is a JavaDoc comment
*/

Variable and Data Types

     Variables are used to hold data.All variables have a name, a type, and a scope.Name of variable is what programmers assign.Type can be a user defined data type or primitive data types.Scope is the portion of code in which the variable is visible.
Java has four main primitive data types built into the language. We can also create our own data types.

  • Integer - byte, short, int, and long.
  • Floating point - float and double.
  • Character - char.
  • Boolean -    variable with a value of true or false.

Rules for naming variable

  • Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
  • Must begin with a letter, dollar sign, or an underscore
  • Are case sensitive
  • Keywords cannot be used as identifiers
  • Within a given section of your program or scope, each user defined item must have a unique identifier
  • Can be of any length.

Example

Lets take a simple example
int number;  //Variable declaration
number = 10; //Variable assignment
int number defines variable with name "number" of type integer.Next statement assigns a value 10 to the variable number.

Access modifiers in Java

Before we proceed further in developing programs in java lets cover access modifiers in details.They are quite simple to understand.

There are four access modifiers in JAVA.They define who can access the corresponding variables or functions.
  • Public
  • Protected
  • No access modifier
  • Private
There are two levels of access modifiers.
  • Class level access modifier
  • Member level access modifier.

Class level Access modifier

There are two access modifiers at class level
  1. public - If class is defined as public then the class can be accessed from anywhere.
  2. No access modifier - If no access modifier is specified class can be accessed only in the same package.

Member level Access modifier

 When i say a member in Java, a member can be a member variable or a member function.All four access modifiers are applicable in this case.
  1. private - If a member is defined to be private it can only be accessed by a member in the same class and nowhere else.
  2. No access modifier -  If no access modifier is specified that member can be accessed by a member in the same class as well as member in classes within the same package but not by members of subclass or members outside current package.
  3. Protected - If a member is defined as protected it can be accessed by a member in same class, in same package and in all of it's subclasses but not by members in other packages.
  4. public - A public member can be accessed by any member from anywhere.

Table representation for quick review

 

Hello World in Java

So lets start writing our first java program.Before writing any program one must define what goal the program or in broader sense the project must achieve. This helps us to program better. Generally programmers design UML(Unified modeling language) diagrams like Class Diagram, Sequence diagram etc. before proceeding with coding.We will come to UML diagrams after a few tutorials but lets just write and understand our first program.

In your eclipse dashboard click on go to Workspace.Generally what will load is a default workspace but if you want to have same different workspace you can do File->Switch workspace->other. Lets make a new project now.Go to File->New->JavaProject . Enter a project name and click finish. Don't worry about other parameters for now eclipse will automatically detect installed JDK and JRE.However if it dosen't you may need to manually browse and show it's location.Let the project name be greetings.It is a good programming practice to start your project name with a capital letter.You can now see your project in package explorer tab to the left.If you cannot see go to Windows->ShowView->packageExplorer. It is again a good programming practice to put your code in the new packages you create. Don't use default package.Also it is a convention and good programming practice to start your package name in small letters.So lets create package in our project.3rd  click your project in package explorer and select new->Package. Name it greetingspackage and click finish.You can then see the package in ProjectName/src directory i.e Greeting/src directory.Now go ahead 3rd click on package and select new->Class. Name it Welcome and click finish. Again it is a convention to name starting letter of class name as capital.Now lets start writing code.

Code

package greetingsPackage;
public class Welcome
{
    public static void main(String[] args)
   {
        System.out.println("Hello World!");
   }
}


Understanding the code

First like is package "greetingsPackage;" represents what package this particular file is.Generally this is followed by import lines. Since we are not using any library we need not use any import in this program.
Next line is "public class Welcome " This defines the class name.Remember this name is same as the filename incase you are not using an IDE. Next line is "public static void main(String[] args)". Check out this function very carefully.When we run any java program compiler finds this function and starts execution from here. Remember there is only one main() function in entire project.Now lets analyze this function by breaking it into individual words.
     First word is public. This is an access modifier .There are other access modifiers like private,protected etc but for now understand this that access modifier describe access privileges. Access modifiers will be covered in later tutorials.Next word is static.  Leave this for a moment.Next void is the return type which means function will not return any value. Next main  is the function name followed by parameters ib brackets. String args[] are special parameters taken from command line.args  is just a name and can be replaced by any suitable name.

Final statement is  "System.out.println("Hello World!");" It simply prints "Hello World!" on the standard output. You can view standard output in console at the bottom. If you can't see it again go to Windows->showView->Console.

Snapshot



 If you are compiling and running using command line.Do the following
javac Welcome.java
java Welcome

Output should be printed on command line itself.
If you get error saying "Command not recognized" you have not added JAVA classpath in your environment variables. Or if you don't want to do this run your java program giving absolute path like

c:\Program Files\Java\jdk1.6.0_01\bin\javac Welcome.java
c:\Program Files\Java\jdk1.6.0_01\bin\java Welcome

You can also notice a Welcome.class file generated.It is nothing but the bytecode discussed earlier.

Note: Very important! Java is a case sensitive language so you need to take care to what case you use like for ex if you use string instead of String compiler will throw an error.

Related Links


Getting started with JAVA

Setting up Java

In this post we will see how to set up Java Development Kit(JDK) and get started with JAVA programming.

What is JDK after all?

     JDK is java development kit.Sounds fancy? Basically JDK is nothing but set of libraries which can be used at compile and runtime when you start coding in java.Think of it as an environment needed to compile, debug and run you java programs.

    To describe it in one statement - The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.

     Before we proceed to downloading JDK it is important to know its types and purpose. We have JSE(java Standard Edition)  and JEE(Java Enterprise Edition).As long as you don't use any application servers or other advanced distributed architectures you will be perfectly fine with former one.
You can get Java JDK here. You can also check the difference between JSE and JEE in the previously mentioned link.After you download the JDK just unzip it and install.You may need to change enviroment variables if you are compiling and running programs from command line.

Where do i actually write my code?

You can write your code in any standard text editor notepad/notepad++ for Windows or vi/emacs for Linux.
For beginners its is recommended to write and compile on command line to get familiar with how things work but all you want is to write Java programs you can directly use IDE(Integrated Development Environment).There are two IDE's that are commonly used-
  1. Eclipse
  2. NetBeans
What i would recommend and use during these tutorials is Eclipse because it is most widely used and considerably light wight than NetBeans.Also there is no installation needed for Eclipse.You can download Eclipse from here. Go for Eclipse Classic than EE version if you are working with JSE.After downloading unzip it and execute eclipse.exe.You should see something like this
 


If it does not work you need to check your SDK installation.For windows check C:\Program Files\Java
directory if JRE and JDK folders are created.In next post we will see how to write our first Program.


How Java actually works?

As stated in earlier post that java in a compiled as well as interpreted language.So now lets look how this works.

To understand this well lets take an example.Lets say you created a file called Foo.java which has the class Foo in it.When you compile the file using  javac Foo.java what if formed is another file called Foo.class. Do not worry about the syntax mentioned above at this point.This post is meant only to make you understand how Java works internally. Compilation and execution of Java programs will be dealt in upcoming posts.
     So this Foo.class file created on compilation of Foo.java is nothing but what we call java bytecode.This bytecode can then be interpreted by Java interpreter present in the JVM.These class files are generally packaged and distributed as jar(Java ARchive) files.
     

Why do we need this "bytecode"?

     The answer is very simple - platform independence.Lets say you have written a code in C, compiled it on one particular architecture say x86.The program may run fine on this architecture but for other architectures the program may fail.
     In case of java this intermediate code called bytecode  is the result of compilation of java code.This bytecode can then be run on any machine with any architecture. All it needs is a JVM to interpret the bytecode.The Java byte code cannot be directly executed on hardware the way that compiled C code can. Instead the byte code must be interpreted by the JVM (Java Virtual Machine) at runtime in order to be executed.

     Java seeks to find a compromise between a purely compiled language (with no portability) and a purely interpreted language (that is significantly slower). By operating this way, Java gets some of the benefits of compiled languages, while also getting some of the benefits of interpreted languages. However, it also inherits some limitations from both of these languages.


Diagrammatic Representation-


Complete process in a nutshell 

 







Difference between Compiler, Interpreter and Assembler

Lets get some of our concepts clear before to head on to programming in java.This and perhaps next few posts will help you clear some computer programming concepts.

Both compiler and interpreter convert human readable high level language like Java,C++ etc into machine language but there is difference in the way both function.So lets take a look to understand  the differences.

Difference between Compiler and Interpreter

  • Compiler scans the entire program once and then converts it into machine language which can then be executed by computer's processor.In short compiler translates the entire program in one go and then executes it. Interpreter on the other hand first converts high level language into an intermediate code and then executes it line by line. This intermediate code is executed by another program.
  • The execution of program is faster in compiler than interpreter as in interpreter code is executed line by line.
  • Compiler generates error report after translation of entire code whereas in case of interpreter once an error is encountered it is notified and no further code is scanned.
  • Example Python is an interpreted language whereas C,C++ are compiled languages.Java however uses both compiler and interpreter.We will look into how this exactly works in case of java in next post.
  • Diagrammatic representation-



What is Assembler?

     Assembler is used for converting the code of low level language (assembly language) into machine level language.If you have worked on microprocessors like 8085 and 8086 the module which converts assembly language into machine language is nothing but Assembler.

Java - Compiled or interpreted?


As our basics are now clear lets get on to Java.  Well you must have heard that Java is both compiled and interpreted language. When it comes to the question  - How Java works? It goes something like below - 

  • When you run javac HelloWorld.java java compiler is invoked which converts human readable code(Contents of .java file) to java byte codes(intermediate form). This bytecodes are stored in a special file(called Class file) with .class extension.
  • Finally when you run java HelloWorld java interpreter is invoked which reads these bytecodes line by line, convert it into machine language and execute it.
This is why Java is called as both compiled as well as interpreted language. But this is not all. There is another concept called - Just-in-time compilation

JIT(Just-in-time compilation)

You can read the wiki page for complete details but here I am only going to provide relevant points from Java perspective.

  • JIT as the name suggests does just in time or on the fly compilation of java byte codes to native machine language that can be directly executed by the processor.
  • JIT compiler runs only after the program(JVM) has started. so it has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.
But question may arise - Addition time is spent every time to compile the code?

Yes it is true if we use pure JIT then additional time is spent compiling every time code is run and hence a new technique was introduced - HotSpot Compiling. In this

  • JVM maintains a count of number of time a module/routine is executed. When program/JVM first starts it goes through normal compilation to bytecodes followed by interpretation.
  •  But if the count of execution exceeds a limit the corresponding byte codes are compiled to machine code by JIT and are directly executed thereafter. 
  • The advantage is that there is no initial delay due to the compiling.



Above picture best represents the overview.

  • Java compiler (javac) converts Java code to byte code and then Java interpreter (java) interprets bytecodes line by line, converts it into native code and executes it.
  • However if a "hot spot" is encountered - typically a piece of code or method that is getting executed very frequently then JIT compiler comes up. Compiles the byte code to native code with optimizations (as JIT has runtime information) and thereafter that piece of code is never interpreted - the native code generated by JIT is directly executed.
  • Yes this will have an additional overhead in terms of time and memory footprint as JIT performs optimizations and compilation into native code on the fly (as your application is running) but subsequent calls to that part of code are efficient and fast.

Related Links

Java Introduction

Before we proceed to learn JAVA in greater depth lets take a look at some very basic questions like what is java and what are it's features that has made it so popular.

What is java?

     Java is a programming language and computing platform first released by Sun Microsystems in 1995.Just for the record Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.

 Why do I need Java?

     There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere! Java is free to download. You can download it from here.

What will I get when I download Java software?

      The Java Runtime Environment (JRE) is what you get when you download Java software. The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform libraries. The JRE is the runtime portion of Java software, which is all you need to run it in your Web browser.This is just to get things going but we will come to actually setting up java in later part of these tutorials.

Why Java over other programming languages?

     There are various reasons why one would prefer Java over other programming languages but it is my opinion that choosing a programming language should depend on what are you developing using this language and what are the features(Frameworks or Libraries to be more specific) specific to your project that the programming language supports.
     Lets now see why we have chosen Java as a programming language.
  • Object oriented - Java is an Object oriented programming(OOP) language which gives it an edge over other languages like C. OOP has many important features like Inheritance, Polymorphism, Data Encapsulation etc. We will look into these as we proceed but lets just keep these in mind.
  • Simple grammar -  java has a very simple grammar familiar to programmers having some exposure to C or C++.
  • Platform Independence - Java is compiled into bytecode which can be run on any machine. This makes java programs hardware independent. Also it is independent of any OS(Operating System) you use. All you need is a JVM (Java virtual machine) - this is installed when you install JRE mentioned above. JVM sits over your OS and runs all java programs.
  • Speed - The latest JIT compilers for Suns JVM approach the speed of C/C++ code, and in some memory allocation intensive circumstances, exceed it. (Too bad Ruby, Python, Perl, and Squeak don't even come close).
  • Safe - Java has always given preference to safety. After all it was developed for web. Java from it's earliest version provide support to catch exceptions and handle errors.
  • Garbage collection - If you have previously worked with C++ you may know that you explicitly need to define destructors to release memory taken by the objects on the heap.In Java this process is automated and there is no concept of destructors. JVM automatically invoked garbage collector to do this.This itself is a topic and will be dealt later in detail.
  • and many more...... You will get to know other benefits of using Java as we proceed in these tutorials.



t> UA-39527780-1 back to top