Unit 1
Unit 1
Unit 1
Simple
Object-Orient
Dynamic
ed
Distributed Portable
Multithreaded
Features Platform
Independent
of Java
High
Secured
Performance
Interpreted Robust
Architecture
Neutral
-Ms. Vishakha Bagwe
Architecture and its components
Is interpreted by
Results in
Program
Execution JVM
Windows
Mac OS
Linux
-Ms. Vishakha Bagwe
Components of Java Architecture
? A class file is the compiled form of a .java file. When we compile the Java
source code (.java file), it generates a .class file.
? The javac command is used to convert the Java source file into the class
file. The java command is used to run a Java program stored in a .class file.
? Documentation Section
✔ The documentation section is an important section but optional Package Statement
for a Java program.
✔ It includes basic information about a Java program.
Import Statement
✔ The information includes the author's name, date of creation,
version, program name, company name, and description of
the program.
Interface Statement
✔ It improves the readability of the program.
✔ Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the Class Definitions
program.
✔ To write the statements in the documentation section, we
use comments. The comments may be single-line, multi-line. Main method { main
-Ms. Vishakha Bagwe
method definition }
? Package Declaration
✔ The package declaration is optional.
✔ It is placed just after the documentation section.
✔ There can be only one package statement in a Java program. It must be
defined before any class and interface declaration.
✔ We use the keyword package to declare the package name.
? Import Statements
✔ The package contains the many predefined classes and interfaces.
✔ The import statement represents the class stored in the other package.
✔ We use the import keyword to import the class.
✔ It is written before the class declaration and after the package statement.
✔ We use the import statement in two ways, either import a specific class or
import all classes of a particular package.
-Ms. Vishakha Bagwe
? Interface Section
✔ It is an optional section. We use the interface keyword to create an interface.
✔ An interface is a slightly different from the class.
✔ It contains only constants and method declarations.
✔ Another difference is that it cannot be instantiated.
✔ We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword.
? Class Definition
✔ Without the class, we cannot create any Java program.
✔ A Java program may contain more than one class definition. We use
the class keyword to define the class.
✔ It contains information about user-defined methods, variables, and constants.
✔ Every Java program has at least one class that contains the main() method.
-Ms. Vishakha Bagwe
? Main Method
✔ The execution of all Java programs starts from the main() method.
✔ In other words, it is an entry point of the class.
✔ It must be inside the class. Inside the main method, we create objects and
call the methods
✔ public static void main(String[] args)
{
}
? The Java compiler breaks the line of code into text (words) is called Java
tokens. These are the smallest element of the Java program.
? The Java compiler identified these words as tokens.
? These tokens are separated by the delimiters. It is useful for compilers to
detect errors. Remember that the delimiters are not part of the Java tokens.
Declaration • We declare variables and constants by specifying their data type and
name.
• int quantity;
? 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.
? Type casting is a method or process that converts a data type into another
data type in both ways manually and automatically. The automatic conversion
is done by the compiler and manual conversion performed by the
programmer.
? Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place
when:
• Both data types must be compatible with each other.
• The target type must be larger than the source type.
? Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up.
? It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error.
? The object of Scanner class of the java.util package is used to read input
data from different sources.
import java.util.Scanner;
? Java Scanner Methods to Take Input
? nextInt()
? nextFloat()
? nextLine()
? next()
• Syntax:
if (condition) {
// statements
}
Here, condition is a boolean expression such as age >= 18.
● Syntax:
if (condition) {
// codes in if block
}
else {
// codes in else block
}
Here, the program will do one task (codes inside if block) if the
condition is true and another task (codes inside else block) if the
condition is false.
Example:
class Ifelseexample {
public static void main(String[] args) {
int number = 10;
// checks if number is greater than 0
if (number > 0) {
System.out.println("The number is positive.");
}
// execute this block
// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}
System.out.println("Statement outside if...else block");
}
}
Java if...else...if Statement
Syntax:
Here, if statements are executed from the top towards
if (condition1) {
the bottom. When the test condition is true, codes
// codes
} inside the body of that if block is executed. And,
The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when outer if block condition is
true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
Example:
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Switch-case statement
The Java switch statement executes one statement from multiple conditions. It
is like if-else-if ladder statement.
○ There can be one or N number of case values for a switch expression.
○ The case value must be of switch expression type only. The case value
must be literal or constant. It doesn't allow variables.
○ The case values must be unique. In case of duplicate value, it renders
compile-time error.
○ Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the
switch expression. If a break statement is not found, it executes the next
case.
○ The case value can have a default label which is optional.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example: case 6: monthString="6 - June";
//Java Program to demonstrate the example of Switch statement
break;
//where we are printing month name for the given number
case 7: monthString="7 - July";
public class SwitchMonthExample {
break;
public static void main(String[] args) {
case 8: monthString="8 - August";
//Specifying month number
break;
int month=7;
case 9: monthString="9 - September";
String monthString="";
break;
//Switch statement
break; break;
//update statement
}while (condition);
Example: Sum of Natural Numbers up to a Given Number
public class Sumdowhile {
public static void main(String args[])
{
int x = 7, sum = 0;
do { // The line will be printed even if the condition is false
sum += x;
x--;
} while (x > 0);
System.out.println(“Sum: ” + sum);
}}
For-each loop
The for-each loop is used to traverse array in Java. It is
easier to use than simple for loop because we don't need
to increment value and use subscript notation.
It works on the basis of elements and not the index. It
returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example 1:
//Java For-each loop example which prints the elements of
the array
class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
if(i==5){
break; //breaking the loop
}
System.out.println(i);
}
} }
Continue statement
○ The return type of the method and type of data returned at the
end of the method should be of the same type. For example, if a
method is declared with the float return type, the value returned
should be of float type only.
Example:
public class ReturnTest
{
int square(int num){
int sq=num*num;
return sq; // return a square value.
}
public static void main(String[] args)
{
// Create an obejct of class Test.
ReturnTest t = new ReturnTest();
// Call the method using object reference variable. Since the return type of
this method is int, we will store it using a variable of type int.
int squareOfNumber = t.square(20);
// Displaying the result.
System.out.println("Square of 20: " +squareOfNumber);
}
}
Arrays
Introduction
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. 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.
For example, if we want to store the names of 100 people then we can create an
array of the string type that can store 100 names.
Here, the above array cannot store more than 100 names. The number of values in
a Java array is always fixed.
Types of Array
dataType[] arrayName;
dataType []arrayName;
dataType arrayName[];
Example:
int rollno[];
Instantiation of an Array in Java
arrayName = new dataType[size];
To define the number of elements that an array can hold, we have to allocate memory for
the array in Java. For example,
// declare an array
int rollno[];
// allocate memory
In Java, we can declare and allocate the memory of an array in one single statement. For
example,
Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java, using
the index number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Important points to remember
Note:
● Array indices always start from 0. That is, the first element of an
array is at index 0.
● If the size of an array is n, then the last element of the array will be
at index n-1.
Access Elements of an Array in Java
We can access the element of an array using the index number. Here is the
syntax for accessing elements of an array,
}}
We can use loops to access all the elements of the array at once
class Arrdemo {
// create an array
System.out.println(age[i]);
}
Multidimensional arrays
1. dataType[][] arrayName;
2. dataType [][]arrayName;
3. dataType arrayName[][];
for(int j=0;j<3;j++){
};
System.out.print(arr[i][j]+" "); }
System.out.println();
}}