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

java2 (1)

The document provides an overview of decision-making statements, loops, and classes in Java, including examples of if statements, switch statements, and various types of loops. It explains the structure and components of Java classes, including POJO, static, concrete, abstract, final, and inner classes, along with object creation methods. Additionally, it highlights the differences between classes and objects in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java2 (1)

The document provides an overview of decision-making statements, loops, and classes in Java, including examples of if statements, switch statements, and various types of loops. It explains the structure and components of Java classes, including POJO, static, concrete, abstract, final, and inner classes, along with object creation methods. Additionally, it highlights the differences between classes and objects in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 2

Decision Making Statements in Java

If Statement in Java
public class IfStatementExample {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote!");
} }}
If-Else Statement in Java
public class IfElseStatementExample {
public static void main(String[] args) {
int age = 16;
if (age >= 18) {
System.out.println("You are eligible to vote!");
}
else
{ System.out.println("You are not eligible to vote yet.");
}
}}
Nested If Statements in Java
public class TicketSystem {
public static void main(String[] args) {
int age = 20;
boolean isStudent = false;
if (age >= 18) {
System.out.println("You are eligible to watch movies.");
if (isStudent) {
System.out.println("As a student, you get a discounted ticket.");
}
else {
System.out.println("You need to purchase a regular ticket.");
}
}
else {
System.out.println("Sorry, you are not eligible to watch movies.");
} }}

If-else-If Statements in Java


public class TransportationExample {
public static void main(String[] args) {
int distance = 10;
/ /Distance in kilometers
if (distance < 1) {
System.out.println("You can walk to your destination.");
}
else if (distance < 5) {
System.out.println("Cycling would be a good option for you.");
}
else if (distance < 10) {
System.out.println("Taking a bus is a convenient choice.");
}
else {
System.out.println("It would be best to drive a car.");
} }}

Switch Statements in Java


public class BeverageExample {
public static void main(String[] args) {
String beverage = "cappuccino";
switch (beverage) {
case "coffee":
System.out.println("Enjoy your hot coffee!");
break;
case "tea":
System.out.println("Savor the flavor of your tea!");
break;
case "cappuccino":
System.out.println("Indulge in the creamy cappuccino!");
break;
default:
System.out.println("Sorry, we don't have that beverage.");
} }}

Jump Statement
The jump statements are the keywords in Java which have specific meaning and specific
action of disrupting the normal flow of the program. Some of them are:
Break Statement
public class BreakExample {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1: System.out.println("You selected option 1.");
break;
case 2:
System.out.println("You selected option 2.");
break;
case 3:
System.out.println("You selected option 3.");
break;
default:
System.out.println("Invalid choice.");
break;
}
System.out.println("End of program.");
}}

Continue Statement
public class ContinueExample {
public static void main(String[] args) {
// Imagine you are counting from 1 to 10
for (int i = 1; i <= 10; i++) {
// Check if the current number is divisible by 2
if (i % 2 == 0) {
// Skip the iteration if the number is divisible by 2
continue;
}
// Print the current number
System.out.println(i);
} }}

Return Statement
public class PizzaDelivery {
public static double calculateTotalPrice(int pizzaCount) {
double pricePerPizza = 12.99;
double totalPrice = pizzaCount * pricePerPizza;
// Return the calculated total price
return totalPrice; }
public static void main(String[] args) {
int numberOfPizzas = 3;
double total = calculateTotalPrice(numberOfPizzas);
System.out.println("Total price: $" + total);
}}
Loops In Java
Loops are a block of code that executes itself until the specified condition becomes false.
'for loop' in Java
class ForLoopDemo {
public static void main(String[] args) {
for (int i=1; i<=10; i++)
{
if (i%2==0)
System.out.println(i);
} System.out.println("Loop Ending");
}}
For-Each Loop
For-each loop is used to iterate over a group of elements like an array. It is generally used to
traverse each element of an array.
class ForEach_Loop_Demo{
public static void main(String args[]) {
int array1[] = {1,2,3,4,6,7,8,9,10};
for( int i:array1) {
System.out.println(i); } }
}

'while loop' in Java


class While_Loop_Demo{
//print even numbers ranging from 1 to 10
public static void main(String args[]) {
int i = 1; //initialization
while (i<=10) //condition or termination {
if (i%2==0) {
System.out.println(i);
}
i++; //increment
} }}

