• Streams & Subjects

    Streams & Subjects

    Get detailed description of each and every topic with proper examples including text, images and videos.

  • Latest Technologies

    Latest Technologies

    Know more about the latest and new emerging technologies and boost your knowledge.

  • Programming

    Programming

    Don't learn just codes and syntax, instead learn the best and efficient way of coding.

  • Technologies

    New Technologies

    Get instant and relevant updates of the latest emerging technologies of lots of streams including web, clouds, virtualization, etc.

  • Freewares

    Freewares

    Download free trials and freewares of various fields and check out their efficiency before buying.

  • Multimedia

    Multimedia

    Learn techniques to design amazing and creative multimedia designs and characters including 2D & 3D layout with rendering.

Showing posts with label Java Technology. Show all posts
Showing posts with label Java Technology. Show all posts

Type conversion

Type Conversion is one which converts the one data type into another for example converting a int into float, converting a float into double, etc. In Type Conversion one data type is automatically gets converted into another but remember we can’t store a large data type into smaller data type. E.g. we can’t store a float into int because a float is greater than int. Type Conversion is also called as Promotion of data type because we are converting one lower data type into higher data type. So this is performed automatically by java compilers.

A promotion from on base type to another may occur in an arithmetic expression:
        double x = 3.14 + 10; /* 10 is promoted to a double */ 
        double y = 12; /* 12 is promoted to a double then assigned */ 

If an double is used where an int is expected, Java will generate an error:
        int z = 2.4; Compile-time error: possible loss of precision


Read more

Operators - Precedence and Associativity

Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.


Precedence Order

When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.


Associativity

When two operators with the same precendence the expression is evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativty (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.


Precedence and associativity of Java operators

The table below shows all Java operators from highest to lowest precedence, along with their associativity. Most programmers do not memorize them all, and even those that do still use parentheses for clarity.


Operator
Description
Level
Associativity
[]
.
()
++
--
access array element
access object member
invoke a method
post-increment
post-decrement
1
left to right
++
--
+
-
!
~
pre-increment
pre-decrement
unary plus
unary minus
logical NOT
bitwise NOT
2
right to left
()
new
cast
object creation
3
right to left
*
/
%
multiplicative
4
left to right
+ -
+
additive
string concatenation
5
left to right
<< >>
>>>
shift
6
left to right
<  <=
>  >=
instanceof
relational
type comparison
7
left to right
==
!=
equality
8
left to right
&
bitwise AND
9
left to right
^
bitwise XOR
10
left to right
|
bitwise OR
11
left to right
&&
conditional AND
12
left to right
||
conditional OR
13
left to right
?:
conditional
14
right to left
  =   +=   -=
 *=   /=   %=
 &=   ^=   |=
<<=  >>= >>>=
assignment
15
right to left

Caveats

There is no explicit operator precedence table in the Java Language Specification and different tables on the Web and in textbooks disagree in some minor ways.


Order of evaluation

In Java, the left operand is always evaluated before the right operand. Also applies to function arguments. Short circuiting. When using the conditional AND and OR operators (&& and ||), Java does not evaluate the second operand unless it is necessary to resolve the result. Allows statements like if (s != null && s.length() < 10) to work reliably. Programmers rarely use the non short-circuiting versions (& and |) with boolean expressions.


Precedence order gone awry

Sometimes the precedence order defined in a language do not conform with mathematical norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of -(a^b). So -1^2 is equal to 1 instead of -1, which is the values most mathematicians would expect. Microsoft acknowledges this quirkas a "design choice". One wonders whether the programmer was relying on the C precedence order in which unary operators have higher precedence than binary operators. This rule agrees with mathematical conventions for all C operators, but fails with the addition of the exponentiation operator. Once the order was established in Microsoft Excel 2.0, it could not easily be changed without breaking backward compatability.


Read more

Datatypes in Java

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in 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:
  1. Primitive Data Types
  2. Reference/Object Data Types

Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.


byte:

  • Byte data type is a 8-bit signed two's complement integer.
  • Minimum value is -128 (-2^7)
  • Maximum value is 127 (inclusive)(2^7 -1)
  • Default value is 0
  • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
  • Example : byte a = 100 , byte b = -50

short:

  • Short data type is a 16-bit signed two's complement integer.
  • Minimum value is -32,768 (-2^15)
  • Maximum value is 32,767(inclusive) (2^15 -1)
  • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
  • Default value is 0.
  • Example : short s= 10000 , short r = -20000

int:

  • Int data type is a 32-bit signed two's complement integer.
  • Minimum value is - 2,147,483,648.(-2^31)
  • Maximum value is 2,147,483,647(inclusive).(2^31 -1)
  • Int is generally used as the default data type for integral values unless there is a concern about memory.
  • The default value is 0.
  • Example : int a = 100000, int b = -200000

long:

  • Long data type is a 64-bit signed two's complement integer.
  • Minimum value is -9,223,372,036,854,775,808.(-2^63)
  • Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
  • This type is used when a wider range than int is needed.
  • Default value is 0L.
  • Example : int a = 100000L, int b = -200000L

float:

  • Float data type is a single-precision 32-bit IEEE 754 floating point.
  • Float is mainly used to save memory in large arrays of floating point numbers.
  • Default value is 0.0f.
  • Float data type is never used for precise values such as currency.
  • Example : float f1 = 234.5f

double:

  • double data type is a double-precision 64-bit IEEE 754 floating point.
  • This data type is generally used as the default data type for decimal values. generally the default choice.
  • Double data type should never be used for precise values such as currency.
  • Default value is 0.0d.
  • Example : double d1 = 123.4

boolean:

  • boolean data type represents one bit of information.
  • There are only two possible values : true and false.
  • This data type is used for simple flags that track true/false conditions.
  • Default value is false.
  • Example : boolean one = true

char:

  • char data type is a single 16-bit Unicode character.
  • Minimum value is '\u0000' (or 0).
  • Maximum value is '\uffff' (or 65,535 inclusive).
  • Char data type is used to store any character.
  • Example . char letterA ='A'

Reference Data Types:

  • Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.
  • Class objects, and various type of array variables come under reference data type.
  • Default value of any reference variable is null.
  • A reference variable can be used to refer to any object of the declared type or any compatible type.
  • Example : Animal animal = new Animal("giraffe");

Java Literals:

A literal is a source code representation of a fixed value. They are represented directly in the code without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10),hexadecimal(base 16) or octal(base 8) number systems as well.
Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these number systems for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well. They are:

NotationCharacter represented
\nNewline (0x0a)
\rCarriage return (0x0d)
\fFormfeed (0x0c)
\bBackspace (0x08)
\sSpace (0x20)
\ttab
\" Double quote
\'Single quote
\\backslash
\dddOctal character (ddd)
\uxxxxHexadecimal UNICODE character (xxxx)


Read more

Applets

A Java applet is like fully functional Java application because it has the entire Java API at its disposal. The creation of applets follows the same three step process of write, compile and run. The difference is, instead of running on your desktop, they run as part of a web page. There are some important differences between an applet and a standalone Java application, including the following:
  1. An applet is a Java class that extends the java.applet.Applet class.
  2. A main() method is not invoked on an applet, and an applet class will not define main().
  3. Applets are designed to be embedded within an HTML page.
  4. When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
  5. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
  6. The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.
  7. Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.
  8. Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.


Read more

Comparision between C++ & Java


  1. C++ supports pointers whereas Java does not pointers, instead java supports Restricted pointers.
  2. At compilation time Java Source code converts into byte code .The interpreter execute this byte code at run time and gives output. Java is interpreted for the most part and hence platform independent. C++ run and compile using compiler which converts source code into machine level languages, so c++ is platform dependent.
  3. Java is platform independent language but C++ is depends upon operating system, machine etc. C++ source can be platform independent (and can work on a lot more, especially embedeed, platforms), although the generated objects are generally platfrom dependent but there is clang for llvm which doesn't have this restriction.
  4. Java uses compiler and interpreter both and in c++ their is only compiler
  5. C++ supports operator overloading multiple inheritance but java does not.
  6. C++ is more nearer to hardware then Java
  7. Everything (except fundamental types) is an object in Java (Single root hierarchy as everything gets derived from java.lang.Object).
  8. Java does is a similar to C++ but not have all the complicated aspects of C++ (ex: Pointers, templates, unions, operator overloading, structures etc..) Java does not support conditional compile (#ifdef/#ifndef type).
  9. Thread support is built-in Java but not in C++.
  10. Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.
  11. Java does not support header file, include library files just like C++ . Java use import to include different Classes and methods.
  12. Java does not support default arguments like C++.
  13. There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.
  14. There is no goto statement in Java.
  15. Exception and Auto Garbage Collector handling in Java is different because there are no destructors into Java.
  16. Java has method overloading, but no operator overloading just like c++.
  17. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion.
  18. Java does not support unsigned integer while C++ does.


Read more

Versions of Java

Major release versions of Java, along with their release dates:

• JDK 1.0 (October 1, 1992)
• JDK 1.1 (February 19, 1997)
• J2SE 1.2 (December 8, 1998)
• J2SE 1.3 (May 8, 2000)
• J2SE 1.4 (February 6, 2002)
• J2SE 5.0 (September 30, 2004)
• Java SE 6 (December 11, 2006)
• Java SE 7 (July 28, 2011)


Read more

Java buzzwords / features

Following are the features or buzzwords of Java language which made it popular:
  1. Simple - Java omits many clumsy and confusing features of otherprogramming languages such as C++. Also, Java is designed to beable to run stand-alone on small machines. The size of the basicinterpreter and class support is 40 KB.
  2. Secure - Because Java supports the distributed environment of the Internet, it also offers multiple security features. Java provides data security through encapsulation. Also we can write applets in Java which provides security. An applet is a small program which can be downloaded from one computer to another automatically. There is no need to worry about applets accessing the system resources which may compromise security. Applets run within the JVM which protects from unauthorized or illegal access to system resources.
  3. Portable - There are no implementation-dependent aspects of the language specifications. For example, the sizes of primitive data types and the behavior of the arithmetic on them are specified. This contributes to make programs portable among different platforms such asWindows, Mac, and Unix. Also they can be executed on any kind of computer containing any CPU. When an application written in Java is compiled, it generates an intermediate code file called as “bytecode”. Bytecode helps Java to achieve portability.This bytecode can be taken to any computer and executed directly.
  4. Object-Oriented - Java supports the features and philosophy of object-oriented programming. So, it supports all the features of object oriented model like encapsulation, inheritance, polymorphism, abstraction, etc
  5. Robust - A program or an application is said to be robust(reliable) when it is able to give some response in any kind of context. Java provides support for error checking at various stages: early checking at compile time, and dynamic checking at runtime. More features of Java providing robustness include Type Checking and Exception Handling.
  6. Multithreaded - A thread is a light weight process. Java supports multithreading which is not supported by C and C++. Multithreading increases CPU efficiency. A program can be divided into several threads and each thread can be executed concurrently or in parallel with the other threads. Real world example for multithreading is computer. While we are listening to music, at the same time we can write in a word document or play a game.
  7. Architecture neutral - The Java compiler compiles the source code into bytecode, which does not depend upon any machine architecture, but can be easily translated into a specific machine by a JVM for that machine.
  8. Interpreted - The Java compiler compiles the source code into bytecode, which can be executed on any machine by the Java interpreter of an appropriate JVM.
  9. High Performance - The Just-In-Time (JIT) compilers improve the performance of interpreting the bytecode by caching the interpretations.
  10. Distributed - Java offers extensive support for the distributed environment of the internet. Java supports distributed computation using Remote Method Invocation (RMI) concept. The server and client(s) can communicate with another and the computations can be divided among several computers which makes the programs to execute rapidly.
  11. Dynamic - New code can be added to the libraries without affecting the applications that are using the libraries, runtime type information can be found easily, and so on.


Read more

Java as an Object Oriented Language

Object oriented programming provide a great flexibility, reusability, modularity and security to an application.. Java is a pure object oriented programming language. It is based on the concept of object. Java implements all the features of object oriented programming like
  1. Abstraction - Abstraction provides a way to hide the less essential properties so as to reduce complexity and increase efficiency.
  2. Encapsulation - Encapsulation is an information hiding and securing mechanism. It helps in restricting the access of data from the outside entities it means only the methods in a class can access its member variables. Encapsulation reduces the system complexity and increases robustness.
  3. Polymorphism - Polymorphism is a way to have more than one form of a method. In polymorphism, we use the method overloading and method overriding techniques.
  4. Inheritance - Inheritance is used to reduce the code and reuse the already available code. Here we extend a base class to a derived class. The derived class then inherits the properties of its base class.
  5. Class - Class is a very essential entity in java. Every program in java has a class. Class is like a blueprint of an object. A class contains member variables and methods.
  6. Objects - Object is soul of object oriented programming. An object is an instance of its class. Object is used to access the methods and variables in a class.
  7. Methods - Methods are the operations that an object can perform. Methods define the behavior of an object.
All of the above object oriented programming concepts are widely used when we write java codes. OOPS concepts are one of the reason for the power and success of java programming language.


Read more

Classpath

Classpath is a parameter, set either on the command-line, or through an environment variable, that tells the Java Virtual Machine or the Java compiler where to look for user-defined classes and packages.


Read more

A simple Java program, its compilation and execution

Program
     class Welcome { 
           // A java program will start from here. 
           public static void main(String args[]) { 
                    System.out.println(" Welcome to Java-Samples!!! "); 
           } 
       }
Compilation 
After we have written our program we need to compile and run the program. For that we need to use the compiler called javac which is provided by java. Go to the command prompt and type the file name as shown here. 
                                                       c:\>javac Welcome.java
The javac compiler will create a class file called Welcome.class that contains only bytecodes. These bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes into machine codes.

Execution 
Once we successfully compiled the program, we need to run the program in order to get the output. So this can be done by the java interpreter called java. In the command line type as shown here.
                                                         c:\>java Welcome 
So the output will be displayed as
                                                   Welcome to Java-Samples!!!


Read more

Principles of Java

There were five primary goals in the creation of the Java language:

• It should be "simple, object-oriented and familiar"
• It should be "robust and secure"
• It should be "architecture-neutral and portable"
• It should execute with "high performance"
• It should be "interpreted, threaded, and dynamic"


Read more

History of Java

Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) in 1991 and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is one of the most popular programming languages in use today, particularly for client-server web applications.

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. Java was originally designed for interactive television, but it was too advanced for the digital cable television industry at the time. The language was initially called Oak after an oak tree that stood outside Gosling's office; it went by the name Green later, and was later renamed Java, from Java coffee, said to be consumed in large quantities by the language's creators. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms. Fairly secure and featuring configurable security, it allowed network- and file-access restrictions. Major web browsers soon incorporated the ability to run Java applets within web pages, and Java quickly became popular. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998–1999), new versions had multiple configurations built for different types of platforms. For example, J2EE targeted enterprise applications and the greatly stripped-down version J2ME for mobile applications (Mobile Java). J2SE designated the Standard Edition. In 2006, for marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.

In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later the Ecma International to formalize Java, but it soon withdrew from the process. Java remains a de facto standard, controlled through the Java Community Process. At one time, Sun made most of its Java implementations available without charge, despite their proprietary software status. Sun generated revenue from Java through the selling of licenses for specialized products such as the Java Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and Runtime Environment (JRE) (a subset of the SDK); the primary distinction involves the JRE's lack of the compiler, utility programs, and header files.

On November 13, 2006, Sun released much of Java as free and open source software, (FOSS), under the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making all of Java's core code available under free software/open-source distribution terms, aside from a small portion of code to which Sun did not hold the copyright.

Sun's vice-president Rich Green said that Sun's ideal role with regards to Java was as an "evangelist." Following Oracle Corporation's acquisition of Sun Microsystems in 2009–2010, Oracle has described itself as the "steward of Java technology with a relentless commitment to fostering a community of participation and transparency". This did not hold Oracle, however, from filing a lawsuit against Google shortly after that for using Java inside the Android SDK (see Google section below). Java software runs on laptops to data centers, game consoles to scientific supercomputers. There are 930 million Java Runtime Environment downloads each year and 3 billion mobile phones run Java. On April 2, 2010, James Gosling resigned from Oracle.


Read more