In Java, the Conditional Operator is a ternary operator that provides a concise way to write simple if-else statements. It is called a ternary operator because it takes three operands. The conditional operator is represented by the symbol ? :
.
Syntax
variable = (condition) ? expression1 : expression2;
true
or false
.true
.false
.public class Main {
public static void main(String[] args) {
int a = 10, b = 20;
// Using conditional operator to find the larger number
int max = (a > b) ? a : b;
System.out.println("The larger number is: " + max);
}
}
Output:
The larger number is: 20
Example 2: Using Conditional Operator for Even or Odd
public class Main {
public static void main(String[] args) {
int num = 7;
// Check if the number is even or odd using the conditional operator
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is: " + result);
}
}
Output:
The number is: Odd
if-else
statements.You can now have an idea that the conditional operator reduces the lines of code, and make our task easier. You can figure out various other use cases where you will find the conditional operator quite useful, and you cannot code without it sometimes as well. Keep researching. And if you want to learn Java in detail you can contact us any time.
Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let us have a look at what you will get with this Java training package:
You need to pay a nominal fee.
You can choose any Java certification, as per your skills and interest.
You have the option to select from online and classroom training.
A chance to study at one of the best Java training institutes in India
We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.
Naresh I technologies cater to one of the best Java training in India.
And a lot more is waiting for you.
Contact us anytime for your complete Java online training.
Concept | Description |
---|---|
Class | A blueprint for creating objects |
Object | An instance of a class |
Encapsulation | Restricting direct access to data (hiding details) |
Abstraction | Hiding implementation details and exposing only functionality |
Inheritance | Allowing a class to acquire properties/methods from another class |
Polymorphism | Using the same method name for different functionalities |
# Creating a class
class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand
self.model = model
self.year = year
def display_info(self): # Method
print(f"Car: {self.brand} {self.model} ({self.year})")
# Creating an object (instance)
my_car = Car("Tesla", "Model S", 2022)
# Calling a method
my_car.display_info() # Output: Car: Tesla Model S (2022)
Encapsulation restricts direct access to class attributes and methods.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute (__)
def deposit(self, amount):
self.__balance += amount
def get_balance(self): # Getter method
return self.__balance
# Creating an object
account = BankAccount(500)
account.deposit(200)
print(account.get_balance()) # Output: 700
# print(account.__balance) # ❌ Error: Cannot access private variable directly
Abstraction hides complex details and exposes only essential features.
from abc import ABC, abstractmethod
class Animal(ABC): # Abstract class
@abstractmethod
def sound(self):
pass
class Dog(Animal): # Concrete class
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
dog = Dog()
print(dog.sound()) # Output: Bark
Inheritance allows a class to acquire properties and methods from another class.
class Parent:
def show(self):
print("This is Parent class")
class Child(Parent): # Inheriting Parent class
def display(self):
print("This is Child class")
obj = Child()
obj.show() # Output: This is Parent class
obj.display() # Output: This is Child class
? Multiple Inheritance
class A:
def method_A(self):
print("Class A method")
class B:
def method_B(self):
print("Class B method")
class C(A, B): # Inheriting both A and B
def method_C(self):
print("Class C method")
obj = C()
obj.method_A() # Output: Class A method
obj.method_B() # Output: Class B method
? Multilevel Inheritance
class Grandparent:
def grandparent_method(self):
print("Grandparent method")
class Parent(Grandparent):
def parent_method(self):
print("Parent method")
class Child(Parent):
def child_method(self):
print("Child method")
obj = Child()
obj.grandparent_method() # Output: Grandparent method
obj.parent_method() # Output: Parent method
obj.child_method() # Output: Child method
Polymorphism allows using the same method name with different implementations.
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self): # Overriding parent method
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())
# Output:
# Bark
# Meow
Python does not support method overloading, but we can achieve it using default arguments.
class Math:
def add(self, a, b, c=0): # Overloading using default argument
return a + b + c
math_obj = Math()
print(math_obj.add(2, 3)) # Output: 5
print(math_obj.add(2, 3, 4)) # Output: 9
Python has special methods, also called dunder (double underscore) methods.
Method | Purpose |
---|---|
__init__() |
Constructor (initializes objects) |
__str__() |
Returns string representation |
__len__() |
Returns length of object |
__add__() |
Operator overloading for + |
__eq__() |
Checks equality (== ) |
Example: Operator Overloading
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
return self.pages + other.pages # Overloading + operator
book1 = Book(100)
book2 = Book(200)
print(book1 + book2) # Output: 300
✔ Class & Object - Blueprint & instance
✔ Encapsulation - Hides internal details
✔ Abstraction - Shows only essential details
✔ Inheritance - Reusability of code
✔ Polymorphism - Same method, different behaviors
✔ Magic Methods - Special dunder methods
Scope @ NareshIT:
At NareshIT’s Python application Development program you will be able to get the extensive hands-on training in front-end, middleware, and back-end technology.
It skilled you along with phase-end and capstone projects based on real business scenarios.
Here you learn the concepts from leading industry experts with content structured to ensure industrial relevance.
An end-to-end application with exciting features
Python modules are files containing Python code (functions, classes, and variables) that can be imported and reused in other programs. They help keep code organized, reusable, and efficient.
Python modules are categorized into three main types:
os
, sys
, math
, random
, datetime
, json
, etc.import math
print(math.sqrt(16)) # Output: 4.0
.py
file.# my_module.py
def greet(name):
return f"Hello, {name}!"
Import and use it in another script: