Introduction to Java:
Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++.
Java is created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Java is defined by a specification and consists of a programming language, a compiler, core libraries and a runtime machine(Java virtual machine).
The Java runtime allows software developers to write program code in other languages than the Java programming language which still runs on the Java virtual machine.
The Java platform is usually associated with the Java virtual machine and the Java core libraries.
Java virtual machine
The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.
Java Runtime Environment vs. Java Development Kit
A Java distribution typically comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).
The JRE consists of the JVM and the Java class libraries. Those contain the necessary functionality to start Java programs.
The JDK additionally contains the development tools necessary to create Java programs. The JDK therefore consists of a Java compiler, the Java virtual machine and the Java class libraries.
Uses of JAVA
Java is also used as the programming language for many different software programs, games, and add-ons.
Some examples of the more widely used programs written in Java or that use Java include the Android apps, Big Data Technologies, Adobe Creative suite, Eclipse, Lotus Notes, Minecraft, OpenOffice, Runescape, and Vuze.
Awesome Features:
1. Simple
Java is easy to learn and its syntax is quite simple and easy to understand.
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. 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.
4. Secured
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.
5. 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.
6. Architecture 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.
7. Portable
Java Bytecode can be carried to any platform. No implementation dependent features. Everything related to storage is predefined, example: size of primitive data types
8. 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.
9. Multithreaded
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.
10. Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
11. Interpreted
An interpreter is needed in order to run Java programs. The programs are compiled into Java Virtual Machine code called bytecode. The bytecode is machine independent and is able to run on any machine that has a Java interpreter. With Java, the program need only be compiled once, and the bytecode generated by the Java compiler can run on any platform.
Pros and Cons:
Pros :
1. Java is Simple
2. Java is object-oriented because programming in Java is centered on creating objects, manipulating objects, and making objects work together. This allows you to create modular programs and reusable code.
3. One of the most significant advantages of Java is Platform indenpendence.
4. Java is Secure: Java is one of the first programming languages to consider security as part of its design.
5. Java is Multithreaded: Multithreaded is the capability for a program to perform several tasks simultaneously within a program.
6. Java is Robust: Robust means reliable and no programming language can really assure reliability.
Cons:
1. Java can be perceived as significantly slower and more memory-consuming than natively compiled languages such as C or C++.
2. No local constants. In Java, variables that belong to a class can be made constant by declaring them to be final. Variables that are local to a method cannot be declared final, however.
3. Java is predominantly a single-paradigm language. However, with the addition of static imports in Java 5.0 the procedural paradigm is better accommodated than in earlier versions of Java.
Environments setup:
We need to install the Java Development Toolkit aka JDK, which is bundled with the Java Runtime Environment.
At this moment, the latest JDK versions is JDK 8.
All you have to do is head to the main download page provided by Oracle , and download the latest version that you will find.
Follow the instructions to download java and run the .exe to install Java on your machine.Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Assuming you have installed Java in
c:\Program Files\java\jdk
1. Right-click on 'My Computer' and select 'Properties'.
2. Click on the 'Environment variables' button under the 'Advanced' tab.
3. Now, alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to
'C:\WINDOWS\SYSTEM32',
then change your path to read
'C:\WINDOWS\SYSTEM32; c:\Program Files\java\jdk\bin'.
Setting up the path for Linux, Ubuntu, UNIX, Solaris
Environment variable PATH should be set to point to where the Java binaries have been installed.
Refer to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your
'.bashrc: export PATH=/path/to/java:$PATH'
Up until now we have installed a variety of tools towards setting up our Java Development environment.
Since the JDK is already installed (from step one) we could actually jump to coding just by using our text editor of choice (NotePad++, TextPad, NotePad, Ultra Edit etc)and invoking the javac and java commands from the command line.
Free IDE for Java
Netbeans: NetBeans IDE provides Java developers with all the tools needed to create professional desktop, mobile and enterprise applications.
Eclipse:Eclipse is another free Java IDE for developers and programmers and it is mostly written in Java.Eclipse lets you create various cross platform Java applications for use on mobile, web, desktop and enterprise domains.
First Java Program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as Simple.java
To compile:javac Simple.java
To execute:java Simple
It will give output as Hello Java
Lets see what this is :
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method.
The main method is executed by the JVM, it doesn't require to create object to invoke the main method. So it saves memory.
void is the return type of method, it means it doesn't return any value.
main is a entry point of the program. Execution of programs starts from main. It is called by Runtime System
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement.
Variables:
A 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.
The basic form of a variable declaration is shown here:
data_type 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
double pi = 3.14159;
// declares and assigns a value of PI.
char a = 'a';
// the char variable a iis initialized with value 'a'
Constant: During the execution of program, value of variable may change. A constant represents permanent data that never changes.
If you want use some value likes p=3.14159; no need to type every time instead you can simply define constant for p, following is the syntax for declaring constant.
Static final datatype ConstantName = value;
Example: static final float PI=3.14159;
Data types:
Every variable in Java has a data type. Data types specify the size and type of values that can be stored.
Data types in Java divided primarily in two tyeps:
Primitive(intrinsic) and Non-primitive.
Primitive types contains Integer, Floating points, Characters, Booleans And Non-primitive types contains Classes, Interface and Arrays.
Integer:This group includes byte, short, int and long, which are whole signed numbers.
Floating-point Numbers: This group includes float and double, which represent number with fraction precision.
Characters: This group includes char, which represents character set like letters and number
Boolean: This group includes Boolean, which is special type of representation of true or false value.
Some data types with their range and size:
byte: -128 to 127 (1 byte)
short: -32,768 to +32,767 (2 bytes)
int: -2,147,483,648 to +2,147,483,647 (4 bytes)
float: 3.4e-038 to 1.7e+0.38 (4 bytes)
double: 3.4e-038 to 1.7e+308 (8 bytes)
char : holds only a single character(2 bytes)
boolean : can take only true or false (1 bytes)
Variables Scope:
There are three kinds of variables in Java:
Local Variable:
1. A variable that is declared inside the method is called local variable.
2. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
3. Access modifiers cannot be used for local variables.
4. Local variables are visible only within the declared method, constructor or block.
5. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
Instance Variable
1. A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static.
2. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
3. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
4. Instance variables can be declared in class level before or after use.
5. Access modifiers can be given for instance variables.
6. Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
7. Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name . ObjectReference.VariableName.
Class/static variables:
1. A variable that is declared as static is called static variable. It cannot be local.
2. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
3. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
4. Static variables are stored in static memory.
5. Static variables are created when the program starts and destroyed when the program stops.
6. Visibility is similar to instance variables.
7. Static variables can be accessed by calling with the class name ClassName.VariableName.
Example
class A{
int data=50;
//instance variable
static int m=100;
//static variable
void method(){
int n=90;
//local variable
}
}//end of class A
Typecasting:
Casting is an operation that converts a value of one data type into a value of another data type.
The syntax for type casting is to give the target type in parenthesis followed by the variable name.
Example:
float f = (float) 10.1;
Int i = (int)f;
in this case, value of i is 10, the fractional part is discarded, while using type casting there is a chance of lost information that might lead to inaccurate result.
Example:
int i = 10000;
byte s = (short) i;
In this example value of s becomes 10, which is totally distorted, to ensure correctness; you can test if the value is in the correct target type range before using type casting.
Casts that results in no loss of information
byte =>short, char, int, long, float, double
short =>int, long, float, double
char =>int, long, float, double
int => long, float, double
long => float, double
float => double
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
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
arithmetic operators:
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Relational Operators:
There are following relational operators supported by Java language
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
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.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift & Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Logical Operators:
The following table lists the logical operators:
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Assignment Operators:
There are following assignment operators supported by Java language:
= Simple assignment operator
+= Add AND assignment operator
-= Subtract AND assignment operator
*= Multiply AND assignment operator
/= Divide AND assignment operator
%= Modulus AND assignment operator
<<= Left shift AND assignment operator.
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator.
^= bitwise exclusive OR and assignment operator.
|= bitwise inclusive OR and assignment operator.
Increment and Decrement Operators
Increment and decrement operators are used to add or subtract 1 from the current value of oprand.
++ increment
-- decrement
Increment and Decrement operators can be prefix or postfix.
In the prefix style the value of oprand is changed before the result of expression and in the postfix style the variable is modified after result.
For eg.
a = 9;
b = a++ + 5;
/* a=10 b=14 */
a = 9;
b = ++a + 5;
/* a=10 b=15 */
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator.
The operator is written as:
variable x = (expression) ? value if true : value if false
Instance of Operator:
This operator is used only for object reference variables.
instanceof operator is wriiten as:
( Object reference variable ) instanceof (class/interface type)
Expressions:
Expressions perform operations on data and move data around. Some expressions will be evaluated for their results, some for their side effects, some for both.
An assignment expression has the following form.
variable-expression assignment-operator expression
The variable expression can be just the name of a variable, or it can be an expression that selects a variable using array indices. The value type of the right-hand-side expression must be compatible with the variable type.
An assignment expression is most often used for its side effect: it changes the value of the variable selected by the variable expression to the value of the expression on the right-hand side. The value of the assignment expression is the value that is assigned to the selected variable.
An expression can have three kinds of result:
1. a value, such as the result of: (4 * i)
2. a variable, such as the result of: i = 4
3. nothing (in the case of an invocation of a method declared as void)
In most common assignment expressions, the assignment operator is =. Then the assignment expression has the following form.
variable-expression = expression
The Java arithmetic and bitwise operators can be combined with = to form assignment operators.
For example, the += assignment operator indicates that the right-hand side should be added to the variable, and the *= assignment operator indicates that the right-hand side should be multiplied into the variable.
Operators precedence:
Certain operators have higher priorities than others. Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. for example, the dot operator has higher precedence than the any other operator.
Precedence 15
() Parentheses
[] Array subscript
· Member selection
Precedence 14
++ Unary post-increment
-- Unary post-decrement
Precedence 13
+ Unary plus
- Unary minus
++ Unary pre-increment
-- Unary pre-decrement
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
Precedence 12
* Multiplication
/ Division
% Modulus
Precedence 11
+ Addition
- Subtraction
Precedence 10
<< Bitwise left shift
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
Precedence 9
< Relational less than
> Relational greater than
<= Relational less than or equal
>= Relational greater than or equal
instanceof Type comparison (objects only)
Precedence 8
== Relational is equal to
!= Relational is not equal to
Precedence 7
& Bitwise AND
Precedence 6
^ Bitwise exclusive OR
Precedence 5
| Bitwise inclusive OR
Precedence 4
&& Logical AND
Precedence 3
|| Logical OR
Precedence 2
? : Ternary conditional
Precedence 1
= Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
If Expressions:
if statement
An if statement contains a Boolean expression and block of statements enclosed within braces.
if(conditional expression)
//statement or compound statement;
else
//optional
//statement or compound statement;
//optional
If the Boolean expression is true then statement block is executed otherwise (if false) program directly goes to next statement without executing Statement block.
if....else
If statement block with else statement is known as as if...else statement. Else portion is non-compulsory.
if ( condition_one )
{
//statements
}
else if ( condition_two )
{
//statements
}
else
{
//statements
}
If the condition is true, then compiler will execute the if block of statements, if false then else block of statements will be executed.
nested if...else
when a series of decisions are involved, we may have to use more than one if...else statement in nested form as follows:
if(test condition1)
{
if(test condition2)
{
//statement1;
}
else
{
//statement2;
}
}
else
{
//statement3;
}
//statement x;
No comments:
Post a Comment