java note
java note
public void displayDetails() { public class Main { public static void main(String[] args) {
System.out.println("Vehicle Name: " + name); Calculator calc = new Calculator();
System.out.println("Number of Wheels: " + wheels);
} // Calling different overloaded methods
} System.out.println("Sum of two integers: " + calc.add(5,
10));
public class Main { public static void main(String[] args) { System.out.println("Sum of three integers: " + calc.add(5,
Vehicle v1 = new Vehicle(); // Calls default constructor Vehicle v2 = new 10, 15));
Vehicle("Car"); // Calls constructor with one parameter System.out.println("Sum of two doubles: " + calc.add(5.5,
Vehicle v3 = new Vehicle("Bike", 2); // Calls constructor with two parameters 10.5));
}
v1.displayDetails(); v2.displayDetails(); v3.displayDetails(); }
}
} Explanation:
• The add() method is overloaded with different parameter combinations: two
integers, three integers, and two doubles. The correct method is invoked based on the
arguments passed.
Answer: Object-Oriented Programming (OOP): OOP is a programming paradigm Answer: An interface in Java is a reference type, similar to a class, that can contain
based on the concept of objects. An object represents a real-world entity, only constants, method signatures, default methods, static methods, and nested types.
encapsulating data (attributes) and behavior (methods). Key OOP concepts include: Interfaces cannot contain instance fields or constructors. A class implements an
• Encapsulation: Bundling data and methods together, restricting interface by providing implementations for all its methods.
access to certain components and ensuring that data is only modified Interfaces are used to define a contract for what a class can do, without specifying how
through predefined functions. it does it. A class that implements an interface must provide concrete implementations
for the methods declared in the interface.
• Inheritance: Creating a new class from an existing class, Example Program:
promoting code reuse. java Copy code interface Animal { void sound(); // Abstract method
• Polymorphism: Allowing a method to perform different }
functions based on the object that calls it, enhancing flexibility.
• Abstraction: Hiding complex implementation details and
class Dog implements Animal { public void sound() {
System.out.println("Bark");
showing only the necessary features.
}
Procedure-Oriented Programming (POP): POP is a programming paradigm that relies
}
on functions or procedures to perform operations. The focus is on writing sequences
of instructions to perform tasks, not on representing entities. POP is typically less
class Cat implements Animal { public void sound() {
modular and more difficult to manage for larger codebases compared to OOP.
System.out.println("Meow");
Differences:
}
• Focus: OOP focuses on objects; POP focuses on functions. }
• Modularity: OOP promotes code modularity and reusability;
POP is less modular. public class InterfaceExample {
public static void main(String[] args) {
• Security: OOP has better data protection through Animal dog = new Dog();
encapsulation; POP allows unrestricted access to data. Animal cat = new Cat();
• Example Languages: OOP includes Java, C++, and Python; POP
includes C and Fortran. dog.sound(); // Calls Dog's implementation of sound cat.sound(); // Calls Cat's
implementation of sound
}
}
Explanation:
• The Animal interface defines an abstract method sound(). Both Dog and Cat classes
implement this interface and provide their own implementation of the sound()
method.
Answer: Exception handling in Java is a mechanism that handles runtime errors, ensuring In Java, literals are fixed values that are directly assigned to variables or used in
that the normal flow of execution is not disrupted. Java provides a powerful model for expressions. There are several types of literals:
exception handling using the try, catch, throw, and finally blocks. 1. Integer Literals: Represent whole numbers and can be
Key Components: written in decimal, octal, hexadecimal, or binary formats.
• try block: Code that might throw an exception is placed inside the Example: int decimal = 100;, int hex = 0x1A;
try block. 2. Floating-Point Literals: Represent decimal values with
• catch block: If an exception occurs, the catch block is executed. It fractional parts and are written as float or double.
specifies the type of exception to catch. Example: double pi = 3.14;, float price = 5.99f;
• throw statement: This is used to explicitly throw an exception. 3. Character Literals: Represent a single character enclosed in
• finally block: This block is always executed, regardless of whether
single quotes.
Example: char letter = 'A';
an exception occurred or not. It is commonly used for clean-up operations like
closing files or releasing resources. 4. String Literals: Represent sequences of characters enclosed
Syntax: in double quotes.
java Copy code try { Example: String greeting = "Hello, World!";
// Code that may throw an exception 5. Boolean Literals: Represent true or false values.
} catch (ExceptionType e) { Example: boolean isJavaFun = true;
// Handling the exception
} finally { 6. Null Literal: Represents a null reference, which points to no
// Code that will run no matter what object.
} Example: String str = null;
Example code with different literals:
Example Program: public class LiteralsExample {
java Copy code public static void main(String[] args) { int decimal = 100; // integer literal
public class ExceptionHandlingExample { public static void main(String[] args) { try { double price = 99.99; // floating-point literal char letter = 'A'; // character
int result = 10 / 0; // This will throw literal
ArithmeticException String message = "Welcome to Java!"; // string literal boolean isTrue =
} catch (ArithmeticException e) { true; // boolean literal
System.out.println("Error: Division by zero");
} finally { System.out.println("Decimal: " + decimal);
System.out.println("This block is always executed"); System.out.println("Price: " + price);
} System.out.println("Letter: " + letter);
System.out.println("Message: " + message);
try { int[] numbers = new int[2]; numbers[5] = 10; // This will throw System.out.println("Boolean value: " + isTrue);
ArrayIndexOutOfBoundsException }
} catch (ArrayIndexOutOfBoundsException e) { }
System.out.println("Error: Array index out of bounds");
} finally {
System.out.println("This block is also always executed");
}
}
}
Answer: Java provides several built-in methods for manipulating strings. Strings in Java are Answer: In Java Swing, JLabel and JButton are used for building Graphical User
objects of the String class, and these methods allow you to perform common operations Interface (GUI) components.
like comparison, modification, and transformation. • JLabel: It is used to display a short string or an image. It
Common String Methods: doesn't interact with the user but simply provides information or
• length(): Returns the length of the string. displays content. It is a non-editable component.
• charAt(int index): Returns the character at the specified index. • JButton: It is a push button that can be clicked to perform
• substring(int beginIndex, int endIndex): Returns a substring from an action. When the user clicks on it, an event is triggered, and an
the string. action listener can respond to this event.
These components are often used together to create interactive applications. For
• toLowerCase(): Converts the string to lowercase. example, a JLabel can be used to display instructions or messages, and a JButton
• toUpperCase(): Converts the string to uppercase. can be used to trigger actions when clicked, such as submitting a form or closing a
• trim(): Removes leading and trailing spaces.
window. Example Program:
java Copy code import javax.swing.*; import java.awt.*; import java.awt.event.*;
• equals(String anotherString): Compares two strings for equality.
• contains(CharSequence sequence): Checks if the string contains a public class ButtonLabelExample {
specified sequence. public static void main(String[] args) {
// Create a frame
• replace(CharSequence oldChar, CharSequence newChar): Replaces JFrame frame = new JFrame("JLabel and JButton Example");
occurrences of a character or sequence with another. // Create a JLabel
Example Program: JLabel label = new JLabel("Click the button to change the text!");
java Copy code // Create a JButton
public class StringManipulation { public static void main(String[] args) { JButton button = new JButton("Click Me");
String str = " Hello, Java World! "; // Add an ActionListener to the button button.addActionListener(new
ActionListener() { public void actionPerformed(ActionEvent e) {
System.out.println("Length of string: " + str.length()); label.setText("Text has been changed!");
System.out.println("Character at index 6: " + str.charAt(6)); } });
System.out.println("Substring (7, 11): " + str.substring(7, // Set layout manager
11)); frame.setLayout(new FlowLayout());
System.out.println("Lowercase: " + str.toLowerCase()); // Add components to the frame frame.add(label);
System.out.println("Uppercase: " + str.toUpperCase()); frame.add(button);
System.out.println("Trimmed string: '" + str.trim() + "'"); // Set frame size and visibility frame.setSize(300, 200);
System.out.println("String contains 'Java': " + str.contains("Java")); frame.setVisible(true);
System.out.println("Replace 'Java' with 'Python': " + str.replace("Java", "Python")); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} }}
} • A JLabel is used to display initial text, and a JButton is created to change the
label text when clicked. The event handling mechanism is used to trigger the
action.