UNIT-I an Introduction to Java
UNIT-I an Introduction to Java
• Example
• This is how a simple basic structure of a Java
program looks like.
• Verification:
It ensures the correctness of the .class file i.e. it checks whether this
file is properly formatted and generated by a valid compiler or not.
If verification fails, we get run-time exception java.lang.VerifyError.
This activity is done by the component ByteCodeVerifier. Once this
activity is completed then the class file is ready for compilation.
• Preparation:
JVM allocates memory for class static variables and initializing the
memory to default values.
• Resolution:
It is the process of replacing symbolic references from the type with
direct references. It is done by searching into the method area to
locate the referenced entity.
Initialization:
3) Initialization: -
In this phase, all static variables are assigned
with their values defined in the code and
static block(if any).
This is executed from top to bottom in a class
and from parent to child in the class
hierarchy.
Java Comments
• Java Comments:-
• Comments can be used to explain Java code, and to make it more readable. It can also be
used to prevent execution when testing alternative code.
• 1) Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).
• Example:-
• // This is a comment
• System.out.println("Hello World");
• 2) Java Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Java.
• Example
• /* The code below will print the words Hello World to the screen,
• and it is amazing */
• System.out.println("Hello World");
• 3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API.
These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used
in the code.
The documentation comments are placed between /** and */.
Data types
• Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
• 1) Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
• 2) Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Variable
A variable is the name of a reserved area allocated in memory.
• In other words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
Types of Variables
• There are three types of variables in Java:
• 1) local variable
• 2) instance variable
• 3) static variable
Variable
• 1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
• 2) Instance Variable
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
• 3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances
of the class.
Memory allocation for static variables happens only once when the class is loaded
in the memory.
Keywords
Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code.
These are predefined words by Java so they cannot be used as a variable or
object name or class name.
Java Control Structures
Java compiler executes the code from top to bottom.
The statements in the code are executed according to the order in
which they appear. However, Java provides statements that can be
used to control the flow of Java code.
Such statements are called control flow statements.
Java provides three types of control flow statements.
• 1) Decision Making statements
- if statements
- switch statement
• 2) Loop statements
- do while loop
- while loop
- for loop
- for-each loop
• 3) Jump statements
- break statement
- continue statement
Java Control Structures
1) Decision Making statements
"if" statement is used to evaluate a condition.
The control of the program is diverted
depending upon the specific condition. The
condition of the If statement gives a Boolean
value, either true or false. In Java, there are
four types of if-statements given below.
• 1. Simple if statement
• 2. if-else statement
• 3. if-else-if ladder
• 4. Nested if-statement
• 1. Simple if statement:-
• It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of
code if the expression evaluates to true.
• Syntax of if statement is given below.
• if(condition) {
• statement 1; //executes when condition is true
• }
• Example:-
• public class Student {
• public static void main(String[] args) {
• int x = 10;
• int y = 12;
• if(x+y > 20) {
• System.out.println("x + y is greater than 20");
• }
• }
• }
• Output:
• x + y is greater than 20
•
• 2) if-else statement
• The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
• Syntax:
• if(condition) {
• statement 1; //executes when condition is true
• }
• else{
• statement 2; //executes when condition is false
• }
• Consider the following example.
• x + y is greater than 20
•
• 3) if-else-if ladder:
• The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we
can say that it is the chain of if-else statements that create a decision tree where the program may enter in
the block of code where the condition is true. We can also define an else statement at the end of the chain.
• Syntax of if-else-if statement is given below.
• if(condition 1) {
• statement 1; //executes when condition 1 is true
• }
• else if(condition 2) {
• statement 2; //executes when condition 2 is true
• }
• else {
• statement 2; //executes when all the conditions are false
• }
• Consider the following example.:-
• public class Student {
• public static void main(String[] args) {
• String city = "Delhi";
• if(city == "Meerut") {
• System.out.println("city is meerut");
• }else if (city == "Noida") {
• System.out.println("city is noida");
• }else if(city == "Agra") {
• System.out.println("city is agra");
• }else {
• System.out.println(city);
• }
• }
• }
• Output: Delhi
•
• 4. Nested if-statement
• In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
• Syntax of Nested if-statement is given below.
• if(condition 1) {
• statement 1; //executes when condition 1 is true
• if(condition 2) {
• statement 2; //executes when condition 2 is true
• }
• else{ statement 2; //executes when condition 2 is false } }
• Consider the following example.:-
• public class Student {
• public static void main(String[] args) {
• String address = "Delhi, India";
•
• if(address.endsWith("India")) {
• if(address.contains("Meerut")) {
• System.out.println("Your city is Meerut");
• }else if(address.contains("Noida")) {
• System.out.println("Your city is Noida");
• }else {
• System.out.println(address.split(",")[0]);
• }
• }else {
• System.out.println("You are not living in India"); } } } Output: Delhi
• Switch Statement:-
• In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements.
• The syntax to use the switch statement is given below.
• switch (expression){
• case value1: Consider the following example to understand
• statement1; the flow of the switch statement.
• break; public class Student implements Cloneable {
• . public static void main(String[] args) {
• . int num = 2;
• . switch (num){
• case valueN: case 0:
• statementN;
System.out.println("number is 0");
• break;
break;
• default:
case 1:
• default statement;
• }
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output: 2
Java Control Structures
1) Loop statements
In programming, sometimes we need to execute the block
of code repeatedly while some condition evaluates to true.
However, loop statements are used to execute the set of
instructions in a repeated order.
The execution of the set of instructions depends upon a
particular condition.
• In Java, we have three types of loops that execute
similarly. However, there are differences in their syntax
and condition checking time.
1. for loop
2. while loop
3. do-while loop
1. for loop:-
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code.
We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
• for(initialization, condition, increment/decrement) {
• //block of statements
• }
• Example:-
• public class Calculattion {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int sum = 0;
• for(int j = 1; j<=10; j++) {
• sum = sum + j;
• }
• System.out.println("The sum of first 10 natural numbers is " + sum);
• }
• }
• Output:-The sum of first 10 natural numbers is 55
2. While loop:-
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
• The syntax of the while loop is given below.
• while(condition){
• //looping statements
• }
• Example:-Calculation .java
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• while(i<=10) {
• System.out.println(i);
• i = i + 2;
• }
• }
• }
• Output:
• Printing the list of first 10 even numbers
• 0
• 2
• 4
• 6
3. do-while loop:-
• The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
The syntax of the do-while loop.
• do
• {
• //statements
• } while (condition);
• Example:- Calculation.java
• public class Calculation {
• public static void main(String[] args) {
• // TODO Auto-generated method stub
• int i = 0;
• System.out.println("Printing the list of first 10 even numbers \n");
• do {
• System.out.println(i);
• i = i + 2;
• }while(i<=10);
• }
• }
• Output:-
• Printing the list of first 10 even numbers
• 0
• 2
• 4
• 6
• 8
• 10
Arrays
An array is a collection of similar type of elements which
has contiguous memory location.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index
and so on.
We can store primitive values or objects in an array in Java.
Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Advantages:-
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
• There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
• Single Dimensional Array in Java
• Syntax to Declare an Array in Java
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];