JAVA MATERIAL
JAVA MATERIAL
So, the process is: Write > Compile > Translate > Run.
What is the difference between Compiler
and Interpreter?
A compiler and an interpreter both convert code into something a computer can
understand, but they do it differently:
● Compiler: It translates the entire program at once into machine code before
running it. This makes running faster, but you have to fix all errors first.
○ Example: C++ uses a compiler.
● Interpreter: It translates and runs the code line by line. This makes it easier to fix
errors as you go, but it runs slower.
○ Example: Python uses an interpreter.
So, compiler = translate all at once, interpreter = translate one line at a time.
What is the meaning of WORD LENGTH in
Computers?
Word length in computers refers to the number of bits (binary digits) that a computer
can process at one time. It defines how much data the CPU can handle in a single
operation.
For example:
● A computer with a 16-bit word length can process 16 bits of data at once.
● A computer with a 32-bit word length can process 32 bits.
Java Architecture
Java architecture is designed to provide platform independence and efficiency. It consists of
several key components:
1. Java Development Kit (JDK): This is the tool you use to write Java programs. It
includes a compiler, libraries, and tools needed for development.
2. Java Runtime Environment (JRE): This is what you need to run Java programs. It
contains the Java Virtual Machine (JVM) and the libraries required for executing Java
applications.
3. Java Virtual Machine (JVM): The heart of Java architecture. It takes Java bytecode
(compiled Java code) and translates it into machine code that the computer's
processor can execute. The JVM allows Java programs to run on any device that has a
JRE, making Java platform-independent.
How It Works:
● Write Code: You write Java code using the JDK.
● Compile Code: The JDK compiles the code into bytecode using the Java
compiler.
● Run Code: The JVM reads and executes the bytecode on any platform with a
JRE.
So, the flow is: JDK (Write) → Compiler (Compile) → Bytecode → JVM (Run).
This architecture makes Java versatile and allows it to run on different devices
without modification.
How java is Platform Independent language?
A platform-independent language is one that can run on any operating system
or device without needing modification. This means you can write code on one
system, and it will work on others without changes.
Java Virtual Machine (JVM): The JVM is available for various platforms
(Windows, Mac, Linux, etc.). It takes the bytecode and translates it into machine
code specific to the underlying hardware when you run the program.
So, Java is platform-independent because it uses bytecode and the JVM,
allowing the same Java program to run on any device that supports Java,
regardless of the operating system.
Is Java a compiled or interpreted language,
and how does its architecture support both?
Java is both a compiled and an interpreted language. Here’s how it works:
1. Compilation:
● Source Code to Bytecode: When you write Java code, it is compiled by the Java
compiler (javac) into an intermediate form called bytecode. This bytecode is not
machine-specific and can run on any platform that has a Java Virtual Machine (JVM).
2. Interpretation:
● Bytecode Execution: When you run a Java program, the JVM interprets the bytecode.
It can either interpret the bytecode line by line or use the Just-In-Time (JIT) compiler
to compile frequently executed bytecode into native machine code at runtime.
JIT (Just in Time) Compiler
JIT stands for Just-In-Time Compiler. It is a part of the Java Virtual Machine
(JVM) that improves the performance of Java applications by compiling
bytecode into native machine code at runtime.
JIT Compiler: Compiles bytecode into machine code for faster execution.
2. static:
● This keyword means that the main method belongs to the class itself, not to any specific
instance of the class. You can call this method without creating an object of the class.
The JVM needs to call main before any objects are created.
3. void:
● This indicates the return type of the method. void means that the main method does
not return any value. It simply executes the code inside it.
4. main:
● This is the name of the method. The JVM looks for this specific method name as the
starting point for executing a Java application. It is a standard convention.
5. String args[]:
● This part defines the parameter for the main method allowing the program to accept
command-line arguments. When you run a Java program, you can pass arguments to
it, which can be accessed through this array.
Summary:
Putting it all together, public static void main(String args[]) is a public method that:
int 4 bytes
long 8 bytes
float 4 bytes
Double 8 bytes
boolean 1 byte
char 2 bytes
Type Casting
Widening Casting
Byte -> short -> char -> int -> long -> float -> double
*Automatic
int num1 = 9;
double num2 = num1;
Type Casting
Narrowing Casting
Double -> float -> long -> int -> char -> short -> Byte
*Manual
*Manual
double num1 = 9.8d;
int num2 = (int) num1;
What is a Wrapper Class?
A wrapper class in Java is a class that encapsulates (or "wraps") a primitive data type in an
object.
Wrapper classes can be used in Java's collection framework (like ArrayList, HashMap),
which requires objects.
Example:
int num = 10; // Primitive type
Integer wrappedNum = Integer.valueOf(num); // Wrapper class
Difference between print, println
& printf
1. print():
● Usage: Outputs text to the console without adding a newline character at the end.
(cursor remains in the same line)
Example:
System.out.print("Hello");
System.out.print(" World");
● Usage: Outputs text to the console and adds a newline character at the end, moving the cursor to the
next line.
Example:
System.out.println("Hello");
System.out.println("World");
Output:
Hello
World
3. printf():
● Usage: Outputs formatted text. It allows you to specify the format of the output using format specifiers
(like %d for integers, %s for strings, etc.). Unlike print and println, printf does not automatically
add a newline at the end unless specified.
Example:
System.out.printf("Hello %s, your score is %d%n", "Alice", 90);
Syntax:
Example:
Syntax:
while (condition) {
// Statements to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println("Iteration: " + i);
i++;
}
Do-while loop
The do-while loop is similar to the while loop, but it guarantees that the block of statements
will be executed at least once, even if the condition is false.
Syntax:
do {
// Statements to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println("Iteration: " + i);
i++;
} while (i < 5);
Patterns
Solid Rectangle
*****
*****
*****
*****
for (int row = 0; row < 4; row++) { // Loop for 4 rows
for (int col = 0; col < 5; col++) { // Loop for 5 stars in each row
System.out.print("* "); // Draw a star
}
System.out.println(); // Move to the next line after each row
}
Hollow Rectangle
*****
* *
* *
*****
for (int i = 1; i <= 4; i++) { // Loop through rows
for (int j = 1; j <= 5; j++) { // Loop through columns
// print star only when following condition is met
if (i == 1 || i == 4 || j == 1 || j == 5) {
System.out.print("*"); // Print a star
} else {
System.out.print(" "); // Print a space
}
}
System.out.println(); // Move to the next line after
each row
}
Half Pyramid
*
**
***
****
*****
for(int i=1; i<=4; i++){
for(int j=1; j<=i; j++){
System.out.print(“*”);
}
System.out.println();
}
Half Pyramid
*
**
***
****
*****
for(int i=1; i<=4; i++){
for(int j=1; j<= n-i; j++){
System.out.print(“ ”);
}
for(int j=1; j<= i; j++){
System.out.print(“*”);
}
System.out.println();
}
Buttery Pattern
* *
** **
*** ***
********
********
*** ***
** **
* *
//upper half
for(int i=1; i<=4; i++){
for(int j=1; j<= i; j++){
System.out.print(“x”);
}
int spaces = 2*(n-i);
for(int j=1; j<= spaces; j++){
System.out.print(“ ”);
}
for(int j=1; j<= i; j++){
System.out.print(“x”);
}
System.out.println();
}
//upper half
for(int i=4; i>=1; i--){
//same code as the above
}
Functions
return_type function_name(arguments)
{
//operations or logic
}
WAP to print first n natural numbers
import java.util.Scanner;
Initialization
arrayname[index] = value;
int marks[] = {40, 55, 63, 17, 22, 68, 89, 97, 89}
Default values in an Array in Java are
int Type - 0
float type - 0.0
String type - “ ”
Size of an array:
arrayname.length;
Sort an array:
Arrays.sort(arrayname);
Eg. Arrays.sort(marks);
2D Arrays:
}
}
WAP to find maximum and minimum in an
Array
// Initialize max and min with the first element of the array
int max = array[0];
int min = array[0];
System.out.println("Duplicate elements:");
Declaration
String strname = "value";
Concatenation
String firstName = “Akash”;
String lastname = “Patil”;
Length of String
Char at index
char chr = str.charAt(index);
Declaration
Char at index
char chr = sb.charAt(index);
Insert function
strname.insert(index, 'char');
strname.delete(beg_idx, end_idx);
Eg: sb.delete(2,3);
Append Function
strname.append("value");
Eg: sb.append("y");
WAP to count the occurrence of a given
character in a string?
String str = "programming";
char ch = 'm';
int count = 0;
if(name.equals(revname))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
Sorting
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in the wrong order.
It compares the adjacent elements and shifts the largest element in the last
position of the array
It sorts an array by repeatedly selecting the smallest element from the unsorted
portion and swapping it with the first unsorted element
It finds the smaller element and swaps it with the front most element
Insertion sort is a simple sorting algorithm that works by iteratively inserting each
element of an unsorted list into its correct position in a sorted portion of the list.
Each element in the unsorted part is compared with each element in the sorted
part and place in its right position by shifting the sorted elements.
// Method (behavior)
public void write() {
System.out.println("Writing something...");
}
new keyword:
The new keyword is used to create an instance (object) of a class. It
allocates memory for the object on the heap and returns a reference to it.
Constructor
A constructor is a special method used to initialize objects. It is called when an
object is created. Constructors can also initialize object attributes with values.
Types of Constructors
1. Default Constructor:
A constructor with no parameters. It initializes the object with default values.
2. Parameterized Constructor:
A constructor with parameters, used to initialize objects with specific values.
3. Copy Constructor:
A constructor that takes another object of the same class as a parameter and
copies its values.
Properties of Constructors
Garbage Collection
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Polymorphism
● Polymorphism: The word "poly" means many, and "morphism" means forms.
Polymorphism allows a single action to be performed in different ways.
○ It enables a single interface to have multiple implementations.
○ Polymorphism allows methods or objects to take on many forms.
Types of Polymorphism
● Method overloading occurs when multiple methods have the same name but
differ in parameters (number or type of arguments).
● These methods are said to be "overloaded."
Method Overriding:
● When a subclass has a method with the same signature (same name, return
type, and parameters) as a method in its parent class, it overrides the
method from the parent class.
● Run-time polymorphism enables dynamic method dispatch, where the
method to be executed is determined at runtime based on the object’s type.
class Animal {
public void sound() {
System.out.println("The animal makes a sound");
}
}
1. Code Reusability: You can reuse the fields and methods of an existing class
without writing them again.
2. Method Overriding: You can modify or override the parent class methods in
the child class to provide specific implementations.
// Parent class
class Animal {
String name;
3. Protected:
● Scope: The protected modifier allows access within the same package and by
subclasses (through inheritance) even if they are in different packages.
● Cannot be accessed from outside the package unless it's through a subclass.
4. Public:
By bundling these components, encapsulation allows for data hiding, meaning the
internal details of an object are protected from unauthorized access and modification by
external classes.
1. Data Hiding: The internal state of the object is hidden from the outside world, and
only specific methods can access or modify the data.
2. Control over Data: Encapsulation allows control over how data is accessed or
modified by using getters and setters.
3. Achieved through Classes: Encapsulation is implemented through classes in
Java, where private variables are defined and accessed through public methods.
Abstraction
Abstraction is the process of hiding the implementation details and exposing only
the functionality to the user. It focuses on what an object can do rather than how it
does it.
1. Abstract Classes
2. Interfaces
Abstract Class in Java
Note: Using abstract classes, we cannot achieve 100% abstraction, as they can
contain non-abstract methods. For full abstraction, interfaces are used.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void sound();
// Interface 2
interface Pet {
void play();
}
Key Points:
1. static Variables:
○ A static variable is shared across all instances of the class.
○ It gets memory only once when the class is loaded.
○ It is often used for common properties like a college name for all students.
2. static Methods:
○ A static method belongs to the class and can be called without creating an
object of the class.
○ It can access only static variables and cannot directly refer to instance
variables (non-static).