0% found this document useful (0 votes)
18 views

JAVA

The document provides an overview of the Java programming language, including its history, usage statistics, environment, basic syntax like classes and methods, variables, data types, operators, and comments. It also discusses how Java programs are compiled and executed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

JAVA

The document provides an overview of the Java programming language, including its history, usage statistics, environment, basic syntax like classes and methods, variables, data types, operators, and comments. It also discusses how Java programs are compiled and executed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

What is Java

A program is a collection of instructions that performs a specific task when executed by a


computer. A program must be written in a programming language.Java is one of the most
popular programming languages. Some statistics about Java are given below:

● Java has been evolving since 1991 with different editions


● According to the TIOBE Programming Community Index, it has been
one of the top 5 programming languages for the past several years
● It is being used by more than 10 million developers worldwide
● More than 15 billion devices are powered by Java technology
● More than 125 million Java-based TV devices have been deployed
● 97% of enterprise desktops run Java

Java environment

Java which are called as High-level programming languages. But


computers cannot understand high-level languages, they understand only
binary language, i.e., 0's and 1's. This is the reason that every program that
we write needs to get converted into binary form for the computer to
understand.

This conversion is made possible using system software called compilers


and interpreters.

In Java, the program (source code) written by the programmer gets


compiled and converted into byte code (compiled code) by the Java
compiler.

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 {

public static void main(String[] args) {

System.out.println("Hello World! Welcome to Java


Programming!");

class Welcome {

public static void main(String[] args) {

System.out.println("Hello World! Welcome to Java


Programming!");

1. The message is displayed using System.out.println which is used for


displaying messages or output in Java.
2. Every statement in Java program must end with semicolon (;).
3. Every statement in Java must be present inside a method. A method
is a block of code that performs a particular task.
4. In the code given above, the method is named as main. Every
program in Java must have a main method as the code execution
starts from the main method.
5. The method is defined using curly braces ({}). { signifies the start of a
code block and } signifies its end.
6. Every method in Java must be present inside a class. In the code
given above, the class is named as Welcome. You will learn about
classes and methods in detail later in the course.
7. Java is a case-sensitive programming language. E.g. - The word
class should be written in lower case.

Execution of Java program

The development, compilation and execution of Java programs is taken


care by JDK which contains 2 main components: Development tools and
JRE.

● Java compiler (javac.exe) - It is the primary Java compiler. The


compiler accepts Java source code and produces Java bytecode
conforming to the Java Virtual Machine Specification (JVMS).
● Java launcher (java.exe) - It helps in launching a Java application
during execution.

Next, let us discuss about Java Runtime Environment (JRE).

The Java Runtime Environment (JRE) contains Java Virtual Machine(JVM)


and the Java standard library (Java Class Library).

● 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

If a program written on a particular platform can run on other platforms


without any recompilation, it is known as a platform independent program.
Usually larger applications are created by a team of developers. While most
of them could be working on the same operating system such as Windows,
others might be using different operating systems like Mac or Linux. In this
scenario, we might have a situation where a program written on Windows
needs to be executed on Mac OS also.
Since Java is platform independent, it is not a problem. A program written
using Java on Windows will execute without any recompilation on any
other platform
Keywords
Every programming language has a set of keywords which are reserved
words having a predefined meaning. Each keyword represents a specific
functionality in the language.

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

An identifier is the name given to a variable, method or class to uniquely


identify it. In Java, following rules apply to the identifier name:

● It can contain alphanumeric characters([a-z], [A-Z], [0-9]), dollar sign


($), underscore (_)
● It should not start with a digit ([0-9])
● It should not have spaces
● It should not be a Java keyword
● It is case-sensitive
● It has no length restrictions
Data types
Primitive data types are the basic data types defined in Java. There are 8
primitive data types as shown in the below table.

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

In Java, variable names should be nouns starting with lowercase letter. If it


contains multiple words, then every inner word must start with capital
letter. This type of casing is called camel casing.

Some examples of variables are given below:

● 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.

There are two types of comments in Java:

//This is a single line comment

public static void main(String args[]) {

int age = 25; // Here age is a variable

System.out.println(age);

Multi-line comment

It is used to comment multiple lines of code


public static void main(String args[]) {

/*

Given below is a variable age

and a print statement to print age

*/

int age = 25;

System.out.println(age);

public static void main(String args[]) {

/*

Given below is a variable age

and a print statement to print age

*/

int age = 25;

System.out.println(age);

public static void main(String args[]) {

int discountPercentage = 10;

double totalPrice = 800;

double priceAfterDiscount = totalPrice * (1 - ((double)


discountPercentage / 100));

if (totalPrice > 500) {


priceAfterDiscount = priceAfterDiscount * (1 - ((double) 5 /
100));

System.out.println("Customer has paid a bill of amount: "+


priceAfterDiscount);

Operator

Operators are the symbols used to perform specific operations. There are
various operators that can be used for different purposes.

The operators are categorized as:

● 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.

public static void main(String args[]) {

int numOne = 10;

int numTwo = 5;

System.out.println(numOne + numTwo); //Output will be 15

System.out.println(numOne - numTwo); //Output will be 5

System.out.println(numOne * numTwo); //Output will be 50

System.out.println(numOne / numTwo); //Output will be 2

System.out.println(numOne % numTwo); //Output will be 0

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.

public static void main(String args[]) {


int numOne = 100;
int numTwo = 20;
int numThree = 30;
System.out.println(numOne > numTwo && numOne > numThree);
//Output will be true
}

Ternary operator
Ternary operator is used as a single line replacement for if-then-else
statements and acts upon three operands.

Syntax:

<condition> ? <value if condition is true> : < value if condition is false>

E.g.:

public static void main(String args[]) {


int numOne = 10;
int numTwo = 5;
int min = (numOne < numTwo) ? numOne : numTwo;
System.out.println(min); //Output will be 5
}
first the condition (numOne < numTwo) is evaluated. The result is false and
hence, min will be assigned the value numTwo.

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.

public static void main(String args[]) {


int numOne = 10; //The value 10 is assigned to numOne
System.out.println(numOne); //Output will be 10
numOne += 5;
System.out.println(numOne); //Output will be 15
numOne -= 5;
System.out.println(numOne); //Output will be 10
numOne *= 5;
System.out.println(numOne); //Output will be 50
numOne /= 5;
System.out.println(numOne); //Output will be 10
}

BITWISE OPERATOR
Bitwise operators are used to perform manipulation of individual bits of a
number.

Step 1:

Divide the decimal number by 2.

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:

Continue this process until the result of the division is 0.

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).

Lets take the example of 11001.

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

// Unsigned right shift operator(>>>)


System.out.println(a >> 2);
System.out.println(a >>> 2);
// works in the same way for positive numbers
int c = -1;
System.out.println(c >> 2);
System.out.println(c >>> 2);

// There is no unsigned left shift operator(<<<). The below line


leads
// to an error
// System.out.println(a<<<2);

// Bitwise operators are used to perform manipulation of


individual bits

// Logical OR(||) does not check second condition if first is true


// Bitwise OR(|) always checks both conditions even if first
condition
// is true or false
System.out.println(a | b);
// Logical AND(&&) does not check second condition if first is
false
// Bitwise AND(&) checks both conditions even if first condition
is true
// or false
System.out.println(a & b);
}
}
OPERATOR PRECEDENCE

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: num1 = num2 = num3 = 39 is treated as (num1 = (num2 =


(num3 = 39))), leaving all three variables with the value 39, since the =
operator has right-to-left associativity. On the other hand, 84 / 4 / 3 is
treated as ((84 / 4) / 3) since the / operator has left-to-right associativity.
Some operators, like the postfix and prefix operators, are not associative:
for example, the expression num++-- is invalid
VARIABLE
a variable will not be able to store a value if the value is more than the
capacity of the datatype of the variable.

DATA TYPE COMPATIBILITY


Whenever any operation is performed containing different data types, the
data type of result is the largest data type in the expression.

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.

This conversion is of two types:

● Implicit
● Explicit

Implicit type conversion

Implicit Type Conversion is also known as Widening conversion. It happens


in the below scenarios:
● When a value of a data type with smaller range is assigned to a
variable of a compatible data type with larger range.
● When two variables of different data types are involved in an
expression, the value of smaller range datatype is converted to a
value of larger range datatype and then the operation is performed.

int discountPercentage = 10;

double newDiscountPercentage = discountPercentage;

Here, when we assign the value of discountPercentage to


newDiscountPercentage, automatically discountPercentage is converted to
double type. It is done automatically by the compiler; hence it is called as
Implicit type conversion.

In Java, implicit type conversion happens as depicted in the diagram below.


For example, if a short variable is assigned to int, long, float or double
variable, it will get converted implicitly.

Explicit type conversion

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.

double totalPrice = 200;

int newPrice = totalPrice;


This will lead to an error because a value of larger range data type, in this
case double, cannot be directly assigned to a smaller range data type, in
this case int. Here, you need to explicitly typecast double to int as shown
below.

int newPrice = (int)totalPrice;

public static void main(String[] args) {

int discountPercentage = 10;

double totalPrice = 200;

double priceAfterDiscount = totalPrice * (1 - (discountPercentage /


100));

System.out.println("Customer has paid a bill of amount: "+


priceAfterDiscount);

Here, the result of (discountPercentage / 100) will be integer and the


fractional part will be lost. This happens because both the operands,
discountPercentage and 100, are integers. To get the result with fractional
part, one of the operands must be converted to float or double as below.

double priceAfterDiscount = totalPrice * (1 - ((double)discountPercentage /


100));

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

An "if" statement contains a relational and logical expression followed by a


block of statements. Based on the result of the expression, the
corresponding statements/code blocks get executed or skipped.

if (<condition>) {

<statements>;

public class Customer {

public static void main(String[] args) {

String customerType = "Regular";

int quantity = 2;
int unitPrice = 10;

int totalCost = 0;

int discount = 5;

totalCost = unitPrice * quantity;

if (customerType == "Regular") {

totalCost = totalCost - (totalCost * discount / 100);

System.out.println("You are a regular customer and


eligible for 5% discount");

System.out.println("Total cost: " + totalCost);

IF-ELSE

An if statement can be written along with an else statement. The


condition/expression given in the if statement is checked and set of
statements are executed based on the outcome of the condition. If the
condition is true, the statements written in if block get executed. If the
condition is false, then the statements inside else block get executed.

if (<condition>) {

<statements>;

else {

<statements>;

}
public class Customer {

public static void main(String[] args) {


String customerType = "Regular";
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
eligible for 5% discount");
} else {
totalCost = totalCost + deliveryCharge;
System.out.println("You need to pay an additional
delivery charge of $5");
}
System.out.println("Total cost: " + totalCost);
}
}

class Tester {
public static void main(String[] args) {
int number = 5;
if (number % 2 == 0) {
System.out.println(number + " is an even number");
} else {

System.out.println(number + " is an odd number");


}
}
}

IF ELSE IF

it is a combination of else and if. Like else, it extends an if statement to


execute a different set of statements in case the original if expression
evaluates to false. Then, the conditions present inside the else if blocks are
checked. Once a condition evaluates to true, remaining else if and else
statements are skipped.

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>;
}

public class Customer {


public static void main(String[] args) {
String customerType = "Regular";
int quantity = 3;
int unitPrice = 10;
int discount = 5;
int deliveryCharge = 5;
int totalCost = unitPrice * quantity;
if (customerType == "Regular") {
totalCost = totalCost - (totalCost * discount / 100);
System.out.println("You are a regular customer and
eligible for 5% discount");
System.out.println("The total cost to be paid is " +
totalCost);
} 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 // If there is only one statement inside a block, {} is
optional
System.out.println("Invalid customer type");
}
}

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.

switch (expression or variable) {


case value1: <statements>;
break;
case value2: <statements>;
break;
default: <statements>;
}

During execution, the result of expression or variable written in the switch


statement is compared with the constant values of cases one by one.
When a match is found, the set of statements present in that case are
executed until a break statement is encountered or till the end of switch
block, whichever occurs first. In the absence of break statement, the flow of
control falls through subsequent cases and executes the statements of all
those cases until it reaches a break statement or end of switch block.

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:

● char and integral datatypes are supported in switch-case statement,


but float or double are not supported.
● String datatype is also supported in switch-case statement from Java
7 version onwards.
public class Customer {
public static void main(String[] args) {
String orderedFood = "Pizza";
switch (orderedFood) {
case "Burger":
System.out.println("You have ordered Burger. Unit price:
$10");
break;
case "Pizza":
System.out.println("You have ordered Pizza. Unit price:
$15");
break;
case "Sandwich":
System.out.println("You have ordered Sandwich. Unit
price: $8");
break;
default:
System.out.println("Invalid selection");
}
}
}

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
+ "%");
}
}

Iteration control structure


Iteration control structures are used to execute a set of statements
repeatedly. To terminate the repetition, a condition is required.

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>);

//Importing the Scanner class


import java.util.Scanner;
public class Customer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Creating a Scanner
object
int totalCost = 0;
char wantToAddFoodItem = 'N';
int unitPrice = 10;
int quantity = 1;
do {
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 the order? Y or N");
String input = sc.next(); // Accepting input from the
customer
// Extracting first character from the input string
wantToAddFoodItem = input.charAt(0);
} while (wantToAddFoodItem == 'Y');
System.out.println("Thank you for ordering the food! It will
reach you shortly...");
}
}

//Importing the Scanner class


import java.util.Scanner;
public class Customer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Creating a Scanner
object
int totalCost = 0;
char wantToAddFoodItem = 'N';
int unitPrice = 10;
int quantity = 1;
do {
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 the order? Y or N");
String input = sc.next(); // Accepting input from the
customer
// Extracting first character from the input string
wantToAddFoodItem = input.charAt(0);
} while (wantToAddFoodItem == 'Y');
System.out.println("Thank you for ordering the food! It will
reach you shortly...");
}
}

For loop
The 'for' loop is used when the number of iterations are known.
for (<initialization>; <condition>; <increment/decrement>) {
<statements>;
}

● Initialization: It is used for initializing the variables used for checking


the condition. It is executed only once and gets executed when the
loop starts.
● Condition: It is used for checking the condition to decide whether the
loop should be terminated or executed. If the condition is true, the
body of the loop is executed, else the loop terminates.
● Increment / Decrement: It increments or decrements the value of the
variable used for checking the condition after every iteration of the
loop.

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.

//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;
int unitPrice = 10;
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();
System.out.println("You have ordered: " + foodItem);
totalCost += unitPrice * quantity;
System.out.println("Order placed successfully!");
System.out.println("Total cost of the order: " + totalCost);
}
}
}

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
}
}
}

//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;
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.

break statement is also used to terminate the execution of a switch case.

Continue statement

continue statement is used to skip the current iteration of a loop and


continue with the next iteration. In case of while and do-while loops,
continue statement skips the remaining code of the loop and passes the
control to check the loop condition. Whereas in case of for loop, the control
goes to the increment section and then the condition is checked.
In the below code, when the value of counter is 3, continue statement is
encountered which skips the current iteration and continues with the next
iteration.

//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;
int unitPrice = 10;
System.out.println("Enter the number of food items to be
ordered");
int noFoodItemsToBeOrdered = sc.nextInt();
for (int counter = 1; counter <= noFoodItemsToBeOrdered;
counter++) {
if (counter == 3)
continue;
System.out.println("Enter the food item");
String foodItem = sc.next();
System.out.println("Enter the quantity");
int quantity = sc.nextInt();
System.out.println("You have ordered: " + foodItem);
System.out.println("You have successfully placed the
order number: "+ counter);
totalCost += unitPrice * quantity;
System.out.println("Total cost of the order: " + totalCost);
}
}
}

public class Customer {


public static void main(String[] args) {
String customerType = "Regular";
String orderedFood = "Pizza";
int quantity = 1;
int unitPrice = 10;
int totalCost = 0;
int discountPercentage = 5;
int deliveryCharge = 5;
totalCost = unitPrice * quantity;
if (customerType.equals("Regular") &&
orderedFood.equals("Pizza")) {
System.out.println("You have ordered Pizza");
totalCost = totalCost - (totalCost * discountPercentage /
100);
} else if (customerType.equals("Guest") &&
orderedFood.equals("Pizza")) {
System.out.println("You have ordered Pizza");
totalCost = totalCost + deliveryCharge;
} else {
System.out.println("Invalid selection");
}
System.out.println("The total cost to be paid is " + totalCost);
}
}

Object Oriented Programming

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.

OOP has many advantages. Some of them are listed below:

● Modularity: OOP enables programmers to create modules that do not


need to be changed when an object is added.
○ A programmer can simply create a new object to represent a
new real-life entity.
● Scalability: OOP makes development and maintenance easier.
○ Since the design is modular, part of the system can be updated
in case of issues without a need to make large scale changes.
○ In structured programming (like C language), it is not easy to
manage the code as project size grows. These languages have
functions that do not clearly segregate the functionality and
attributes and makes it difficult for the programmer to
understand the code.
● Data hiding: OOP provides hiding and securing data.
● Real life scenario: OOP provides ability to simulate real world event
more effectively and efficiently.
A representation specifying the characteristics and behaviors of an object
is called a class. It is not a real life entity but a template for representing
real life entities.

Classes and objects

An object, which is an instance of a class is a real life entity which has


some attributes and behaviors. The class determines the attributes and
behaviors which an object should possess to belong to the class.
A class can have attributes (characteristics) and methods (behaviors)

Attributes are the elements or variables which hold the values or state of a
particular entity.

class Customer {

public String customerId;

public String customerName;

public long contactNumber;

public String address;

● Attributes are represented in classes by variables.


● Attributes represent the state of a real life entity.
● Each real life entity can have its own values for those variables. Since
each instance of a class has different values for its variables, these
variables are called instance variables.
● Each instance variable has a data type associated with it. In the given
code, String and long are the data types used.
Apart from data types, you can see another keyword being used, public. It is
an access modifier.

● Access modifiers help in limiting access to the members of a class. It


can be used along with class, attribute and method.
● There are multiple access modifiers. Let us discuss two of them now.
○ private - private allows members to be accessible only inside
the class
○ public - public allows members to be accessible in other
classes as well

Methods are the set of instructions which define the behaviors of the entity.

class Customer {

public String customerId;

public String customerName;

public long contactNumber;

public String address;

public void displayCustomerDetails() {

System.out.println("Displaying customer details \n***********");

System.out.println("Customer Id : " + customerId);

System.out.println("Customer Name : " + customerName);

System.out.println("Contact Number : " + contactNumber);

System.out.println("Address : " + address);

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

In Java, an object of a class is created using the new keyword.

public class Tester {

public static void main(String args[]) {

// Object creation

Customer customer = new Customer();

// Assigning values to the instance variables

customer.customerId = "C101";

customer.customerName = "Stephen Abram";

customer.contactNumber = 7856341287L;

customer.address = "D089, St. Louis Street, Springfield, 62729";


}

● 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.

● Class names in Java should follow pascal case


○ Pascal case are words created by concatenating capitalized
words
○ E.g. - Customer, RegularCustomer, PremiumCustomer
● Method names and variables in Java should follow camel case
○ In camel case, each word in the middle of the phrase begins
with a capital letter, with no spaces or punctuation used
between words
○ E.g. - customerName, contactNumber, displayCustomerDetails

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy