Saturday, 13 May 2017

Typecasting ~ GNIITHELP

Type Casting

Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
  • Widening Casting(Implicit)
  • widening-type-conversion
  • Narrowing Casting(Explicitly done)
  • narrowing-type-conversion

Widening or Automatic type converion

Automatic Type casting take place when,
  • the two types are compatible
  • the target type is larger than the source type
Example :
public class Test
{
    public static void main(String[] args)
    {
      int i = 100; 
      long l = i; //no explicit type casting required  
      float f = l; //no explicit type casting required  
      System.out.println("Int value "+i);
      System.out.println("Long value "+l);
      System.out.println("Float value "+f);
    }
    
}
Output :
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit type conversion

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.
Example :
public class Test
{
    public static void main(String[] args)
    {
      double d = 100.04;  
      long l = (long)d;  //explicit type casting required  
      int i = (int)l; //explicit type casting required  
      
      System.out.println("Double value "+d);
      System.out.println("Long value "+l);
      System.out.println("Int value "+i);
     
    }
    
}
Output :
Double value 100.04
Long value 100
Int value 100
Read More »

Data type and Identifier ~ GNIITHELP

Data Types in Java

Java language has a rich implementation of data types. Data types specify size and the type of values that can be stored in an identifier.
In java, data types are classified into two catagories :
  1. Primitive Data type
  2. Non-Primitive Data type

1) Primitive Data type

A primitive data type can be of eight types :
Primitive Data types
charbooleanbyteshortintlongfloatdouble
Once a primitive data type has been declared its type can never change, although in most cases its value can change. These eight primitive type can be put into four groups

Integer

This group includes byteshortintlong
byte : It is 8 bit integer data type. Value range from -128 to 127. Default value zero. example: byte b=10;
short : It is 16 bit integer data type. Value range from -32768 to 32767. Default value zero. example: short s=11;
int : It is 32 bit integer data type. Value range from -2147483648 to 2147483647. Default value zero. example: int i=10;
long : It is 64 bit integer data type. Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Default value zero. example: long l=100012;

Floating-Point Number

This group includes floatdouble
float : It is 32 bit float data type. Default value 0.0f. example: float ff=10.3f;
double : It is 64 bit float data type. Default value 0.0d. example: double db=11.123;

Characters

This group represent char, which represent symbols in a character set, like letters and numbers.
char : It is 16 bit unsigned unicode character. Range 0 to 65,535. example: char c='a';

Boolean

This group represent boolean, which is a special type for representing true/false values. They are defined constant of the language. example: boolean b=true;

2) Non-Primitive(Reference) Data type

A reference data type is used to refer to an object. A reference variable is declare to be of specific and that type can never be change. We will talk a lot more about reference data type later in Classes and Object lesson.

Identifiers in Java

All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier. Identifier must follow some rules. Here are the rules:
  • All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
  • After the first character, an identifier can have any combination of characters.
  • A Java keyword cannot be used as an identifier.
  • Identifiers in Java are case sensitive, foo and Foo are two different identifiers.
Read More »

My First Java Program ~ GNIITHELP

First Java Program

Let us look at a simple java program.
class Hello
{
  public static void main(String[] args) 
  {
     System.out.println ("Hello World program");
  }
}
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.
System.out.println : This is used to print anything on the console like printf in C language.

Steps to Compile and Run your first Java program

Step 1: Open a text editor and write the code as above.
Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java program assuming it is saved in C:\
Step 4: Type javac Hello.java and press Return to compile your code. This command will call the Java Compiler asking it to compile the specified file. If there are no errors in the code the command prompt will take you to the next line.
Step 5: Now type java Hello on command prompt to run your program.
Step 6: You will be able to see Hello world program printed on your command prompt.

Now let us see What happens at Runtime

After writing your Java program, when you will try to compile it. Compiler will perform some compilation operation on your program.
Once it is compiled successfully byte code(.class file) is generated by the compiler.
class-file at runtime in Java
After compiling when you will try to run the byte code(.class file), the following steps are performed at runtime:-
  1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
  2. Byte Code verifier checks the code fragments for illegal codes that can violate access right to the object.
  3. Interpreter reads the byte code stream and then executes the instructions, step by step.
Read More »

Introduction to JVM ~ GNIITHELP

What is JVM?

Java virtual Machine(JVM) is a virtual Machine that provides runtime environment to execute java byte code. The JVM doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated exception handling, Garbage-collected heap.

JVM Architecture

JVM architecture in Java
Class Loader : Class loader loads the Class for execution.
Method area : Stores pre-class structure as constant pool.
Heap : Heap is in which objects are allocated.
Stack : Local variables and partial results are store here. Each thread has a private JVM stack created when the thread is created.
Program register : Program register holds the address of JVM instruction currently being executed.
Native method stack : It contains all native used in application.
Executive Engine : Execution engine controls the execute of instructions contained in the methods of the classes.
Native Method Interface : Native method interface gives an interface between java code and native code during execution.
Native Method Libraries : Native Libraries consist of files required for the execution of native code.

Difference between JDK and JRE

JRE : The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.
What is JRE

JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
What is JDK
Read More »

Setting Classpath for Java ~ GNIITHELP

Java is freely available on Oracle's Website. Download the latest version of JDK (Java Development Kit) on your machine. Do check whether your machine is 32 bit or 64 bit and download that particular Java version. Install JDK on your machine. Once you have installed Java on your machine you would need to set environment variable to point to correct installation directory.
An Environment variable is a dynamic "object" on a computer that stores a value(like a key-value pair), which can be referenced by one or more software programs in Windows. Like for Java, we will set an environment variable with name "java" and its value will be the path of the /bin directory present in Java directory. So whenever a program will require Java environment, it will look for the java environment variable which will give it the path to the execution directory.

