JAVA
JAVA
Java environment
All the byte codes required for the program are then given to the interpreter.
The interpreter reads the byte code line by line, converts it to binary form,
also called as machine language or binary language, and then executes it.
This process requires some support and an environment for the execution
to happen. JDK (Java Development Kit) helps in this for execution of a Java
program. It provides library support and Java Runtime Environment (JRE),
the environment for developing and executing Java based applications and
programs.
First program
class Welcome {
class Welcome {
● Java Virtual Machine (JVM) - It is the virtual machine that enables the
computer to run Java programs.
● Java standard library (Java Class Library) - It is a set of dynamically
loadable libraries that Java applications can call at run time. Java
Platform is not dependent on a specific operating system and hence
applications cannot rely on any of the platform-native libraries. So,
the Java Platform provides a set of standard class libraries
containing functions common to modern operating systems.
The Java source code is saved in a file with .java extension. When we
compile a Java program (.java file), .class files (byte code) with the same
class names present in .java file are generated by the Java compiler
(javac). These .class files go through various steps when we run the
program as shown in the below diagram.
Platform independence
Variable
Data is stored in variables. A variable is a named memory location which
holds some value. The value stored in a variable can vary during the
execution of the program.
public static void main(String[] args) {
int discount = 10; // discount is a variable
double totalPrice = 200; // totalPrice is a variable
double priceAfterDiscount = totalPrice * (1 - ((double) discount /
100)); // priceAfterDiscount is a variable
System.out.println("Customer has paid a bill of amount: "+
priceAfterDiscount);
}
Identifier
1. Numeric and boolean (true, false) values are written without quotes.
E.g. int score = 85; boolean isQualified = true;
2. The character value must be written in single quotes while assigning
it to a character variable. E.g. char gender = 'M';
3. A long value is assigned to the variable, suffixed with L (uppercase
letter or lower case letter L can be used). E.g. long salary = 500000L;
4. A float value must be suffixed with F or f while assigning to the
variable. E.g. float average = 78.6f;
5. You will learn about different places in the program where the
variables can be declared. As of now, note that the default values are
not applicable to the variables declared inside a method. The
variables declared inside a method must be initialized with a value
before printing their value or performing any operation on them. E.g.
class Demo {
public static void main(String[] args) {
int quantity;
float totalCost = 10 * quantity; // error on this line
System.out.println(totalCost);
}
}
Codeing standard
● mobileNumber
● name
● unitPrice
● paymentMode
● Age
Comments are those statements which are not executed by the compiler.
Comments can be used to provide information about a variables or
statement.
System.out.println(age);
Multi-line comment
/*
*/
System.out.println(age);
/*
*/
System.out.println(age);
Operator
Operators are the symbols used to perform specific operations. There are
various operators that can be used for different purposes.
● Unary
● Arithmetic
● Relational
● Logical
● Ternary
● Assignment
● Bitwise
Unary operators
Unary operators act upon only one operand and perform operations such
as increment, decrement, negating an expression or inverting a boolean
value.
public static void main(String args[]) {
int numOne = 10;
int numTwo = 5;
boolean isTrue = true;
System.out.println(numOne++ + " " + ++numOne); //Output will be 10
12
System.out.println(numTwo-- + " " + --numTwo); //Output will be 5 3
System.out.println(!isTrue + " " + ~numOne); //Output will be false -13
}
Arithmetic operators
Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication and division.
int numTwo = 5;
Relational operators
Relational operators are used to compare two values. The result of all the
relational operations is either true or false.
public static void main(String args[]) {
int numOne = 10;
int numTwo = 5;
System.out.println(numOne > numTwo); //Output will be true
}
Logical operators are used to combine two or more relational expressions
or to negate the result of a relational expression.
Ternary operator
Ternary operator is used as a single line replacement for if-then-else
statements and acts upon three operands.
Syntax:
E.g.:
Assignment operator
Assignment operator is used to assign the value on the right hand side to
the variable on the left hand side of the operator.
BITWISE OPERATOR
Bitwise operators are used to perform manipulation of individual bits of a
number.
Step 1:
Step 2:
Write the number on the right hand side. This will be either 1 or 0.
Step 3:
Divide the result of the division and again by 2 and write the remainder.
Step 4:
Step 5:
The first remainder that you received is the least significant bit and the last
remainder is the most significant bit.
The decimal number is equal to the sum of binary digits (d n) times their
power of 2 (2n).
11001 = 1*24+1*23+0*22+0*21+1*20=16+8+0+0+1=25
Output:
40
2
2
2
-1
1073741823
30
0
class Tester {
public static void main(String args[]) {
// Shift operator (<< and >>) is used to move the left operands
value by
// the number of bits specified.
int a = 10;
int b = 20;
System.out.println(a << 2); // left-shift operator moves the
value to
// the left side
System.out.println(b >> 3); // right-shift operator moves the
value to
// the right side
Operators also have precedence. The below table lists the operators
according to the precedence from highest to lowest.
Operators with higher precedence are evaluated before the operators with
lower precedence. When an expression has two operators with the same
precedence one after the other, the expression is evaluated according to
their associativity. The associativity of operators can be left-to-right, right-
to-left or no associativity.
For example, the result of (intVar + floatVar) will be a float value, the result
of (intVar + longVar + doubleVar) will be a double value.
When you assign the value of one data type to another or when you
perform operation on two operands, their data types must be compatible
with each other. If the data types are not compatible, then the data type of
an operand needs to be converted.
● Implicit
● Explicit
Explicit Conversion is used when you want to assign a value of larger range
data type to a smaller range data type. This conversion is not done by the
compiler implicitly as there can be loss of data in some cases. Hence ,
programmers have to be cautious about such conversions. This is also
known as Narrowing conversion.
CONTROL STRUCTURE
the instructions are usually executed line by line. Sometimes, all the
statements in a program may not be executed. There can be change in the
flow of control and can be implemented using control structures.
IF
if (<condition>) {
<statements>;
int quantity = 2;
int unitPrice = 10;
int totalCost = 0;
int discount = 5;
if (customerType == "Regular") {
IF-ELSE
if (<condition>) {
<statements>;
else {
<statements>;
}
public class Customer {
class Tester {
public static void main(String[] args) {
int number = 5;
if (number % 2 == 0) {
System.out.println(number + " is an even number");
} else {
IF ELSE IF
When all the conditions are false, the else block is executed. Coding the
else block is optional.
if (<condition 1>) {
<statements>;
}
else if (<condition 2>) {
<statements>;
}
else if (<condition 3>) {
<statements>;
}
else {
<statements>;
}
class Tester {
public static void main(String[] args) {
int marks = 90;
if (marks < 50) {
System.out.println("Fail");
} else if (marks >= 50 && marks < 60) {
System.out.println("D grade");
} else if (marks >= 60 && marks < 70) {
System.out.println("C grade");
} else if (marks >= 70 && marks < 80) {
System.out.println("B grade");
} else if (marks >= 80 && marks < 90) {
System.out.println("A grade");
} else if (marks >= 90 && marks <= 100) {
System.out.println("A+ grade");
} else {
System.out.println("Invalid!");
}
}
}
Nested if
When an if statement is written within another if statement, it is known as
nested if statement. It enables us to test multiple criteria. The inner if block
condition gets executed only when the condition of the outer if block
evaluates to true.
if (<condition 1>) {
if (<condition 2>) {
<statements>;
}
else {
<statements>;
}
}
public class Customer {
public static void main(String[] args) {
String customerType = "Guest";
int quantity = 2;
int unitPrice = 10;
int totalCost = 0;
int discount = 5;
int deliveryCharge = 5;
totalCost = (unitPrice * quantity);
if (customerType == "Regular") {
totalCost = totalCost - (totalCost * discount / 100);
System.out.println("You are a regular customer and have
got 5% discount");
System.out.println("The total cost to be paid is " +
totalCost);
if (totalCost >= 20) {
System.out.println("You have got a gift
voucher!!!!");
}
} else if (customerType == "Guest") {
totalCost = totalCost + deliveryCharge;
System.out.println("You need to pay an additional
delivery charge of $5");
System.out.println("The total cost to be paid is " +
totalCost);
} else {
System.out.println("Invalid selection");
}
}
}
class Customer {
public static void main(String[] args) {
String customerType = "Guest";
int quantity = 2;
int unitPrice = 10;
int totalCost = 0;
int discount = 5;
int deliveryCharge = 5;
totalCost = (unitPrice * quantity);
if (customerType == "Regular") {
totalCost = totalCost - (totalCost * discount / 100);
System.out.println("You are a regular customer and have
got 5% discount");
System.out.println("The total cost to be paid is " +
totalCost);
if (totalCost >= 20) {
System.out.println("You have got a gift
voucher!!!!");
}
} else if (customerType == "Guest") {
totalCost = totalCost + deliveryCharge;
System.out.println("You need to pay an additional
delivery charge of $5");
System.out.println("The total cost to be paid is " +
totalCost);
} else {
System.out.println("Invalid selection");
}
}
}
Switch case
The switch statement enables to select a block from a set of options. It
allows the flow of execution to be switched according to a value.
The switch block can have a special case called default. The default case is
executed when none of the cases match with the value of
expression/variable. default is optional. If none of the cases match and if
there is no default statement, the control comes out of switch block
without executing any case.
In Java, the switch block works only for the following data types:
class Tester {
public static void main(String[] args) {
double discount;
String customerType = "Premium";
switch (customerType) {
case "Regular":
discount = 5;
case "Premium":
discount = 10;
default:
discount = 0;
}
System.out.println("Customer has got discount of " + discount
+ "%");
}
}
While loop.
When the condition becomes false, the while loop terminates and
control goes to the statement written after the while loop. The while loop is
used when the number of iterations are not known. In case of while loop,
the condition is tested before entering the while loop block and hence it
is known as an entry-controlled loop.
while (<condition>) {
<statements>;
}
//
Importing the Scanner class
import java.util.Scanner;
public class Customer {
public static void main(String[] args) {
// Create a Scanner object
Scanner sc = new Scanner(System.in);
int totalCost = 0;
char wantToAddFoodItem = 'Y';
int unitPrice = 10;
int quantity = 1;
while (wantToAddFoodItem == 'Y') {
totalCost = totalCost + (quantity * unitPrice);
System.out.println("Order placed successfully");
System.out.println("Total cost: " + totalCost);
System.out.println("Do you want to add more food items
to your order? Y or N");
String input = sc.next(); // Accepting input from the
customer
// Extracting first character from the input string
wantToAddFoodItem = input.charAt(0);
}
}
}
Do while
When the loop has to be executed at least once before the condition is
checked, do-while loop is used. After the first execution, the loop then gets
repeated as long as the condition is true. In case of do-while loop, the
condition is tested after executing the code block. Hence, it is called an
exit-controlled loop.
do {
<statements>;
} while (<condition>);
For loop
The 'for' loop is used when the number of iterations are known.
for (<initialization>; <condition>; <increment/decrement>) {
<statements>;
}
All the three parts of for loop are optional. For instance, the for loop can
also be written as for(;;) where none of the parts are provided. This for loop
will result in infinite loop.
1
12
123
1234
12345
123456
1234567
12345678
123456789
1 2 3 4 5 6 7 8 9 10
class Numbers {
public static void main(String[] args) {
int rows = 10;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
// print displays the text without adding a new line
System.out.print(j + " ");
}
System.out.println(""); // println displays the text along
with a new line
}
}
}
import java.util.Scanner;
public class Customer {
public static void main(String[] args) {
// Create a Scanner object
Scanner sc = new Scanner(System.in);
int totalCost = 0;
int unitPrice = 10;
System.out.println("Enter the max amount you can pay");
int maxAmountCustomerCanPay = sc.nextInt();
System.out.println("Enter the number of food items to be
ordered");
int noFoodItemsToBeOrdered = sc.nextInt();
for (int counter = 1; counter <= noFoodItemsToBeOrdered;
counter++) {
System.out.println("Enter the food item");
String foodItem = sc.next();
System.out.println("Enter the quantity");
int quantity = sc.nextInt();
totalCost += unitPrice * quantity;
if (totalCost > maxAmountCustomerCanPay) {
System.out.println("Sorry! Total cost is crossing
your max amount limit.");
break;
}
System.out.println("You have ordered: " + foodItem);
System.out.println("Order placed successfully");
System.out.println("Total cost of the order: " + totalCost);
}
}
}
Break statement
break statement is used to terminate a loop. After terminating the loop, the
next statement following the loop gets executed. In case of break
statement written in nested loops, the inner most loop gets terminated and
the flow of control continues with the statements of outer loop.
Continue statement
There is a need for a programming paradigm which not only focuses on the
functionality but also on the data or state of real life entities. This is
possible with a different paradigm of programming known as Object
Oriented Programming.
Object Oriented Programming(OOP) is a type of programming approach
which enables the programmers to work with real life entities like
Customer, Trainee, Employee, Company, Product, Food, Book, etc.
Java, C#, Simula, JavaScript, Python, C++, Visual Basic .NET, Ruby, Scala,
PHP etc. are some of the popular object-oriented programming languages.
OOP helps a programmer in breaking down the code into smaller modules.
These modules (classes) will have state(represented by
attributes/variables) and functionality (represented by behavior/methods).
These modules can then be used for representing the individual real life
entities known as objects.
E.g. - We can have a class named Customer to represent the state and
behavior of all customers. Each individual customer can then be
represented using an object of the Customer class.
Attributes are the elements or variables which hold the values or state of a
particular entity.
class Customer {
Methods are the set of instructions which define the behaviors of the entity.
class Customer {
System.out.println();
}
● An object is an instance of a class
● An object holds data for every instance variable of a class
● It allows us to use the instance variables and methods specified in
the class
● Any number of objects can be created for a class
// Object creation
customer.customerId = "C101";
customer.contactNumber = 7856341287L;
● The new keyword is responsible for creation of the object and having
memory allocated for it.
● Variables referring to objects are called reference variables. In the
above code, customer is a reference variable.
● Instance variables are automatically initialized to the default value of
the data type during object creation.
● Once an object is created, the object's methods and attributes can be
invoked using the "." operator depending upon the access modifier as
shown above.
The naming conventions that we follow for classes, variables and methods
are given below.