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.
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.
- 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.
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.
Sun 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.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.
Popular Java Editors
To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following −
- Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
- Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
- Eclipse − A Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
First Java Program
Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } }
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: MyFirstJavaProgram.java.
- Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
- Type 'javac MyFirstJavaProgram.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 MyFirstJavaProgram ' to run your program.
- You will be able to see ' Hello World ' printed on the window.
Output
C:\> javac MyFirstJavaProgram.java C:\> java MyFirstJavaProgram Hello World
Basic Syntax
About Java programs, it is very important to keep in mind the following points.- Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
Java Identifiers
All Java components require names.
Names used for classes, variables, and methods are called identifiers.
In Java, there are several points to remember about identifiers.
They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
After the first character, identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Keywords
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
Data Types in Java: A data type refers the type of data to be held on a variable or object and its associated operations.
For example and integer can be divide but string cannot.
The data type indicates that which types of operation are permitted on operand.
Java offers following type of data types.
Primitive: These are in-built data types offered by the compiler.
Java supports eight primitive data types e.g. byte, short, int, long, float, double, char, Boolean etc. Reference: These are constructed by using primitive data types, as per user need. Reference data types store the memory address of an object. Class, Interface and Array are the example of Reference Data types.
Java offers the following primitive data type:
Type Size Description Range
byte 1 Byte Byte integer -128 to +127
short 2 Byte Short integer -32768 to +32767
int 4 Byte integer -2 31 to 2 31 -1
long 8 Byte Long integer -2 63 to 2 63 -1
float 4 Byte Single precision floating point (up to 6 digit) -3.4x10-38 to +3.4x10 38
double 8 Byte Double precision floating (up to 15 digit) -1.8x10-308 to +1.8x10 308
char 2 Byte Single character 0 to 65536
Boolean 1 Byte Logical Boolean values True or False
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.byte
- Byte data type is an 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 integer.
- 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 integer
- 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)
- Integer 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: long a = 100000L, long 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'
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 indicate 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 −
Example
"Hello World" "two\nlines" "\"This is in quotes\""
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. 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 −
Example
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'
Operators in Java: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
A Unary operator requires only single operands whereas
Binary operators require two operands.
Java offers the following types of Operators:-
Arithmetic Operators:
+ Unary plus Represents positive values. int a=+25;
- Unary minus Represents negative values. int a=-25;
+ Addition Adds two values int x= a+b;
- Subtraction Subtract second operands from first. int x=a-b;
* Multiplication Multiplies two values int x= a*b;
/ Division Divides first operand by second int x=a/b;
% Modulus Finds remainder after division. int x= a%b;
+ Concatenate Adds two strings (String Addition) “ab”+”cd” = ”abcd”
“25”+”12” = ”2512”
Relational Operators:
== equalto Tests whether two values are equal. a==b
!= notequalto Tests whether two values are unequal. a!=b
> greaterthan Returns true if the value of the left expression is
greater than right value.
a>b
< lessthan Returns true if the value of the left expression is less
than the right.
a<b
>= greaterthanorequalto Returns true if the value of the left expression is
greater or equal than right.
a>=b
<= lessthanorequalto Returns true if the value of the left expression is less
or equal than right.
a<b
Logical Operators :
&& And Returns true X and y both true x&&y
|| Or Returns true Either x or y is true x||y
! Not Returns true X is false !x
Increment/Decrement Operator :
Java supports ++ and -- operator which adds or subtract 1 from its operand.
i.e. a=a+1 equivalent to ++a or a++
a=a-1 equivalent to --a or a--
++ or -- operator may used in Pre or Post form.
++a or --a (increase/decrease before use) and
a++ or a– (increase/decrease after use)
Example:- Find value of P?
(initially n=8 and p=4)
p=p* --n; 28 p=p* n--; 32
Assignment Operators:
In Java = operator is known as Assignment operator, it assigns right hand value to left hand variables. Example- int x=5; or z= x+y;
Java offers some special shortened Assignment operators,
which are used to assign values on a variable.
These operators areOperator
How to Use Equivalent to +=
X+=Y
X=X+Y
-=
X-=Y
X=X-Y
*=
X*=Y
X=X*Y
/=
X/=Y
X=X/Y
%=
X%=Y
X=X%Y
Miscellaneous Operators
There are few other operators supported by Java Language.Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −variable x = (expression) ? value if true : value if falseFollowing is an example −
Example
public class Test { public static void main(String args[]) { int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } }Output
Value of b is : 30 Value of b is : 20
Java Keywords The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char Java 11 class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Comments in Java Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler. public class MyFirstJavaProgram{ /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ public static void main(String []args){ // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); } }
Escape Sequence Description \t Inserts a tab in the text at this point. \b Inserts a backspace in the text at this point. \n Inserts a newline in the text at this point. \r Inserts a carriage return in the text at this point. \f Inserts a form feed in the text at this point. \' Inserts a single quote character in the text at this point. \" Inserts a double quote character in the text at this point. \\ Inserts a backslash character in the text at this point. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. Example If you want to put quotes within quotes, you must use the escape sequence, \", on the interior quotes: public class Test { public static void main(String args[]) { System.out.println("She said \"Hello!\" to me."); } } This will produce the following result: She said "Hello!" to me.
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.
Example
int i = 5000; float gpa = 13.65; double mask = 0xaf;However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

Number Methods
Following is the list of the instance methods that all the subclasses of the Number class implements −Sr.No. | Method & Description |
---|---|
1 | xxxValue()
Converts the value of this Number object to the xxx data type and returns it. |
2 | compareTo()
Compares this Number object to the argument. |
3 | equals()
Determines whether this number object is equal to the argument. |
4 | valueOf()
Returns an Integer object holding the value of the specified primitive. |
5 | toString()
Returns a String object representing the value of a specified int or Integer. |
6 | parseInt() This method is used to get the primitive data type of a certain String. |
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write −String greeting = "Hello world!";
Concatenating Strings
The String class includes a method for concatenating two strings −string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −
"My name is ".concat("Zara"); Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!" which results in −
"Hello, world!"
String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } }This will produce the following result −
Output
Dot saw I was Tod
10 | boolean equals(Object anObject)
Compares this string to the specified object. |
11 |
29 String replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.Example
public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ public static void main(String []args) { // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); } }
No comments:
Post a Comment