Do-While Loop
class Do_While_Loop_Demo{
//print even number
public static void main(String args[]) {
int i = 1; //initialization
do {
System.out.println(i);
i++; //increment
}
while (i%2==0);//condition or termination
}}
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which objects
are created.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
Example of Java Class
class Student {
int id;
String name;
public static void main(String args[])
{
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Components of Java Classes
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
6. Body: The class body is surrounded by braces, { }.

Types of classes in JAVA

POJO Class
POJO stands for “Plain Old Java Object”. A class which contains only private variables and
setter and getter methods to use those variables is called POJO class. It is a pure data
structure that has fields and may override some methods from Object (e.g. equals) or some
other interface like serializable but does not have the behavior of its own.
Properties of POJO class –
 Public setter and getter methods are a must while writing a POJO class.
 All instance variables should be private.
 It should not extend pre-specified classes.
 It should not implement pre-specified interfaces.
 Should not contain pre-specified annotations.
 It may not have a no-argument constructor.
Example
1 class POJO {
2 private int value=365;
3 public int getValue() {
4 return value;
5 }
6 public void setValue(int value) {
7 this.value = value;
8 }
9 }
10 public class Test {
11 public static void main(String args[]){
12 POJO p = new POJO();
13 System.out.println(p.getValue());
14 }
15 }
Output
365

Static Class
In Java, static is a keyword used to describe how objects are managed within the memory. A
static object belongs specifically to the class, instead of instances of that class. The sole
purpose of the class is to provide blueprints of its inherited classes. A static class can contain
static members only. You cannot create an object for a static class.
Example
1 public class Bank
2 {
3 private static String note = "Bank";
4 public static class SBISavings
5 {
6 public void displayOutput()
7 {
8 System.out.println(" SBISaving is: " + note);
9 }
10 }
11 }
12 public static void main(String[] args)
13 {
14 //creating instance of static class Bank.
15 SBISavings bs = new Bank.SBISavings();
16 //calling the method
17 bs.displayOutput();
18 }
Output
SBISavings is: Bank

Concrete Class
Any normal class which does not have any abstract method or a class having an
implementation for all of its methods is basically a concrete class. They cannot have any
unimplemented methods. A concrete class can extend its parent class, an abstract class or
implement an interface if it implements all their methods. It is a complete class that can be
instantiated.
Example
1public class Concrete { // Concrete Class
2 static int sum(int x, int y) {
3 return a + b;
4 }
5 public static void main(String args[]) {
6 int p = sum(6, 8);
7 System.out.println("Sum: " + p);
8 }
9}
Output
Sum: 14
Abstract Class
An abstract class is declared with an abstract keyword and have zero or more abstract
methods. These classes are incomplete classes, therefore, to use an abstract class we strictly
need to extend the abstract classes to a concrete class. It can have constructors and static
methods as well. It can have final methods which will force the subclass to keep the body of
the method unhung.
Example
1
2
3 interface X
4 {
5 int product(int x, int y);
6 }
7 // This is an abstract class
8 abstract class Product implements X
9 {
10 // this method calculates
11 // product of two numbers
12 public int product(int x, int y)
13 {
14 return x * y;
15 }
16 }
17 // This is a concrete class that implements
18 class Main extends Product
19 {
20 // main method
21 public static void main(String args[])
22 {
23 Main ob = new Main();
24 int p = ob.product(20, 10);
25 // print product
26 System.out.println("Product: " + p);
27 }
28 }
Output
Product: 200

Final Class
Once a variable, method or a class is declared as final, it’s value remains the same
throughout. The final keyword in a method declaration indicates that the method cannot be
overridden by any subclasses i.e., a class that has been declared final cannot be subclassed.
Example:
1 final class BaseClass {
2 void Display() {
3 System.out.print("This is the Display() method of BaseClass.");
4 }
5 }
6 class DerivedClass extends BaseClass { //Compile-time error - can't inherit final class
7 void Display() {
8 System.out.print("This is Display() method of DerivedClass.");
9 }
10}
11 public class FinalClassDemo {
12 public static void main(String[] arg) {
13 DerivedClass d = new DerivedClass();
14 d.Display();
15 }
16}

Output
cannot inherit from final BaseClass
Compile-time error – can’t inherit final class
Inner class
Inner class means the class which is a member of another class. There are four types of inner
classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

Nested Inner class


It can access any private instance variable of an outer class. Like any other instance variable,
we can have access modifiers private, protected, public and default modifier.
class Outer {
// Simple nested inner class
class Inner {
public void show() {
System.out.println("This is inside a nested class method ");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output
This is inside a nested class method

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and methods
of a class. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of
an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Different ways to create objects in Java

1. Using the new keyword:

The developer can create an object of a class using the new keyword followed by the
constructor of the class.

Example:

ClassName objectName = new ClassName();

With this line of code, an object of the class "ClassName" is created and assigned to the variable
"objectName."
2. Using Class.forName() method:

The developer can create an object of a class using the Class.forName() method, which returns
a Class object.

Example:
Class className = Class.forName("ClassName");

ClassName objectName = (ClassName) className.newInstance();

In this code, the class "ClassName" is dynamically loaded by "Class.forName("ClassName")"


and then created by "className.newInstance()" and assigned to the variable "objectName"
after being cast to the proper type.

3. Using clone() method:

The programmers can create a new object by cloning an existing object using the clone()
method.

Example:
ClassName object1 = new ClassName();

ClassName object2 = object1.clone();

According to this example, "object1" generates an instance of "ClassName," whereas "object2


= object1.clone()" makes a new instance of "object2" that is a copy or clone of "object1." You
can duplicate objects with the same characteristics and behaviors due to this.

Difference between Class and Object in Java

Parameter Class Object

A class is a blueprint or a template that defines the An object is an instance of a class that has
Definition
properties and behavior of objects. actual values for those properties.
An object is an instance of a class that has
A class is used to create objects, which are instances
Usage been created using the constructor of that
of that class.
class.

A class defines the properties that objects of that


Properties class will have. These properties are defined using An object has values for those properties.
variables.

A class also defines the behavior that objects of that


An object can call these methods to perform
Methods class will have. This behavior is defined using
specific tasks.
methods.

Memory A class is not allocated memory in the Java Virtual An object is allocated memory when it is
allocation Machine (JVM). created using the "new" keyword.

You might also like