UNIT-II Overview of Java Language
UNIT-II Overview of Java Language
UNIT-II
Overview of Java Language
1. Introduction,
2. Types of Comment ,
3. Java Tokens
4. Reserve Keywords
5. Identifiers
6. Literals
7. Operators,
8. Variables,
9. final variable,
10. Data Types,
11. Array ,
12. Type Casting ,
13. Control Statement - Branching statement - Looping statement
1. Introduction
A Java program is basically a collection of classes.
A class is defined by a set of declaration statements and methods
containing executable statements. Most statements contain expressions, which
describe the actions carried out on data.
2. Types of Comment
For example:
If you have three @see tags, put them one after the other.
/**
* This class draws a bar chart.
*@author Herbert Schildt
* @version 3.2
*/
3. Java Tokens
- Smallest individual units in a program are known as tokens.
- The compiler recognizes them for building up expressions and statements.
- A Java program is a collection of tokens, comments and white spaces.
Java language includes following types of tokens.
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Variable
7. Datatypes
4. Reserve Keywords
- Java has reserved words called keywords, which follow specific syntax rules.
- There are 50 keywords in Java.
- Keywords have fixed meanings and cannot be used as variable, class, or
method names.
- All keywords must be written in lowercase.
abstract continue for new switch
assert *** default goto * package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp ** volatile
const * float native super while
Note: we should also not attempt to use the Boolean values true and false or null as names
in our program.
5. Identifiers
- Identifiers are programmer-designed tokens.
- They are used for naming classes, methods, variables, objects, labels, packages and
interfaces in a program.
Example: average, sum, length etc.
Java identifiers follow these rules:
1. Can include letters, digits, _ (underscore), and $ (dollar sign).
2. Cannot start with a digit.
3. Case-sensitive (uppercase and lowercase are different).
4. Cannot use keywords as identifiers.
5. No spaces allowed in identifiers.
6. Can be of any length.
6. Literals
- Literals in Java are fixed values (digits, letters, or symbols) assigned to
variables.
- They represent boolean, character, numeric, or string data.
Java has five main types of literals:
Integer literals:
- By default, all integer literals are of int type.
- Integer literals can be written in different number systems:
1. Decimal (Base 10): Uses digits 0-9 (e.g., int x = 101;).
2. Octal (Base 8): Uses digits 0-7, prefixed with 0 (e.g., int x = 0146;).
3. Hexadecimal (Base 16): Uses digits 0-9 and letters a-f, prefixed with 0x or 0X
(e.g., int x = 0X123Face;).
4. Binary (Base 2): Uses digits 0 and 1, prefixed with 0b or 0B (e.g., int x =
0b1111;).
Floating point literals:
- By default, floating-point literals are of double type.
- Floating-point literals can only be written in decimal form (not in octal or
hexadecimal).
Character literals:
- A character literal is a single character or escape sequence enclosed in single
quotes (' '). It is always of char type. For Example: 'a', '%', '\u000d'
String literals:
- A string literal is a sequence of characters enclosed in double quotes (" ").
- It can include letters, numbers, special characters, spaces, etc.
- Example: "Jack", "12345", "\n"..
Boolean literals:
- Boolean literals represent values that are either true or false,
Example: true, false
7. Operators,
- Operators constitute the basic building block of any programming language.
- An operator is a symbol that tells the computer to perform certain mathematical
and logical manipulation.
- An operator is a symbol that takes one or more arguments are operates on them to
produce a result.
- Operators are used in program to manipulate data and variables.
Java operators can be classified into a number of related categories as below:.
Arithmetic operators
- Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
The following table lists the arithmetic operators:
- These operators act upon the individual bits of their operands. They are
listed in the following table:
Relational Operators
- Relational operators compare two operands to determine their relationship, such
as equality or order.
- The result is always a boolean value (true or false).
- These operators are commonly used in if statements and loops.
- The relational operators are:
Operators Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
A logical expression yields a value of true or false, according to the truth table show
below:
A B A || B A && B
Assignment Operator
- The assignment operator is the single equal sign, =.
- The assignment operator works in Java much as it does in any other
computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. For example,
the statement,
x=y=z=100;
sets the variables x, y, and z to 100 using a single statement.
8. Variables,
9. final variable:
- When a variable is declared as final, its value cannot be changed after initialization.
- This is useful for creating constants or values that should remain unchanged.
public class ConstantExample {
public static void main(String[] args) {
final double PI = 3.14159;
System.out.println("Value of PI: " + PI); }
}
Output:
Value of PI: 3.14159
• A primitive data type in Java is a basic data type that directly holds values, not
references to objects.
• These types are predefined by Java and stored in memory for fast access.
Numbers
Primitive number types are divided into two groups:
1. Integer
2. Floating point
Integer Types
- Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
1. Byte
- The byte data type can store whole numbers from -128 to 127.
- This can be used instead of int or other integer types to save memory.
- It occupied 1 byte, means 8 bits.
2. Short
- The short data type can store whole numbers from -32768 to 32767.
- It occupied 2 bytes, means 16 bits.
3. Int
- The int data type can store whole numbers from -2147483648 to 2147483647.
- It required 4 bytes means 32 bits.
4. Long
- The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807.
- Note that you should end the value with an "L":
- Occupied 8 bytes means 64 bits.
Floating Point Types
- There two types of floating point: 1. Float 2. Double
- Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double
- The float and double data types can store fractional numbers.
- Note that you should end the value with an "f" for floats and "d" for doubles.
- Float occupied 4 bytes and double occupied 8 bytes.
• A non-primitive data type in Java is a data type that stores references to objects
instead of actual values.
• These types are more complex than primitive data types and can hold multiple
values or behaviors.
11. Array :
- An array in Java is a collection of elements of the same data type
stored in contiguous memory locations.
- Arrays allow storing multiple values under a single variable name.
- Once created, its size cannot change.
- Elements are accessed using an index (start from 0).
- Arrays can store int, float, char, String, or user-defined objects.
int[] numbers = {10, 20, 30, 40, 50}; // Declares, allocates, and initializes
This method automatically determines the size based on the provided elements.
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[4]); // Output: 50
Example:
public class OneDArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (i + 1) * 10;
}
System.out.println("Array elements: ");
for (int num : numbers) {
System.out.print(num+” “);
}
}
}
Output:
Array elements: 10 20 30 40 50
Example
Class MDemo{
Static public void main(String args[]){
int[ ][ ] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for (int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
} } } }
class Animal { }
class Dog extends Animal { }
public class UpcastingExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting (Dog → Animal)
} }
Downcasting (Explicit): Converting a superclass object back to a subclass type.
class Animal { }
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
}
public class DowncastingExample {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
d.bark(); // Output: Barking...
}
}
13. Control Statement - Branching statement - Looping statement
class ElseDemo {
public static void main(String args[]) {
int a = 10, b = 30, c = 20;
System.out.println(“Largest Value is : “);
if ( a > b) {
if (a > c)
System.out.println(a);
else
System.out.println(c);
}else {
if (c > b)
System.out.println(c);
else
System.out.println(b);
}}}
Switch statements
For selecting one of many alternatives, if statements can be used, but they can make
the code complex.
Java provides the switch statement for multiway decisions.
It tests a variable/expression against multiple case values.
When a match is found, the corresponding block executes.
switch (expression){
case value-1:
block-1;
break;
case value-2:
block-2;
break;
<<<<<<..
<<<<<<..
default:
default-block;
break;
}
statement-X;
In a switch statement:
The expression is an integer or character.
value-1, value-2, etc., are unique constants known as case labels.
Each block contains statements to execute if the case matches.
The break statement ends a case and exits the switch, transferring control to the
next statement.
The default case is optional. It runs if no case matches.
Omitting break causes the execution to continue to the next case (fall-through
behavior).
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statement
}
do
In a while loop, the condition is tested before the loop runs.
If you need to execute the loop body before the condition is tested, use the do
statement.
Initialization
do{
Body of the loop;
}while (test-condition);
In a do-while loop:
The loop body is executed first, then the condition is checked.
If the condition is true, the body runs again.
This repeats as long as the condition remains true.
When the condition is false, the loop ends and control moves to the next statement.
Since the condition is checked after the loop, the body is always executed at least once.
For example, in the following program test condition is false in the first attempt, still loop is
executed only once.
class CalcTotal {
public static void main(String args[ ] ) {
int i=100, sum=0;
do {
sum = sum + i;
i++;
} while(i <= 10);
System.out.println("Addition of numbers 1..10 is : " + sum);
}}
The output of the program would be…..
Addition of numbers through 1...10 is : 100
for
The for loop is another entry controlled loop that provides a simple loop structure. The
general form of the for loop is:
for (initialization; test-condition; increment){
Body of the loop;
}
Example:
class CalcTotal {
public static void main(String args[ ] ) {
int i, sum=0;
sum = 0;
for(i = 1; i <= 10; i++)
sum = sum + i;
System.out.println(" Addition of no: 1 to 10 is : " + sum);
}
}
The output of the program would be…
Addition of no: 1to 10 is : 55