Java (Q Spider)
Java (Q Spider)
General Information
File Types
Historical Context
Compiler
Interpreter
Compilation:
javac sourcefilename.java
Execution:
java classname
Note: The class name may or may not be the same as the source filename, but the class file
should exist.
class ClassName {
// Inside class block
// Declaration statements
int variable;
ClassName() { // Constructor
}
void method() { // Method
}
// Initialization statements
static int staticVar; // Static
int nonStaticVar; // Non-static
Tokens in Java
● Definition: Smallest building blocks of any language.
● Keywords: Reserved words with specific meanings/functionality in Java (always
lowercase, 50+).
● Identifiers: Names for components in Java.
● Literals: Values assigned to variables (cannot use keywords, numbers, symbols
except _ and $, no spaces).
● Operators : Operators are symbols that perform operations .
● Separators:Separators (also known as delimiters) are symbols that are used to
separate code elements and help define the structure of Java programs.
● Comments :( ignored by computer )
Separators in Java
Separators (also known as delimiters) are symbols that are used to separate code elements
and help define the structure of Java programs. Common separators in Java include:
1. Parentheses ():
○ Used for method calls and to define precedence in expressions.
System.out.println("Hello, World!"); // method call
2. Braces {}:
○ Used to define a block of code, such as in classes, methods, and loops.
if (a > b) {
// block of code
}
3. Brackets []:
○ Used for array declarations and accessing array elements.
4. Semicolon ;:
○ Used to terminate statements.
int a = 10;
System.out.println(a);
5. Comma ,:
○ Used to separate elements in a list, such as in variable declarations and
method arguments.
int a = 10, b = 20;
6. Dot .:
○ Used to access members of classes and objects.
System.out.println("Hello, World!");
Comments in Java
Comments are used to explain code and make it more readable. They are ignored by the
compiler.
Types of Comments
1. Single-line Comments:
○ Start with // and continue to the end of the line.
// This is a single-line comment
2. Multi-line Comments:
○ Start with /* and end with */. Can span multiple lines.
/*
*/
int a = 10;
3. Documentation Comments:
○ Start with /** and end with */. Used to generate documentation using tools
like Javadoc.
/**
*/
Common Keywords
● 8 types:
○ byte (8-bit)
○ short (16-bit)
○ int (32-bit)
○ long (64-bit)
○ float (32-bit)
○ double (64-bit)
○ char (16-bit)
○ boolean (1-bit)
Value Ranges
Number Systems
● Binary: Base 2.
● Decimal: Base 10.
● Octal: Base 8.
● Hexadecimal: Base 16.
Variables in Java
● variable == container (data / literals )
● declaration == creation of memory location(SYNTAX : int a ; datatype identifier )
● all rules of identifier (snake case)
Characteristics
Types of Variables
Operators in Java:
Characteristics
Types of Operators
Based on Task
Precedence Table
Precedence Operators Associativity
Bitwise OR ` `
Logical OR `
int res = 10 + 5 * 10 - 1 / 5;
res = 10 + 50 - 0;
res = 60;
double resDouble = 10 + 5 * 10 - 1 / 5;
resDouble = 60.0;
int resComplex = 10 - 5 + 2 - 5 - 12 + 5;
resComplex = -5;
String Concatenation
Automatic Promotion
String Pool
== Operator:
● For objects: Checks the actual value (content) of the objects, provided the method is
overridden appropriately in the class
The && operator returns true if both operands are true. If the first operand is false, the
second operand is not evaluated (short-circuit evaluation).
The ! operator returns the opposite boolean value of its operand. It is a unary operator.
true false
false true
Logical OR (||)
● Purpose: Returns true if at least one of the operands is true; otherwise, returns
false.
● Short-Circuiting: If the first operand is true, the second operand is not evaluated.
● Definition: A static method defined in wrapper classes like Integer, Double, Boolean,
etc.
● Return Type: Returns an instance of the wrapper class.
● Null Handling: Can handle null input, returning a corresponding wrapper class object
with the value set to the specified string.
● Usage: Generally used for converting string representations of data into their
wrapper types.
Example:
Similar Methods:
Example:
● .valueOf() Method:
○ Converts string representations to wrapper types.
○ Returns a wrapper object.
○ Can handle null inputs.
● .parseInt() Method:
○ Converts string representations to primitive types.
○ Returns a primitive value.
○ Cannot handle null inputs.
In Java, there are several ways to convert an integer to its string representation. Here are
three common methods:
int a = 10;
a += 5; // equivalent to a = a + 5; a becomes 15
Literal Types
● Integer Literals: By default, int type.
● Decimal Literals: By default, double type.
// Case 1: Widening
byte b1 = 100;
int i1 = b1; // implicit type casting
// Case 2: Narrowing
int i2 = 100;
byte b2 = (byte) i2; // explicit type casting
Structure
int a = 5;
int b = 10;
int max = (a > b) ? a : b; // max will be 10 because a is not
greater than b
System.out.println(greatest); // Output: 30
if Statement
Syntax:
if (true) {
System.out.println("Hello");
}
if (false) {
System.out.println("Hello"); // This statement is unreachable
}
if-else Statement
Syntax:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
if-else-if Ladder
Syntax:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else if (condition3) {
// code to execute if condition3 is true
} else {
// code to execute if none of the above conditions are true
}
switch Statement
Syntax:
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// more cases
default:
// code to execute if expression doesn't match any case
}
● Notes:
○ Menu-driven programs often use switch statements.
○ Without a break, execution "falls through" to subsequent cases.
○ The default case executes if no other case matches.
○ long, double, float, and boolean can't be used in switch expressions.
○ byte, short, int, enum, char, and String can be used in switch
expressions.
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
int a = 10;
System.out.println(a++); // Output: 10 (postfix: use first, then
increment)
System.out.println(a); // Output: 11
a = 10;
System.out.println(++a); // Output: 11 (prefix: increment first,
then use)
System.out.println(a); // Output: 11
int a = 10;
a += 1; // equivalent to a = a + 1;
System.out.println(a); // Output: 11
Typecast Operator
>>Primitives
>>downcasting (1 ways )
// Widening
byte b1 = 100;
int i1 = b1; // implicit type casting
// Narrowing
int i2 = 100;
byte b2 = (byte) i2; // explicit type casting
Scanner Class
● Purpose: Parses and reads input from various sources like keyboard, files, etc.
● Common Methods:
○ next(): Finds and returns the next complete token.
○ nextLine(): Advances the scanner past the current line.
○ nextInt(): Scans the next token as an int.
○ nextDouble(): Scans the next token as a double.
○ hasNext(): Returns true if the scanner has another token.
○ hasNextLine(): Returns true if the scanner has another line.
○ useDelimiter(String pattern): Sets the scanner's delimiting pattern.
● Scanner:
○ This is the class/type we are using.
● sc:
○ This is the name of the Scanner object we are creating.
● new Scanner(System.in):
○ new is a keyword/operator that creates a new instance of the Scanner class.
○ Scanner(System.in) is the constructor call that initializes the Scanner
object to read input from the standard input stream (keyboard).
● The Scanner object accesses the buffer file in the operating system to read input.
● It converts the binary input from the keyboard (or other input sources) into high-level
language constructs that can be used in a Java program.
● contain access to the buffer file in the os which can convert the hl to ll and ll to hl
● these convert s the input of the keyboard (binary to hl language)
import java.util.Scanner;
// Reading a string
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Name: " + name);
// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Age: " + age);
// Reading a double
System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();
System.out.println("GPA: " + gpa);
scanner.close();
}
}
Purpose
● Looping statements in Java are used to repeat the execution of a block of code until
a specific condition is met or for a specified number of times.
while Loop
● Purpose: Executes a block of code repeatedly as long as a specified condition is
true.
while (condition) {
// code to execute
// increment / decrement
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
● Execution Flow: Checks the condition before entering the loop body.
do-while Loop
● Purpose: Similar to while loop but guarantees that the loop body executes at least
once.
do {
// code to execute
// increment / decrement
} while (condition);
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
● Execution Flow: Executes the loop body first, then checks the condition.
for Loop
● Purpose: Used when the number of iterations is known and finite.
Syntax:
Syntax:
Example:
Example:
● Execution Flow: Outer loop executes once for each iteration of the inner loop.
Problem Solving Techniques
METHODS :
Purpose
● Methods are blocks of code designed to perform specific tasks, automate repeated
actions, and organize code into manageable units.
● Methods store actions or behaviors, such as a login function in an application.
Key Features
● Not executed unless called: Methods must be explicitly invoked to run.
● Can return data: Methods can return values to the caller.
● Defined outside the main method: Methods are defined within a class but outside
the main method.
Syntax
Modifiers
Return Types
Method Workflow
1. Method is called.
2. Caller execution is stopped.
3. Method execution starts.
4. After performing its task, control returns to the caller with the data (if any).
Characteristics of Methods
Main Method
● Not built-in: The JVM calls the main method to start the program.
Types of Methods
1. Based on Arguments
○ No Argument: No parameters declared.
○ Parameterized: Declares formal arguments and can receive data during
execution.
○ Var Args: Allows variable number of arguments.
2. Based on Modifiers
○ Public
○ Protected
○ Static
○ Non-static
○ Final
Actual Arguments
● Actual arguments: The data passed to the method in the invocation statement.
No-Argument Method
// Invocation
greet(); // Outputs: Hello, World!
Parameterized Method
// Invocation
greet("Alice"); // Outputs: Hello, Alice!
● Return Statement Position: The return statement should be the last statement in
the method body.
● Mandatory Return Statement: If the return type of the method is anything other than
void, a return statement is mandatory.
● Void Return Type: If the return type is void, a return; statement is optional but
not mandatory.
● Type Casting: Rules of type casting also apply to return types.
Calling Static Methods from Other Classes
Class Definition:
class A {
public static void M1() {
// Method of Class A
}
}
class B {
public static void main(String[] args) {
A.M1(); // Calling method from Class A
// M1(); // This will not work as it only looks within Class
B
}
}
Syntax:
ClassName.methodName();
● java.lang Package: This package is imported by default in every Java program and
includes commonly used classes such as Math, String, Integer, etc.
System.out.println(max); // Output: 2
System.out.println(ceilValue); // Output: -1.0
System.out.println(roundedValue); // Output: 2
System.out.println(sqrtValue); // Output: 10.006168097728521
●
Example Programs
METHOD OVERLOADING:
>> declaring more than one mehod with same name but with different signature
(method overloading )
>> add(int a ,int b)
>> add(int a ,int b ,int c )
length of argument:
>> m1 (int )
>> m1 (int ,int )
>> m1 (int ,int ,int )
Arrays in Java
Definition and Characteristics
Purpose
● Store Multiple Values: Arrays are used to store multiple values of the same type
together.
● Syntax:
○ Declaration and Instantiation: datatype[] variable = new
datatype[size];
■ Example: int[] arr = new int[7];
○ Separate Declaration and Instantiation:
■ Declaration: int arr[];
■ Instantiation: arr = new int[5];
○ Initialization with Values: int[] arr = {10, 20, 30};
Array Index
Default Values
Exception Handling
Initialization Methods
Assigning Values to Indices:
Direct Initialization:
Direct Initialization:
int[] numbers = {10, 20, 30, 40, 50};
● Storing Homogeneous Data: Arrays are ideal for storing lists of items of the same
type.
● Iteration: Arrays are commonly used with loops to perform operations on each
element.
Linear Search
Definition
Characteristics
● Return Value:
○ Index of Element: Returns the index of the element if found.
○ -1 if Not Found: Returns -1 if the element is not found.
■ Reason: Indices start from 0, so -1 is used to indicate absence.
Usage
● Finding Elements: Suitable for small to moderately sized arrays where ease of
implementation is prioritized over performance.
● Performance: O(n) time complexity, where n is the number of elements in the array.
Objects in Java
Definition
● Object: A block of memory that can store heterogeneous data (properties) and
methods (behaviors) to represent a real-world entity.
Key Characteristics
Advantages
Example Code
class Student {
String name;
int age;
int rollNo;
public static void main(String[] args) {
// Step 2: Create an Object
Student s = new Student();
}
}
Key Concepts
● new Keyword:
1. Memory Allocation: Allocates memory in the heap.
2. Type Matching: Returns the same type as the class.
Variables in Java
Types of Variables:
1. Static Variables:
○ Declared with the static keyword inside a class.
○ Initialized with default values if not explicitly initialized.
○ Can be accessed using the class name.
Characteristics:
Purpose:
3. Local Variables:
○ Declared inside methods, constructors, or blocks.
○ No default value; must be initialized before use.
○ Have precedence over global variables with the same name.
1. Error:
● Errors are serious problems that a reasonable application should not try to catch.
● They typically represent fatal problems that the application cannot recover from.
● Examples include:
○ StackOverflowError: Thrown when a stack overflow occurs because an
application recurses too deeply.
○ OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) cannot
allocate an object because it is out of memory.
○ VirtualMachineError: A superclass of all the errors that occur within the
JVM.
2. Exception:
Handling Exceptions:
● Java provides the try, catch, finally, and throw keywords for handling
exceptions.
Constructor in Java
A constructor is a special method used to initialize objects in Java. It has the same name as
the class and does not have a return type. Constructors are invoked automatically when an
object is created.
Characteristics of Constructors:
Syntax
[Modifier] ClassName(arguments) {
// Constructor body
Example:
String name;
int age;
// Constructor
this.name = name;
this.age = age;
}
Types of Constructors
1. Built-In Constructor
Default Constructor:
String model;
// Default Constructor
Car() {
this.model = "Unknown";
No-Args Constructor:
String title;
// No-Args Constructor
Book() {
this.title = "Untitled";
Parameterized Constructor:
Example:
String title;
String author;
// Parameterized Constructor
this.title = title;
this.author = author;
Usage:
Notes on Constructors
● Implicit vs. Explicit Calls: While you can’t call a constructor directly, you can
instantiate an object using the new keyword, which implicitly calls the constructor.
● Constructor Overloading: Multiple constructors can be defined in a class with
different parameters.
this Keyword
Definition:
● this is a Java keyword that refers to the current object instance within a class.
● It is a non-static variable that holds a reference to the current object.
Uses of this:
1. Distinguishing Instance Variables from Local Variables:
○ this is used to differentiate between instance variables and local
variables or method parameters when they have the same name.
Example:
String title;
Book(String title) {
2. In the Book class, this.title refers to the instance variable title, while
title refers to the constructor parameter.
3. Calling Other Constructors:
○ this() can be used to call another constructor in the same class
(constructor chaining).
Example:
String title;
String author;
// No-Args Constructor
Book() {
}
// Parameterized Constructor
this.title = title;
this.author = author;
Example:
String title;
this.title = title;
Example:
String title;
void printBook(Book b) {
System.out.println(b.title);
void print() {
Constructor Overloading
Definition:
● Constructor overloading is a feature that allows a class to have more than one
constructor with different parameter lists.
● Same Name: All overloaded constructors must have the same name as the class.
● Different Signatures: Each constructor must have a different parameter list.
Conclusion
Understanding the this keyword and constructor overloading are essential for effective
object-oriented programming in Java. They help manage object state and provide flexibility
in object creation.
Constructor Chaining refers to calling one constructor from another within the same class
or from a parent class constructor. It is a technique to reuse code and manage object
initialization more effectively.
// Parameterized Constructor
Book(String title, String author) {
this.title = title;
this.author = author;
System.out.println("Title: " + title + ", Author: " +
author);
}
Output:
Title: Java Basics, Author: John Doe
Title: Unknown Title, Author: Unknown Author
String type;
1. this() Usage:
○ this() can only be used to call another constructor in the same class.
○ It must be the first line in the constructor.
○ You can only have one this() call per constructor.
○ Recursive constructor calls (where a constructor calls itself directly or
indirectly) are not allowed.
○ If you have N constructors in a class, you can only have (N-1) this() calls.
2. super() Usage:
○ super() can be used to call a constructor from the parent class.
○ It must be the first line in the constructor.
○ You can only have one super() call per constructor.
○ It initializes the parent class before the child class constructor executes.
Constructor Overloading
Constructor overloading is a concept where you have more than one constructor in a class
with different parameters. This allows you to create objects in different ways depending on
the arguments provided.
Example(int i) {
this(i, "Hello"); // Calls the constructor with two
arguments
System.out.println("Single int Constructor: " + i);
}
Example(int i, String s) {
System.out.println("Two-arg Constructor: " + i + ", " + s);
}
Output:
Conclusion
Constructor chaining is a powerful feature in Java for initializing objects. It uses this() for
constructors within the same class and super() for constructors in a parent class.
Understanding these concepts helps manage object creation and inheritance effectively.
Key Takeaways:
Purpose:
Characteristics:
● The memory of non-static methods is allocated inside the object.
● The memory for objects is stored in the heap.
● Can be accessed, used, or invoked with the help of an object reference.
● The block associated with non-static methods is called a non-static initializer.
● In a non-static context, both static and non-static members can be accessed directly
without any reference.
Static Methods
Definition:
Purpose:
Characteristics:
● Memory is allocated in the class static block, which is present inside the static area or
static pool.
● Can be accessed, used, or invoked with the help of the class name.
● Static variables can be accessed directly in the static context.
● In other classes, use the class name to access them.
● Can also be accessed with instance variables.
Initializer Blocks
Definition:
Types:
1. Static Initializer:
○ Declared inside the class block only.
○ Initialized during the class loading process.
○ Executed only once during class loading.
○ Execute in top-to-bottom order.
2. Non-Static Initializer:
○ Declared inside the class block only.
○ Executed during the object loading process.
○ Executed every time an object is created.
○ Execute in top-to-bottom order.
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Encapsulation
Definition: Encapsulation is the process of wrapping up the properties (fields) and behaviors
(methods) of an object into a single unit, or class. It hides the internal state and requires all
interaction to be performed through an object's methods.
● ATM Machine:
○ Properties: location
○ Behaviors: withdraw()
Advantages:
1. Data Hiding: Ensures that the internal representation of an object is hidden from the
outside. Only the methods of the object can be used to interact with its internal state.
This provides a controlled way of accessing and modifying the data.
2. Data Validation: Allows validation of data before it is assigned to variables, ensuring
that the object maintains a valid state.
Access Modifiers:
● Getter Method: A public method that returns the value of a private field.
● Setter Method: A public method that sets the value of a private field.
Factory Method:
● A static method that returns an instance of a class. It is often used to encapsulate the
creation logic of an object.
Example:
Inheritance
Definition: Inheritance is the mechanism by which one class (the child or subclass) inherits
the properties and behaviors (fields and methods) of another class (the parent or
superclass). This promotes code reusability and establishes a natural hierarchy between
classes.
Example:
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Child class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Purpose of Inheritance:
● Code Reusability: Methods and fields of the parent class can be reused in the child
class.
● Method Overriding: Allows a subclass to provide a specific implementation of a
method that is already defined in its superclass.
● Polymorphism: Refers to the ability to call the same method on different objects and
have each of them respond in their own way.
Polymorphism
Definition: Polymorphism means "many shapes" and allows objects to be treated as
instances of their parent class rather than their actual class. The two main types are
compile-time (method overloading) and runtime (method overriding).
Types of Polymorphism:
Method Overloading:
class MathOperation {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
Method Overriding:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Advantages:
Abstraction
Definition: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of an object. It reduces complexity and allows the
programmer to focus on interactions at a high level.
● Abstract Classes: Classes that cannot be instantiated and are declared with the
abstract keyword. They can have abstract methods (methods without a body) and
concrete methods (regular methods).
● Interfaces: A contract that classes can implement. Interfaces can have abstract
methods (implicitly public abstract) and, from Java 8 onwards, default and static
methods.
Example:
Abstract Class:
// Regular method
void sleep() {
System.out.println("This animal sleeps");
}
}
class Dog extends Animal {
// Providing implementation of the abstract method
void sound() {
System.out.println("Dog barks");
}
}
Interface:
interface Animal {
void sound(); // Abstract method
}
Advantages:
Types of Coupling
Tight Coupling
● Definition: Tight coupling occurs when classes are highly dependent on each other.
Changes in one class will often require changes in the other.
● Example: A Car class has an Engine class directly instantiated within it.
Loose Coupling
● Definition: Loose coupling occurs when classes are mostly independent and interact
with each other through well-defined interfaces or methods. Changes in one class
minimally affect others.
● Example: A Car class has an Engine class passed to it via a constructor or setter
method.
1. Purpose of super():
○ Used to call the constructor of the immediate parent class.
○ Ensures that the parent class is initialized when the child class object is
created.
2. super() Call Statement:
○ Must be the first statement inside the constructor body.
○ Can only be used within a constructor.
○ Cannot use both super() and this() inside the same constructor.
○ By default, super() is called as the first statement in a constructor if this()
is not specified.
○ For multiple constructors, each can have its own super() call.
Example:
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
Characteristics of super.field:
1. Accessibility:
○ Private members cannot be inherited.
○ Public, protected, and default members can be inherited.
2. Final Class:
○ Cannot be extended by any other class (e.g., String class in Java).
HAS-A Relationship (Composition/Aggregation)
Definition: The HAS-A relationship defines a composition or aggregation relationship
between classes. It indicates that one class contains or uses another class.
class Engine {
// Engine class implementation
}
class Car {
private Engine engine;
public Car() {
this.engine = new Engine(); // Early instantiation
}
}
class Engine {
// Engine class implementation
}
class Car {
private Engine engine;
1. Early Instantiation:
○ Achieved with initializers.
○ The dependent object is created during the construction of the depending
object.
2. Lazy Instantiation:
○ Achieved with helper methods.
○ The dependent object is created later when needed.
Conclusion
IS-A Relationship:
● Purpose of super():
○ The super() call is used to invoke the constructor of the immediate parent
class.
○ Ensures that the parent class is properly initialized when the child class is
created.
● Usage:
○ super() must be the first statement inside the constructor body.
○ It can only be used within the constructor body.
○ You cannot use both super() and this() in a single constructor body.
○ By default, if no constructor call is specified, super() is the implicit first
statement in a constructor.
○ For classes with multiple constructors, each constructor can have its own
super() call.
1. First Statement: Must be the first statement inside the constructor body.
2. Constructor Body: Can only be used inside the constructor body.
3. Mutual Exclusivity: Cannot use both super() and this() inside the same
constructor.
4. Default Call: By default, super() is the first statement unless this() is specified.
5. Multiple Constructors: For classes with multiple constructors, each can include a
super() call.
Example:
java
Copy code
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
● super Keyword:
○ super is used to eliminate ambiguity between superclass and subclass
variables and methods.
○ It is a non-static variable that can only be used in a non-static context.
○ Allows access to the properties and behaviors of the parent class from the
child class.
void display() {
System.out.println("Parent display");
}
}
void display() {
super.display(); // Calls the parent class method
System.out.println("Child display");
}
void showValues() {
System.out.println("Parent value: " + super.value); //
Accesses the parent class field
System.out.println("Child value: " + this.value);
}
}
● Purpose: When a method is overridden in a subclass, you can use super to invoke
the version of that method from the superclass. This is useful when you want to
access or extend the functionality of the superclass's method while still benefiting
from the overridden version in the subclass.
● Syntax: super.methodName(parameters);
Summary
4o