Sessions 1-2|4 Pillars of Object-Oriented Programming¶
Object refers to real-world entities like a Car, Bike, Dog, etc.
An object has two main components:
- Properties (variables)
- Behaviors (methods)
Abstraction¶
- It hides the internal implementation and exposes only the essential functionality to the user.
- It can be achieved through abstract classes and interfaces.
- Examples:
- Cellphone: Making a call is abstracted. Users press a button, not concerned with how the call connects.
- Car: Pressing the brake slows the car, but the internal workings of the braking system are hidden from the driver.
Advantages¶
- Increases security and confidentiality.
Encapsulation¶
- Encapsulation bundles the data and the code working on that data into a single unit, also known as data hiding.
To achieve Encapsulation¶
- Declare a variable in a class as private.
- Provide public getter and setter methods to modify and view the value of the variable.
Advantages¶
- Loosely coupled code.
- Better access control and security.
Inheritance¶
- Inheritance is the capability of a class to inherit properties and methods from its parent class.
- It allows the child class to reuse code from the parent class, so we do not have to write the same code again.
- It can be achieved using the
extends
keyword or through an interface.
Types of Inheritance¶
- Single Inheritance
- A child class derives properties and behaviors from a single parent class.
- Multilevel Inheritance
- A class inherits from a base class, and then another class inherits from that derived class, forming a chain of inheritance.
- Hierarchical Inheritance
- One superclass is inherited by multiple subclasses, creating a hierarchical structure.
- Multiple Inheritance
- When a class extends more than one superclass, it's known as multiple inheritance.
- It is not supported directly in Java.
- Instead, it utilizes interfaces as a mechanism to achieve similar behavior and to overcome the diamond problem.
Advantages¶
- Code reusability.
- Allows achieving polymorphism.
Polymorphism¶
- Polymorphism means "many forms".
- The same method behaves differently in different situations.
- Example:
- A person can be a father, husband, employee, and brother.
Types of Polymorphism¶
- Compile-Time Polymorphism/Static Polymorphism/Method Overloading
- Methods with the same name and return type but different parameter lists.
- Run-Time Polymorphism/Dynamic Polymorphism/Method Overriding
- A method in a child class overrides the implementation (body) of a method in its parent class.
- Operator overloading is not supported in Java.
Object Relationships¶
- Is-a Relationship
- Achieved through inheritance.
- Inheritance establishes an "is-a" relationship between parent and child classes.
- Example:
- A
DOG
is anANIMAL
.
- A
- Has-a Relationship
- When an object is used within another class.
- These relationships can be one-to-one, one-to-many, or many-to-many.
- Examples:
- A
School
hasStudents
. - A
Bike
has anEngine
.
- A
- Association: A general relationship between two distinct objects.
- Aggregation: Both objects can exist independently. The lifecycle of one object does not depend on the other.
- A
Library
can exist without theBooks
, and theBooks
can exist outside of theLibrary
.
- A
- Composition: The existence of one object depends on the other. The end of one object will end the other object.
- If a
House
is destroyed, itsRooms
are also destroyed because they cannot exist independently.
- If a
- Aggregation: Both objects can exist independently. The lifecycle of one object does not depend on the other.
System.getProperty("java.version");
21.0.5
Sesson 3|Java Virtual Machine¶
🎥 JVM Architecture – Durga sir
Java is a platform-independent, highly portable language—write once, run anywhere (WORA).
- JDK: Java Development Kit (includes JRE, language syntax, compiler, debugger).
- JRE: Java Runtime Environment (includes JVM and standard libraries).
- JVM: Java Virtual Machine (platform dependent).
JDK and JRE are platform-dependent because they contain the platform-specific JVM. However, the resulting Java bytecode is platform-independent and executes on any system with a compatible JVM.
Java Output Workflow¶
Editions¶
- JSE: Java Standard Edition (Core Java).
- JEE: Jakarta Enterprise Edition.
- JME: Java Micro Edition.
Session 4|main Method¶
🎥 Explanation of public static void main(String[] args) {}
– Durga sir
// Hello.java
public class Hello {
public static void main(String args[]) {
System.out.println("Hello, World");
}
}
The main
method is the entry point for a Java program. The JVM calls the main
method because it needs to start the program execution. Since the method is static
, the JVM can invoke it without creating an instance of the class.
If a Java file contains multiple public
classes, the JVM wouldn't know which class to call for the main
method. Therefore, Java enforces a restriction that at most one public
class can exist per .java
file, and if a class is declared public
, that class must have the same name as the file.
Sessions 5-7|Data Types and Variables¶
A variable is a named container used to store a value.
- The name can start with
$
,_
, or letters (a-z, A-Z), including Unicode characters but not with numbers. - Variable names are case-sensitive.
int A
andint a
are treated as two different variables. - Reserved words cannot be used as variable names.
- For multi-word variable names, the camelCase convention is typically used
- Constants should be written in UPPER_SNAKE_CASE (e.g., MAX_VALUE).
Primitive Data Types¶
- byte: 1 byte, default
0
- short: 2 bytes, default
0
- char: 2 bytes, default
'\u0000'
- int: 4 bytes, default
0
- float: 4 bytes, default
0.0F
- long: 8 bytes, default
0L
- double: 8 bytes, default
0.0
- boolean: N/A, default
false
The declaration int x;
is allowed at the class level with a default value of 0
. However, declaring int x;
inside a method causes a compilation error because local variables must be initialized before use.
class MyClass {
int x; // instance variable
static int staticVariable; // static variable
public void display() {
System.out.println(x); // 0
}
public void myMethod() {
int z; // local variable
System.out.println(z); // Compilation error: variable 'z' might not have been initialized
}
}
Variable Types¶
- Local: Declared within a method or block.
- Instance: Declared within a class but outside any method; unique to each instance of the class.
- Static/Class: Declared with the
static
keyword; shared among all instances of the class. - Method Parameters: Variables passed to methods.
- Constructor Parameters: Variables passed to constructors.
Types of Conversion¶
- Automatic Conversion: Implicit conversion, often from a smaller type to a larger type (e.g.,
int
tolong
). - Narrowing/Down Casting/Explicit Conversion: Explicit conversion from a larger type to a smaller type (e.g.,
double
toint
). - Promotion During Expression: Temporary conversion of types during expression evaluation (e.g., in arithmetic operations).
- Explicit Casting During Expression: Manually specifying the type conversion during expression evaluation.
// Automatic Conversion
int i = 10;
long l = i; // int to long Conversion
// Narrowing Conversion
double d = 9.75;
int x = (int) d; // double to int conversion
// Promotion During Expression
int a = 5;
float b = 10.5f;
float result = a + b; // Promotion of int to float
// Explicit Casting During Expression
double e = 20.99;
int y = (int) (a + e); // double to int Casting
Reference Data Types¶
null
is the default value for any object type, can't be applied to primitive types.
- Class: Custom data types defined by user.
- String: Represents a sequence of characters.
- Interface: Defines a contract that classes can implement.
- Array: A collection of elements of the same type.
In Java, Everything is pass by value
For primitive data types, pass-by-value means that when you pass a variable to a method, a copy of the value is made. The original value remains unchanged in the calling method, even if the value is modified within the method.
For reference types, pass-by-value means a copy of the object's memory address is passed—not the object itself. This allows methods to modify the object's fields. However, the method only has a copy of the address. So, if inside the method you try to make that address point to a completely different object, it won't affect the original address you had in the first place. Your original variable will still point to the same object it did before the method was called.
String Constant Pool¶
In Java, String Constant Pool is a special region within the heap memory that stores string literals. When a string is created using a literal, Java checks the pool to see if an identical string already exists. If it does, the new reference points to the existing string, avoiding duplication and optimizing memory usage.
String s1 = "Hello"; // string literal
String s2 = new String("Hello"); // object
System.out.println(s1 == s2); // false [memory address is different]
System.out.println(s1.equals(s2)); // true
Wrapper Classes¶
🎥 Java Wrapper Classes – Durga sir
Types¶
Autoboxing¶
Automatically converts primitive types to their corresponding wrapper classes. The 8 primitive types have respective reference classes.
int
↔Integer
float
↔Float
double
↔Double
byte
↔Byte
char
↔Character
long
↔Long
boolean
↔Boolean
short
↔Short
Example:
int x = 10;
Integer y = x; // Autoboxing
Unboxing¶
Automatically converts wrapper classes back to their corresponding primitive types.
Integer
↔int
Float
↔float
Double
↔double
Byte
↔byte
Character
↔char
Long
↔long
Boolean
↔boolean
Short
↔short
Example:
Integer x = 5;
int y = x; // Unboxing
Java Collections work with reference objects, not primitive types. Primitive types are stored in stack memory, whereas reference types are stored in heap memory.
Example:
ArrayList<Integer> arr2 = new ArrayList<Integer>();
Sessions 8-9|Methods¶
- A method is a named block of code designed to execute a specific task.
- Method enhance code readability and reusability.
public int sum(int a, int b) throws Exception {}
Access Modifiers¶
- Private: The access level of a private modifier is restricted to within the class. It cannot be accessed from outside the class.
- Default: The access level of a default modifier is limited to within the package. It cannot be accessed from outside the package. If no access level is specified, the default modifier is used.
- Protected: The access level of a protected modifier is within the package and outside the package through the child classes. If no subclass is created, it cannot be accessed from outside the package.
- Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package, and outside the package.
Return Type¶
- If a method doesn't return any value, its return type is declared as
void
. - Otherwise, the return type can be either a primitive data type or the name of a class.
Method Name¶
- Names should be verbs that describe an action.
- They should begin with a lowercase letter and use camelCase for multi-word names.
Parameters¶
- Parameters are variables passed to a method to provide input.
- A method can have zero or more parameters.
Method Body¶
- The method body contains the code to be executed when the method is called.
- It ends either when a
return
statement is executed or when the closing brace is reached. - In
void
methods, you can usereturn;
to exit early without returning a value.
Method Types¶
- System-Defined Methods: Predefined methods provided by Java, such as
Math.sqrt()
. - User-Defined Methods: Custom methods created by the programmer to perform specific tasks based on the program’s needs.
- Overloaded Methods: Methods within the same class that share the same name but differ in their parameter lists. Overloading is determined by method arguments—not by return type.
- Overridden Methods: When a subclass provides a different implementation of a method that already exists in its superclass, using the same method signature (name and return type). Overriding enables runtime (dynamic) polymorphism.
- Static Methods:
- Belong to the class rather than instances of the class.
- Can be called directly using the class name.
- Cannot access non-static instance variables or methods.
- Cannot be overridden.
@Override
is for dynamic binding, whereasstatic
is for compile-time polymorphism. - When to use static methods:
- If the method does not depend on instance data.
- For utility or helper methods.
- Example: Factory design pattern.
- When the method performs a general task based solely on its input parameters.
Abstract Method¶
- Abstract methods can only be declared within abstract classes.
- They contain only the method signature—no body or implementation.
- Subclasses are responsible for providing the method's implementation.
abstract class Animal {
public abstract void sound();
}
class Cat extends Animal {
public void sound() {
System.out.println("Meow");
}
}
Variable Arguments (varargs)¶
- Allows a method to accept a variable number of arguments.
- Only one varargs parameter is allowed per method.
- It must be the last parameter in the method’s parameter list.
- Declared using the syntax:
type... variableName
.
public static void printNumbers(int... numbers) {
for (int num : numbers) {
System.out.println(num);
}
}
Final Method¶
- A method declared with the
final
keyword cannot be overridden by subclasses.- Why? A
final
method means its implementation remains unchanged.
- Why? A
public final void hello() {
System.out.println("Hello, World!");
}
Session 10|Constructor¶
📘 A Guide to Constructors in Java – Baeldung
📘 Java Constructors vs Static Factory Methods – Baeldung
At runtime, the new
keyword calls a constructor to create an object. A child class does not inherit the constructor of its parent class. The super()
call is used to invoke the parent class's constructor before executing the child class's constructor.
A constructor is used to create an instance and initialize instance variables. It is similar to a method, except:
- The constructor's name must match the class name.
- A constructor does not have a return type.
- A constructor cannot be declared as
static
,final
,abstract
, orsynchronized
.
public class Car {
String make;
public Car(String make) {
this.make = make;
}
public static void main(String[] args) {
Car myCar = new Car("Toyota");
System.out.println(myCar.make);
}
}
Types of Constructor¶
- Default Constructor
- No-arguments Constructor
- Parameterized Constructor
- Constructor Overloading
- Private Constructor
- Constructor Chaining
this()
super()
// no-args constructor
ConstructorExample() { ... }
// parameterized
ConstructorExample1(String message) { ... }
// overloading
ConstructorExample1(String message, int num) { ... }
// private
private ConstructorExample2(boolean flag) { ... }
// super() chaining
ConstructorExample3() {
super(); // calls the superclass constructor [parent]
}
// this chaining
class Employee {
String name;
int empID;
Employee() {
this(empID);
}
Employee(int empID) {
this("AB", empID);
}
Employee(String name, int empID) {
this.name = name;
this.empID = empID;
}
}
Frequently asked Interview Questions on Constructor¶
- Why constructors do not have a return type?
- Constructors do not have a return type because their primary purpose is to instantiate and initialize objects, not to return a value.
- Why constructors cannot be final?
- A
final
method cannot be overridden. If a constructor werefinal
, it would prevent any subclass from modifying the constructor, which defeats the purpose of subclassing and initialization.
- A
- Why constructor can not be abstract?
- Abstract methods are declared without implementation and must be implemented by subclasses. Since constructors are used to instantiate and initialize objects, having an abstract constructor is meaningless—it must always have an implementation.
- Why constructor can not be static?
- Static methods belong to the class rather than any instance and cannot access instance variables. Since constructors are responsible for initializing instance variables, they cannot be
static
.
- Static methods belong to the class rather than any instance and cannot access instance variables. Since constructors are responsible for initializing instance variables, they cannot be
- Can you define a constructor in an interface?
- No, constructors cannot be defined in an interfaces because interfaces cannot be instantiated directly.
- Why is the constructor name the same as the class name?
- This convention ensures that constructors are easily identifiable and distinguishes them from regular methods, enhancing code readability and consistency.
Session 11|Memory Management¶
📘 Memory Management in Java Interview Questions (+Answers) – Baeldung
📘 Static Fields and Garbage Collection – Baeldung
Types of Memory¶
- Stack Memory
- Heap Memory
Stack Memory¶
- Stores temporary variables and has a separate memory block for methods.
- Stores primitive data types.
- Stores references to heap objects:
- Strong reference
- The
Object obj = new Object();
will not be garbage collected as long as the reference exists.
- The
- Weak reference
- A reference that allows the object to be garbage collected if there are no strong references.
WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
- Soft reference
- It allows an object to be garbage collected only when memory is low.
SoftReference<MyObject> softRef = new SoftReference<>(new MyObject());
- Strong reference
- Each thread has its own stack.
- Variables are visible only within the scope in which they are defined. Once a variable goes out of scope, it is removed from the stack (in LIFO order).
- If the stack is full, a
java.lang.StackOverflowError
is thrown.
Heap Memory¶
- Used to store objects.
- There is no fixed order for allocating memory. Memory is dynamically allocated.
- The Garbage Collector is used to delete unreferenced objects from the heap.
- The Mark and Sweep algorithm is used during garbage collection.
- Types of Garbage Collectors:
- Serial Garbage Collector
- Single-threaded; causes noticeable application pauses during cleanup.
- Parallel Garbage Collector
- Multi-threaded; reduces pause time by running GC in parallel.
- CMS (Concurrent Mark-Sweep)
- GC runs alongside application threads, minimizing pause duration.
- G1 (Garbage-First)
- Focuses on short pauses and high throughput; ideal for large heaps.
- Serial Garbage Collector
- Heap memory is shared among all threads.
- Heap also contains the String Pool.
- If the heap memory is full, a
java.lang.OutOfMemoryError
is thrown.
Heap Memory Structure¶
- Young Generation (minor garbage collection occurs)
- Eden: Where new objects are initially created.
- Survivor Spaces (S0, S1): Hold objects that survive garbage collection in Eden.
- Old Generation (major garbage collection occurs)
- Objects that have survived a certain age in the Young Generation are moved here.
Outside of Heap¶
- Permanent Generation (PermGen)
- Used in earlier Java versions (before Java 8).
- Stored class metadata and static variables.
- Replaced by MetaSpace
- MetaSpace
- Introduced in Java 8 to replace PermGen.
- Stores class metadata.
- Grows automatically as needed, using native memory rather than heap space.
class Person {
private int empId;
Person(int empId) {
this.empId = empId;
}
public int getEmpId() {
return this.empId;
}
}
class MemoryManagement {
public void hello() {
int primitiveVariable = 10;
String stringLiteral = "Hello, World";
}
public void memoryManagementTest(Person personObj) {
Person personObj2 = personObj;
String stringLiteral2 = "Hello, World";
String stringLiteral3 = new String("Good luck with Java");
System.out.println(stringLiteral3);
}
}
Person personObj = new Person(10);
MemoryManagement memObj = new MemoryManagement();
memObj.memoryManagementTest(personObj);
Good luck with Java
Sessions 24-25|Operators¶
- Operator: It indicates what action to perform, such as addition (+), subtraction (-), etc.
- Operand: It refers to the items on which the operator is applied.
- Expression: It consists of one or more operands and zero or more operators.
Categories¶
Arithmetic Operators¶
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)%
(Modulus)
Relational Operators¶
Compare the relationship between two operands and return either true
or false
.
==
(Equal to)!=
(Not equal to)>
(Greater than)>=
(Greater than or equal to)<
(Less than)<=
(Less than or equal to)
Logical Operators¶
Combine two or more conditions and return either true
or false
.
&&
(Logical AND)||
(Logical OR)
Unary Operators¶
Operate on a single operand.
++
(Increment)x++
➝ Returnsx
value, then incrementsx
by 1.++x
➝ Incrementsx
by 1, then returns the new value.
--
(Decrement)x--
➝ Returnsx
value, then decrementsx
by 1.--x
➝ Decrementsx
by 1, then returns the new value.
-
(Unary minus)+
(Unary plus)!
(Logical NOT)
Assignment Operators¶
Assign a new value to a variable.
=
(Assignment)+=
(Addition assignment)-=
(Subtraction assignment)/=
(Division assignment)*=
(Multiplication assignment)%=
(Modulus assignment)
Bitwise Operators¶
It operates using either bit 1
or bit 0
.
&
(AND)
0 0 ➝ 0
0 1 ➝ 0
1 0 ➝ 0
1 1 ➝ 1
|
(OR)
0 0 ➝ 0
0 1 ➝ 1
1 0 ➝ 1
1 1 ➝ 1
^
(XOR)
0 0 ➝ 0
0 1 ➝ 1
1 0 ➝ 1
1 1 ➝ 0
~
(NOT)- The bitwise complement of an integer
n
, denoted~n
, is equal to-(n + 1)
.
- The bitwise complement of an integer
Bitwise shift Operators¶
Used to shift the bits of a number either to the left or to the right.
<<
(Signed left shift)>>
(Signed right shift)>>>
(Unsigned right shift)
Note: There is no <<<
because <<
and <<<
are not distinct; both perform a signed left shift.
Ternary Operators¶
It functions like an if/else condition.
condition ? true : false
int x = 5;
int y = 10;
int maxValue = x > y ? x : y;
Type Comparision Operator instanceOf
¶
It is used to check the type of an object, determining whether it is an instance of a particular class.
class Parent {}
class Child1 extends Parent {}
class child2 extends Parent {}
Parent obj = new Child2();
System.out.println(obj instanceOf Child2); // true
System.out.println(obj instanceOf Child1); // false
String message = "Hello";
System.out.println(message instanceOf String); // true
Operator Precedence¶
Session 26|Control Flow Statements¶
Decision Making Statements¶
if
if/else
if/else if/else
- nested
if/else
switch
statementswitch
expressions (Introduced in Java 12)
int num = 10;
// if statement
if (num > 0) {
System.out.println("The number is positive.");
}
// if/else statement
if (num % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
// if/else if/else statement
if (num > 0) {
System.out.println("The number is positive.");
} else if (num < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
// Nested if/else statement
if (num > 0) {
if (num % 2 == 0) {
System.out.println("The number is positive and even.");
} else {
System.out.println("The number is positive and odd.");
}
} else {
System.out.println("The number is not positive.");
}
Switch Statement¶
📘 What are switch expressions and how are they different from switch statements? – Stackovrflow
📘 Java Switch Statement – Baeldung
📘 Pattern Matching for Switch – Baeldung
Key Points¶
- Case values must be unique; two cases cannot have the same value.
- The data type of the switch expression must match the data types of the case values/constants.
- Case values must be either LITERAL or CONSTANT.
- Not all use cases need to be handled.
- Nested switch statements are allowed.
- A
return
cannot be used directly from a switch statement.- However, two methods are available to achieve this (Java 12 and later):
- Using the
case N ➝
label. - Using the
yield
statement.
- Using the
- However, two methods are available to achieve this (Java 12 and later):
- Supported Data Types
- 4 primitive types:
int
,short
,byte
, andchar
- Wrapper types for the above primitives:
Integer
,Character
,Byte
, andShort
Enum
String
- 4 primitive types:
Statement Syntax¶
switch (expression) {
case value_1:
// code
break;
case value_2:
// code
break;
case value_3:
// code
break;
default:
// code
}
int a = 10;
int b = 20;
switch (a + b) {
case 10:
System.out.println("a + b = %d".formatted(10));
break;
case 20:
System.out.println("a + b = %d".formatted(20));
break;
case 30:
System.out.println("a + b = %d".formatted(30));
break;
default:
System.out.println(a + b);
}
a + b = 30
int a = 10;
int b = 10;
// without break statement
switch (a + b) {
case 10:
System.out.println("a + b = %d".formatted(10));
case 20:
System.out.println("a + b = %d".formatted(20));
case 30:
System.out.println("a + b = %d".formatted(30));
default:
System.out.println(a + b);
}
a + b = 20 a + b = 30 20
String month = "January";
month = "May";
// combine multiple cases
switch (month) {
case "January":
case "February":
case "March":
System.out.println("Month value is 1");
break;
case "April":
case "May":
case "June":
System.out.println("Month value is 2");
break;
default:
System.out.println("Month value is 0");
break;
case "July":
case "August":
case "September":
System.out.println("Month value is 3");
break;
}
Month value is 2
// Another way of combining multiple cases
// works only in Java 12 or higher
String month = "August";
month = "March";
switch (month) {
case "January", "February", "March":
System.out.println("Month value is 1");
break;
case "April", "May", "June":
System.out.println("Month value is 2");
break;
default:
System.out.println("Month value is 0");
break;
case "July":
case "August":
case "September":
System.out.println("Month value is 3");
break;
}
Month value is 1
// NOTE: Case values should be either LITERAL (2, "Hello") or CONSTANT.
int value = 1;
switch (3 - 2) {
case value:
System.out.println("Matched");
break;
default:
System.out.println("Not Matched");
}
| case value: constant expression required
// jshell doesn't treat `final int val` as compiled time constant, that's why it throws an error
// but it works fine in .java file
// alternate solution for jshell
class Constants {
static final int val = 2;
}
switch (3 - 1) {
case Constants.val:
System.out.println("Matched");
break;
default:
System.out.println("Not Matched");
}
Matched
// All use cases need not be handled.
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
Day today = Day.SUNDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the workweek!");
break;
case FRIDAY:
System.out.println("End of the workweek!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend!");
break;
default:
System.out.println("Midweek day");
}
Weekend!
// Nested switch statement is allowed.
int day = 3; // Wednesday
int time = 10; // 10 AM
switch (day) {
case 3:
System.out.println("It's Wednesday.");
switch (time) {
case 9:
System.out.println("It's 9 AM");
break;
case 10:
System.out.println("It's 10 AM");
break;
case 11:
System.out.println("It's 11 AM");
break;
default:
System.out.println("Time outside range.");
}
break;
default:
System.out.println("Not Wednesday.");
}
It's Wednesday. It's 10 AM
// `return` is not possible from a switch statement
int val = 1;
String output = switch (val) {
case 1:
return "One";
};
System.out.println(output);
| return "One"; attempt to return out of a switch expression | String output = switch (val) { | case 1: | return "One"; | }; switch expression does not have any result expressions
Switch Expressions¶
🎥 Java Switch Expressions – Nagoor Babu Sir
📘 Guide to the yield Keyword in Java – Baeldung
Expression Syntax¶
type val = switch (expression) {
case value -> {
yield value;
}
case value -> return value;
default -> {
yield value;
}
};
Rules¶
- All cases must be handled, either explicitly with
case
or by adefault
block. - You cannot have a block of statements after the arrow (➝). It's a single expression per case.
- If you want to use a block of statements for a
case
and return a value, you must use theyield
keyword.
int val = 1;
String outputval = switch(val) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
default -> "None";
};
System.out.println(outputval);
One
int val = 3;
// All possible use cases must be handled for the expression.
// Adding a default case fixes this issue.
String outputval = switch(val) {
case 1 -> "One";
case 2 -> "Two";
case 3 -> "Three";
};
System.out.println(outputval);
| String outputval = switch(val) { | case 1 -> "One"; | case 2 -> "Two"; | case 3 -> "Three"; | }; the switch expression does not cover all possible input values
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
Day today = Day.FRIDAY;
String output = switch(today) {
case SUNDAY -> "Weekend";
case MONDAY -> "Workday";
case FRIDAY -> {
yield "Prayer Day";
}
default -> today.toString();
};
System.out.println(output);
Prayer Day
int val = 3;
String outputval = switch(val) {
case 1 -> {
// code
yield "One";
}
case 2 -> {
// code
yield "Two";
}
case 3 -> {
int x = 10;
int y = 20;
System.out.println(x + y);
yield "Three";
}
default -> {
// code
yield "None";
}
};
System.out.println(outputval);
30 Three
int values[] = {1, 2, 3, 4, 5};
for (int val: values) {
System.out.print(val + " ");
}
1 2 3 4 5
int values[] = new int[5];
values[0] = 1;
values[1] = 2;
values[2] = 3;
for (int val: values) {
System.out.print(val + " ");
}
1 2 3 0 0
For loop¶
for (variable; condition; increment/decrement) {
// code
}
for (int i = 1; i <= 10; i += 1) {
System.out.print(i + " ");
}
1 2 3 4 5 6 7 8 9 10
for (int x = 1; x <= 3; x++) {
for (int y = 1; y <= 3; y++) {
System.out.println("x=" + x + " : y=" + y);
}
}
x=1 : y=1 x=1 : y=2 x=1 : y=3 x=2 : y=1 x=2 : y=2 x=2 : y=3 x=3 : y=1 x=3 : y=2 x=3 : y=3
While loop¶
type var = 1;
while (condition) {
// code
var += 1;
}
int val = 5;
while (val >= 1) {
System.out.print(val + " ");
val -= 1;
}
5 4 3 2 1
Do-while loop¶
type var = 1;
do {
// code
val += 1;
} while (condittion);
int val = 5;
do {
System.out.print(val + " ");
val -= 1;
} while (val >= 1);
5 4 3 2 1
Branching Statements¶
break
statementcontinue
statement
// The break statement exits the current loop and transfers control to the next statement.
for (int x = 1; x <= 3; x++) {
for (int y = 1; y <= 3; y++) {
if (x == 2) {
break;
}
System.out.println("x=" + x + " : y=" + y);
}
}
x=1 : y=1 x=1 : y=2 x=1 : y=3 x=3 : y=1 x=3 : y=2 x=3 : y=3
for (int x = 1; x <= 3; x++) {
for (int y = 1; y <= 3; y++) {
if (x == 1) {
continue;
}
System.out.println("x=" + x + " : y=" + y);
}
}
x=2 : y=1 x=2 : y=2 x=2 : y=3 x=3 : y=1 x=3 : y=2 x=3 : y=3
// This instructs the JVM to transfer control to the end of the specified labeled loop
// rather than exiting only the innermost loop.
outerLoop: for (int x = 1; x <= 3; x++) {
innerLoop: for (int y = 1; y <= 3; y++) {
if (x == 2) {
break outerLoop;
}
System.out.println("x=" + x + " : y=" + y);
}
}
x=1 : y=1 x=1 : y=2 x=1 : y=3
Outer: for (int x = 1; x <= 3; x++) {
Inner: for (int y = 1; y <= 3; y++) {
if (x == 1) {
continue Outer;
}
System.out.println("x=" + x + " : y=" + y);
}
}
x=2 : y=1 x=2 : y=2 x=2 : y=3 x=3 : y=1 x=3 : y=2 x=3 : y=3