Setting up path for windows ( 2000/XP/vista/Window 7,8 )

Assuming that you have installed Java in C:\ Program files/ Java / JDK directory
Step 1: Right click on my computer and select properties.
setting classpath in java

Step 2: Go to the Advance System Settings tab.
setting classpath in java

Step 3: Click on Environment Variables button.
setting classpath in java

Step 4: Now alter the path variable so that it also contains the path to JDK installed directory.
setting classpath in java
For e.g:- Change C:\windows/ system 32. to C:\windows/system 32; C:\program files / Java/ JDK.

Setting up path for window 95/98/ME

Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the following:
Step 1: Edit the C:\autoexec.bat file and add the following line at the end.
SET PATH =% PATH% C:\ PROGRAM FILE/JAVA/JDK/bin 

Setting up path for Linux , Unix , Solaris, free BSD

Assuming that you have installed Java in C:\program files\ java\ JDK directory, do the following:
Step 1: Environment variable path should be set to point where java binaries have been installed. Refer to your shell if you have trouble doing this.
For Example: If you use bash as your shell, then you would add following line to the end
bash mc: export PATH=/ Path/to/java 
Read More »

Features of Java ~ GNIITHELP

The prime reason behind creation of Java was to bring portability and security feature into a computer language. Beside these two major features, there were many other features that played an important role in moulding out the final form of this outstanding language. Those features are :

1) Simple

Java is easy to learn and its syntax is quite simple, clean and easy to understand.The confusing and ambiguous concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C++.

2) Object Oriented

In java everything is Object which has some data and behaviour. Java can be easily extended as it is based on Object Model.

3) Robust

Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time error checking and runtime checking. But the main areas which Java improved were Memory Management and mishandled Exceptions by introducing automatic Garbage Collector and Exception Handling.

4) Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into platform specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on any machine, plus this bytecode format also provide security. Any machine with Java Runtime Environment can run Java Programs.
Java is platform Independent Language

5) Secure

When it comes to security, Java is always the first choice. With java secure features it enable us to develop virus free, temper free system. Java program always runs in Java runtime environment with almost null interaction with system OS, hence it is more secure.

6) Multi Threading

Java multithreading feature makes it possible to write program that can do many tasks simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to execute multiple threads at the same time, like While typing, grammatical errors are checked along.

7) Architectural Neutral

Compiler generates bytecodes, which have nothing to do with a particular computer architecture, hence a Java program is easy to intrepret on any machine.

8) Portable

Java Byte code can be carried to any platform. No implementation dependent features. Everything related to storage is predefined, example: size of primitive data types

9) High Performance

Java is an interpreted language, so it will never be as fast as a compiled language like C or C++. But, Java enables high performance with the use of just-in-time compiler.


New Features of JAVA 8

Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go through them quickly, we will explore them in details later.
  • Enhanced Productivity by providing Optional Classes feature, Lamda Expressions, Streams etc.
  • Ease of Use
  • Improved Polyglot programming. A Polyglot is a program or script, written in a form which is valid in multiple programming languages and it performs the same operations in multiple programming languages. So Java now supports such type of programming technique.
  • Improved Security and performance.
Read More »

Basics of Java ~ GNIITHELP

Overview of Java

Java is one of the world's most important and widely used computer languages, and it has held this distinction for many years. Unlike some other computer languages whose influence has weared with passage of time, while Java's has grown.
As of 2015, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers using and working on it.


Creation of Java

Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun Microsystems Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered trademark of another Tech company.

Evolution of Java

Java was initially launched as Java 1.0 but soon after its initial release, Java 1.1 was launched. Java 1.1 redefined event handling, new library elements were added.
In Java 1.2 Swing and Collection framework was added and suspend()resume() and stop() methods were deprecated from Thread class.
No major changes were made into Java 1.3 but the next release that was Java 1.4 contained several important changes. Keyword assert, chained exceptions and channel based I/O System was introduced.
Java 1.5 was called J2SE 5, it added following major new features :
  • Generics
  • Annotations
  • Autoboxing and autounboxing
  • Enumerations
  • For-each Loop
  • Varargs
  • Static Import
  • Formatted I/O
  • Concurrency utilities
Next major release was Java SE 7 which included many new changes, like :
  • Now String can be used to control Switch statement.
  • Multi Catch Exception
  • try-with-resource statement
  • Binary Integer Literals
  • Underscore in numeric literals, etc.
And the latest addition to the lot is, Java SE 8, it was released on March 18, 2014. Some of the major new features introduced in JAVA 8 are,
  • Lambda Expressions
  • New Collection Package java.util.stream to provide Stream API.
  • Enhanced Security
  • Nashorn Javascript Engine included
  • Parallel Array Sorting
  • The JDBC-ODBC Bridge has been removed etc.

Application of Java

Java is widely used in every corner of world and of human life. Java is not only used in softwares but is also widely used in designing hardware controlling software components. There are more than 930 million JRE downloads each year and 3 billion mobile phones run java.
Following are some other usage of Java :
  1. Developing Desktop Applications
  2. Web Applications like Linkedin.com, Snapdeal.com etc
  3. Mobile Operating System like Android
  4. Embedded Systems
  5. Robotics and games etc.

Download JDK

For running Java programs in your system you will have to download and install JDK kit from here (current version is jdk 1.8).
Read More »