Introduction to Java Programming Language
Introduction
Java is an imperative-based object-oriented programming language introduced by Sun Microsystems (which is now a subsidiary of Oracle) in 1995.
Its syntax is derived from C and C++ but it has a simpler object model and fewer low low-level facilities.
It was first created for developing software for embedded consumer electronic, such as toasters, microwave ovens, and interactive TV systems. But today, it is mostly used to develop software for networking, mobile devices, multimedia, games, web-based content and enterprise software.
Java applications are typically compiled to an intermediate representation called bytecode that can run (be interpreted) on any Java Virtual Machine (JVM) regardless of computer architecture.
In order to speed up the execution of java bytecode, Just-in-Time compilers are provided to translate the bytecode of a method into machine language when it is called for the first time during the execution of the program.
You need to install the Java Runtime Environment (JRE) on your computer in order to execute java applications. It consists of the Java Virtual Machine (JVM), the Java core classes, and the supporting Java class libraries also known as the Java APIs (Applications Program Interfaces).
You need a Java development environment or an integrated development environment(IDE) in order to create, compile, and execute Java applications.
The latest version of the Javadevelopment environ provided by Sun Microsystems is Java SE Development Kit 8 (JDK8) that can be downloaded from the web site java.sun.com/javase/downloads/.
IDEs provide tools that support the software development process, including editors, and debuggers. Popular IDEs include Eclipse ( and Netbeans (
Elements of Java Programming Language
Comments
Comments are the same as in C++.
Examples
/*-- Program to add two integer values --*/
// read the values
Identifiers
- Rules for writing valid identifiers:
- In Java, a letter denoted by L is defined as: ‘a’ to ‘z’, ‘A’ to ‘Z’, the underscore character ‘_’ or any Unicode character that denotes a letter in a language.
- A digit denoted by D is defined as ‘0’ to ‘9’ or any Unicode character that denotes a digit in a language.
- An identifier is defined as:(L | $)(L | D | $)*
- However, by convention, user-defined identifiers do not start with the dollar sign ‘$’ or the underscore ‘_’ and the dollar sign ‘$’ is never used for user-defined identifiers.
- C++ conventions for identifiers are also used in Java: use of the underscore character as a connector or start the second word with an uppercase letter. Examples: gross_pay, grossPay.
- An identifier cannot be a Java Keyword. Java keywords are provided in Appendix 1.
- Uppercase and lowercase letters are different.
Constant Data
There are six types of constant data in Java:
- Boolean constants
- character constants,
- integer constants,
- floating-point constants,
- strings constants, and
- Special constants
Boolean Constants
Boolean constants arethe same as in C++:true and false.
However, 0 is not false and anything else is nottrue as in C++.
Character Constants
A character constant is either a single printable Unicode character enclosed between single quotes, or an escape sequence enclosed between single quotes.
Examples ofprintable characters:'A', '$', '8', ‘ ’ (space bar), 'z'.
Examples ofescape sequences:'\n', '\t', '\'', '\\', ‘\”’.
Escape sequences are used to represent characters that you can not type from the keyboard or characters that have a meaning for the compiler such as single quote, double quote, . . ., etc.
Unicode characters that you cannot type from the keyboard may be specified using a Unicode escape sequence in the form: \uXXXX where XXXX represents the hexadecimal code of that character.
Examples‘\u00EA’ forêand ‘\u00A5’for ¥
Integer Constants
Integer constants are the same as in C++: positive or negative whole numbers.
An integer constant may be specified in one of the following bases:
- DecimalExample:26
- Octal (base 8)Example:032(the number 26 in octal)
- Hexadecimal (base 16)Example:0x1A(the number 26 in hexadecimal)
Floating-point constants
Floating-point constants are the same as in C++:
They may either be written indecimal notation or exponential notation.
They may be specified with the ‘f’ or ‘F’ suffix for the 32-bit value or the ‘d’ or ‘D’ suffix for the 64-bit value which is the default.
Examples123.41.234e+2D123.4f
String constants
A string constant is a sequence of zero or more Unicode characters (including escape sequences) enclosed between double quotes.
Examples
“\nJohn Doe”
“Enter a value:\t”
“T\u00EAte”(Tête)
Special Constants
There are two special constants:
- null can be used as the value for any reference type (but not primitive type) variable.
- A class literal (constant) is formed by taking a type name and appending “.class” to it. For example, String.class.
Variables, Basic Data Types, and Type Binding
Name of a variable:is an identifier.
Address of a variable:is not accessible in a program.
In Java, the number of bytes reserved for a memory location depends on the data type of the corresponding variable, and not on the machine on which you will be running the Java program.
Basic data types:Java basic data types with their range of values are provided in the following table:
Data Type / Type of Data / Range of Values / Sizeboolean / Boolean value / true, false
char / A single character / Unicode character representations: ‘\u0000’ – ‘\uffff’ / 2 byte
byte / integers / -27 (-128) to 27 – 1 (127) / 1 bytes
short / integers / -215 (-32,768) to 215 – 1 (32,767) / 2 bytes
int / integers / -231 (-2,147,483,648) to 231 – 1 (2,147,483,647) / 4 bytes
long / integers / -263 (-9,223,372,036,854,775,808) to 263 – 1 (9,223,372,036,854,775,807) / 8 bytes
float / Floating point decimals / Negative range: -3.4028235E+38 to -1.4E-45
Positive range: 1.4E-45 to 3.4028235E+38 / 4 bytes
double / Floating point decimals / Negative range: -1.7976931348623157E+308 to -4.9E-324
Positive range: 4.9E-324 to 1.7976931348623157E+308 / 8 bytes
The precisions of a floating point data types are provided as follows:
Data Types / Precisionfloat / 7 digits
double / 15 digits
Type Binding:(static type binding with explicit declarations of variables).
In Java, a variable must be declared before it can be used.
The declaration statement is the same as in C++.
Examples
intnum,// to hold the first value
number,// to hold the second value
sum;// to hold their sum
Note
There is a Java class named type-wrapper class for each of the basic data types above. This class has the same name as the basic data type, but starts with an uppercase letter: Byte, Short, Integer, Long, Float, and Double.
Arithmetic Expressions
The rules for writing and evaluating valid arithmetic expressions are the same as in C++. However, unlike in C++, the order of operands evalution in Java is left-to-right.
Java also allows mixed-mode expressions as in C++: the following table shows the Java arithmetic operators and how the data type of the result is obtained from those of the operands.
Operation / Operator / Example / Promotion RuleAddition / + / A + B /
- Operands with data type byte or short are converted to int.
- If either operand is of type double, then the other operand is converted to double.
- Otherwise, if either operand is of type float, then the other operand is converted to float.
- Otherwise, if either operand is of type long, then the other operand is converted to long.
- Otherwise, both operands are converted to int.
Subtraction / - / A – B
Multiplication / * / A * B
Division / / / A / B
Modulus (Remainder) / % / A % B
Negation / - / -A
Assignment Statement
Its syntax is the same as in C++:<variable-name>=<arithmetic-expression>;
Examples
char letter;
int num1, result;
double dnum;
letter = ‘A’;
num1 = 25;
dnum = 4.25;
result = num1 * 3;// the new value of variable result is 75
Assignment conversion Rules
Java allows you to make certain assignment conversions by assigning a value of one type to a variable in another type as follows:
byte→short→int→long→float→double
Example
byte bnum = 97;
int inum = 123;
long lnum;
double dnum;
lnum = bnum;
dnum = inum;
Conversions from one type to the right of an arrow above to another type to the left of the arrow are done by means of casts. However, there may be a loss of information in the conversion.
Example
double dnum = 9.997;
int inum = (int) dnum;// the value of inum is: 9
Compound Assignments and the Assignment Operator
Compound assignments are specified in the same way as in C++ as follows:
<variable-name<operator>= <expression>;
Which is equivalent to the regular assignment:
<variable-name>=<variable-name> <operator> <expression>;
Examples
Compound Assignments / Equivalent Simple Assignmentscounter += 5; / counter = counter + 5;
power *= value; / power = power * value;
total -= value; / total = total - value;
remain %= 8; / remain = remain % 8;
result /= num - 25 / result = result / (num - 25);
number *= -1; / number = -number;
In Java, the assignment is an operator with right-to-left associativity.
Example num1 = num2 = number = 5;//num1 = 5num2 = 5number = 5
Initial value of a Variable
The initial value of a variable with a basic data type can be specified when it is declared in the same way as in C++.
Examples
int num1 = 25,
num2,
sum = 0;
char letter , grade = 'A';
Naming Constants
In Java, you use the keyword final in the declaration of a variable to indicate that its initial value cannot be modified as follows:
final <data-type> <variable-name> = <arithmetic-expression>;
Example
final double PI = 3.14;
final int MAXVALUE = 150;
final variables correspond to const variables in C++. They are in general specified in upper case.
Increment and Decrement Operators
The increment and the decrement operatorsare the same as in C++.
Example
int inum1 = 12, inum2 = 50;
double dnum = 2.54;
inum1++;
inum2 = - -inum1 * 10 ;
++dnum;
Logical Expressions
A logical expression (or condition) are specified and evaluated in the same way as in C++.
A simple condition has the following syntax:
<arithmetic expression> <relational operator> <arithmetic expression>
Relational Operators
C/C++ Symbol / Meaningis less than
is greater than
= = / is equal to
<= / is less than or equal to
>= / is greater than or equal to
!= / is not equal to
A compound condition is built from simple conditions and logical operators.
Logical Operators
C++ Symbol / Meaning / EvaluationAND / <condition1> & <condition2> is true if and only if both conditions are true
|| / OR / <condition1> || <condition2> is true if and only if at least one of the two conditions is true
! / NOT / !<condition> is true if and only if <condition> is false
In C++, 0 is false and anything else is true. But this is not the case in Java. So, the C++ condition !num (which is equivalent to num = = 0) is not valid in Java.
Precedence of Java Operators
Operator / Order of Evaluation / Precedence!
Unary – / right to left / 7
*
/
% / left to right / 6
+
- / left to right / 5
<=
<= / left to right / 4
==
!= / left to right / 3
left to right / 2
|| / left to right / 1
Conditional Expressions
A conditional expression has the following syntax:
<Condition > ? <expression-True> : <expression-false>
With the meaning: if <Condition> is true, the value of the expression is the value of <expression-true> otherwise, it is the value of <expression-false>.
Example:average = (count = = 0) ? 0 : sum / count;
A conditional expression can be used in a program where any other expression can be used.
Variable Initialization and Expressions
In Java, a variable can be initialized when it is declared with an expression that only contains variables with assigned values.
Example:
int num1 = 7,
num2 = num1 + 3;
Class String
The Java programming language does not have a basic data type to store and manipulate character strings.
However, thestandard Java library contains a predefined class called String(from the package java.lang) that may be used to create and manipulate character strings.
A String object(as any other object in Java) is created by using the new operator and a class constructor.
For example: String name = new String(“John Doe”);
But you can declare a String object that references a string constant as follows:
String <variable-name>=<string-constant>;
Example
String greeting = “Hello world!”;
You can also use the assignment statement to store a character string into a String variable.
Example
String address;
address = “300 Pompton Road, Wayne, NJ 07470”;
Concatenation Operator
In Java, the + operator can be used to join (concatenate) two strings together or a string to any other value.
Examples
int num = 105;
String head = “Hello”;
String tail = “ world!”;
String greeting1 = head + tail;// the value of variable greeting1 is: Hello world!
String greeting2 = head + 2009;// the value of variable greeting2 is: Hello2009
String rating = “PG” + 13;//the value of the variable rating is: PG13
String message = “num =” + num;// the value of the variable message is: num = 105
You can also use the + operator in the compound assignment.
Examples
String greeting = “Hello”// the value of variable greeting is: Hello
greeting+ = “ world”;// the value of variable greeting is: Hello world!
Testing Strings for Equality
In Java, you do not use the = = operator to test for Strings equality as in C++.
You use instead the equals( ) or the equalsIgnoreCase( ) methods to do it as follows:
StringVar1.equals(StingVar2)returns true if strings StingVar1 and StringVar2 are identical.
StringVar1.equalsIgnoreCase(StingVar2)returns true if strings StingVar1 and StringVar2 are identical except for the uppercase/lowercase letter distinction.
Examples
String greeting = “Hello”;
String message = “Thanks”;
greeting.equals(“Hello”)returns true
greeting.equals(message)returns false
“Thanks”.equals(message)returns true
greeting.equals(“HELLO”)returns false
greeting.equalsIgnoreCase(“HELLO”)returns true
String Length
The length( ) method returns the number of character contained in a String object.
Example
String message = “Thank you”;
int n = message.length( );// the value of variable n is: 9
Converting Strings to their Numerical Values
Strings of digits can be converted into their numerical values by using the following methods:
Byte. parseByte( s ) / Converts string s to a byteShort.parseShort( s ) / Converts string s to a short
Integer.parseInt( s ) / Converts string s to an integer (int)
Long.parseLong( s ) / Converts string s to a long integer ( long )
Float.parseFloat( s ) / Converts string s to a single precision floating point (float)
Double.parseDouble( s ) / Converts string s to a double precision floating point (double)
Example
String argument1 = “123”,
argument2 = “123.45”;
int inum = Integer.parseInt( argument1 );// inum = 123
double dnum = Double.parseDouble( argument2 );// dnum = 123.45
Converting Numbers to Strings
Sometimes you may want to convert a number to a string because you need to operate on its value in string form.
You can convert a number to a string in one of the following ways:
- Use the String concatenation operator:
Example
int inum = 123;
double dnum = 12.5;
String st1 = “” + inum;
String st2 = “” + dnum;
- By using the String.valueOf( ) method:
Example
int inum = 123;
double dnum = 12.5;
String st1 = String.valueOf( inum );
String st2 = String.valueOf( dnum );
- By using the toString( )class methods (example: String st1 = Integer.toString( 123);).
Standard Input
Input statements are not provided in the Java language.
However, input from the standard inputdevice may be performed in a Java program by using objects of the class Scanner.
The standard input device (which by default is the keyboard) is represented in a Java program by the object System.in.
You use objects of the class Scanner to perform standard input as follows:
- Write the following import statement before any class of your program:
import java.util.Scanner;
- Declare an object of the class Scanner and initialize it with the object in.System as follows:
Scanner <Object-Name> = new Scanner( System.in );
Example:
Scanner input = new Scanner( System.in );
- Use the following instance methods to perform input:
Method / What it does / Example
next( ) / Input next word (sequence of characters) / String name = input.next( );
nextByte( ) / Input next byte / byte num = input.nextByte( );
nextDouble( ) / Input next double precision value / double dnum = input.nextDouble( );
nextFloat( ) / Input next single precision value / float fnum = input.nextFloat( );
nextInt( ) / Input next integer value / int inum = input.nextInt( );
nextLine( ) / Input next line of text / String line = input.nextLine( );
nextLong( ) / Input next long integer value / long lnum = input.nextLong( );
nextShort( ) / Input next short integer value / short snum = input.nextShort( );
Input values are separated (by default) with white spaces: spaces, tabs, carriage returns, . . ., etc.
Example
int age, hours;
double payRate;
String firstName;
firstName = input.next( );
age = input.nextInt( );
payRate = input.nextDouble( );
hours = input.nextInt( );
Input:John 24 12.50 35
Standard Output
Output statements are not provided in the Java language.
However, output to the standard output device (which is by default the monitor) can be performed by using themethods println and print on object System.out.
They have the following syntax:
System.out.println( <value> );
System.out.print( <value> );
println outputs value and then moves the cursor to the next line whereas print just outputs value.
Example
int num = 105;
String head = “Hello”;
String tail = “ world!”;
System.out.println( num - 5 );Output:100
System.out.println( “Hello World!” );Output:Hello World!
System.out.println( head + tail );Output:Helloworld!
System.out.println( head + 2009 );Output:Hello2009
System.out.println( “PG” + 13 );Output:PG13
System.out.println( “num - 3 =\t” + (num – 3));Output:num - 3 = 102
Formatted Output
Formatted output to the standard output device can be performed by using theprintfmethod on object System.out.
It has the following syntax:
System.out.printf( <format-string>, <Argument-list> );
format-string> consists of fixed text and format specifiers.
The fixed text in the format string is output just as it would be in a print or println method.
Each format specifierin the format-string>is the placeholder of the value of the corresponding argument in the <Argument-list>.
The following table lists some format specifiers with their corresponding data formats:
Format Specifier / Data Format / Example / Output%c / a single character in lowercase / System.out.printf( “%c”, ‘a’ ); / a
%C / a single character in uppercase / System.out.printf( “%C”, ‘a’ ); / A
%s / a string of characters in lowercase / System.out.printf( “%s”, “John” ); / john
%S / a string of characters in uppercase / System.out.printf( “%S”, “John” ); / JOHN
%d / Decimal integer in base 10 / System.out.printf( “%d”, 125 ); / 125
%o / Decimal integer in base 8 / System.out.printf( “%o”, 125 ); / 175
%x or %X / Decimal integer in base 16 / System.out.printf( “%X”, 125 ); / 7D
%f / Floating point in decimal format / System.out.printf( “%f”, 12.5 ); / 12.5
%e or %E / Floating point in exponential format / System.out.printf( “%E”, 12.5 ); / 1.25E+1
%g or %G / Floating point in either floating point format or exponential format based on the magnitude of the value / System.out.printf( “%G”, 12.5 ); / 12.5
Examples