Java Mod 1
Java Mod 1
Module 1
How to Run:
1. Save the file as HelloWorld.java.
2. Open a terminal/command prompt.
3. Compile using:
javac HelloWorld.java
4. Run the program:
java HelloWorld
ava Compiler and Java Virtual Machine (JVM)
Java uses a two-step process to run programs:
Step 1: Java Compiler (javac)
The Java compiler is a program that:
Converts Java source code (.java file) into bytecode (.class file).
Bytecode is an intermediate, platform-independent code.
Example:
When you write:
javac HelloWorld.java
This creates a file called HelloWorld.class — which contains bytecode.
java HelloWorld
The JVM runs the bytecode and produces the output:
Hello, World!
java (JVM) Executes the bytecode on your machine Program output on console
Summary
Java Compiler (javac) ➜ Converts .java to .class (bytecode).
Command Description
IDE Features
Key Features:
Syntax highlighting
Code completion (auto-suggest)
Real-time error checking
Graphical debugging tools
Project management and build tools
Pros:
Boosts productivity
Easier debugging
Integrated GUI builders for apps
Cons:
Heavier than command-line tools
May hide internal compilation steps from learners
Summary
Best For Learning basics, scripting Large projects, GUI apps, debugging
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Example Code
public class WrapperExample {
public static void main(String[] args) {
int num = 5; // primitive
Integer obj = num; // autoboxing
int num2 = obj; // unboxing
Type Casting
Type Casting in Java is the process of converting a value from one data type to another.
Java has two types of type casting:
1. Widening (Implicit) Casting – small → large type
2. Narrowing (Explicit) Casting – large → small type
int n = 66;
char ch = (char) n; // int → char (narrowing)
System.out.println("Character of 66 is: " + ch);
}
}
Java Operators
In Java, operators are special symbols used to perform operations on variables and values. They
are grouped into several categories:
1. Arithmetic Operators
Used for basic mathematical operations.
+ Addition a+b 15
- Subtraction a-b 5
Operator Description Example (a = 10, b = 5) Result
* Multiplication a*b 50
/ Division a/b 2
== Equal to a == b false
&& Logical AND True if both conditions are true (a > 0 && b > 0) → true
! Logical NOT Reverses the boolean result !(a > b) → true if a < b
Unsigned right
>>> Same as >> but fills left with 0 a >>> 1
shift
5. Assignment Operators
Used to assign values or update a variable using an operation.
= a=b Assign b to a
+= a += b a=a+b
-= a -= b a=a-b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b
` =` `a
^= a ^= b a=a^b
Operator Example Meaning
6. Unary Operators
Operate on a single operand.
+ Unary plus +a
- Unary minus -a
~ Bitwise NOT ~a
7. Ternary Operator
A short-hand for if-else.
int max = (a > b) ? a : b;
This means:
If a > b → max = a, else → max = b.
[] Array access
() Method call
// Arithmetic
System.out.println("Addition: " + (a + b));
// Relational
System.out.println("a > b: " + (a > b));
// Logical
System.out.println("Logical OR: " + (a > 0 || b < 0));
// Bitwise
System.out.println("Bitwise OR: " + (a | b));
System.out.println("Bitwise XOR: " + (a ^ b));
// Assignment
a += 3;
System.out.println("After a += 3: " + a);
// Ternary
int max = (a > b) ? a : b;
System.out.println("Max = " + max);
}
}
[], ., obj.method(), a[i], x.y Array/member access, method call Left to right
10 ` ` Bitwise OR
12 ` `
14 =, +=, -=, *=, /=, %= Assignment and compound assignment Right to left
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is Even.");
else
System.out.println(num + " is Odd.");
}
}
import java.util.Scanner;
import java.util.Scanner;
while (num != 0) {
sum += num % 10;
num /= 10;
}
import java.util.Scanner;
if (num <= 1)
isPrime = false;
else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number.");
else
System.out.println(num + " is Not a Prime Number.");
}
}
Example Programs using Control statements in Java
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is Even.");
else
System.out.println(num + " is Odd.");
}
}
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
while (num != 0) {
sum += num % 10;
num /= 10;
}
import java.util.Scanner;
if (num <= 1)
isPrime = false;
else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number.");
else
System.out.println(num + " is Not a Prime Number.");
}
}
Functions in Java
In Java, functions (more correctly called methods) are blocks of code that perform a specific
task. They help in code reusability, modularity, and readability.
Syntax of a Method
Component Description
Key Concepts
1. Base Case – condition to stop recursion
2. Recursive Case – where the method calls itself
Recursion breaks the problem into smaller subproblems until the base case is reached.
Factorial of 5 is 120
Example 2: Fibonacci Series
Problem: Print nth Fibonacci number
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, ...
Fibonacci(7) = 13
Sum of digits = 10
Caution:
Recursive functions may cause StackOverflowError if the base case is missing or
recursion is too deep.
Use iteration for efficiency when possible.
javac CommandLineExample.java
java CommandLineExample Hello World 123
Output:
methodName(datatype... varname)
Treated as an array inside the method.
Only one vararg is allowed per method, and it must be last in the parameter list.
Source of data From user via terminal/command From method call inside program
class ClassName {
// Fields (variables)
// Methods (functions)
}
// Define a class
class Student {
// Fields (data members)
String name;
int age;
// Method (behavior)
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of Student class
Student s1 = new Student();
// Set values
s1.name = "Anjali";
s1.age = 20;
// Call method
s1.displayDetails();
}
}
Output:
Name: Anjali
Age: 20
Key Terminologies
Term Description
Constructor in Java
A constructor is a special method that is automatically called when an object is created.
🔹 Example:
class Student {
String name;
int age;
// Constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
(default)* ✅ ✅ ❌ ❌
Modifier Class Package Subclass World
private ✅ ❌ ❌ ❌
*default (no modifier) means package-private — accessible only within the same package.
class MyClass {
private int secret = 123;
class MyClass {
void defaultMethod() {
System.out.println("Package-private method");
}
}
class Student {
String name;
// Constructor
Student(String name) {
this.name = name; // this.name refers to instance variable
}
void printName() {
System.out.println("Name: " + this.name);
}
}
class Book {
String title;
int pages;
void display() {
System.out.println(title + " - " + pages + " pages");
}
}
class Demo {
Demo getObject() {
return this;
}
}
Data Abstraction
Data Abstraction is the process of hiding internal implementation details and showing only
the essential features of an object.
Purpose:
To reduce complexity.
To focus only on what an object does rather than how it does it.
class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound(); // Output: Barks
}
}
Explanation:
Animal is an abstract class.
makeSound() is an abstract method: only its signature is visible.
The actual implementation is hidden in the subclass (Dog).
The user (main program) only cares about the method being called, not its internal logic.
Technique Description
Abstract
Contains abstract methods that subclasses must implement.
Class
Define what a class must do but not how. (All methods are implicitly
Interfaces
abstract unless using default/static.)
Encapsulation
Encapsulation is the concept of binding data and methods that operate on that data into a
single unit (class) and restricting direct access to some of the object's components.
Purpose:
To protect data from unauthorized access.
To allow controlled access through getters and setters.
Example of Encapsulation:
class BankAccount {
private double balance; // private field (cannot be accessed directly)
// Constructor
BankAccount(double initialBalance) {
balance = initialBalance;
}
// Getter
public double getBalance() {
return balance;
}
Real-world Analogy
Using a TV remote – you press buttons (what it does), but don’t know
Abstraction
how circuits inside work.
A capsule (medicine) – the ingredients (data) are hidden inside, but you
Encapsulation
consume it as a whole.
Summary
Abstraction = Hiding internal implementation and showing only essential behavior.
Encapsulation = Hiding internal data and providing controlled access through methods.
INHERITANCE in Java
Definition:
Inheritance is the mechanism in Java by which one class acquires the properties and
behaviors (fields and methods) of another class.
The class that inherits is called the subclass (or child class).
The class from which it inherits is the superclass (or parent class).
Syntax:
class SuperClass {
// fields and methods
}
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Hierarchical Yes A → B, A → C
POLYMORPHISM in Java
Definition:
Polymorphism means “many forms”. In Java, it allows objects to behave differently based on
the context, even if they share the same interface or method name.
There are two types:
class Calculator {
int add(int a, int b) {
return a + b;
}
Meaning Reuse code from parent class Same method behaves differently
Real-World Analogy
Concept Example
Inheritance A car is a type of vehicle — it inherits basic features like wheels, engine.
A remote control works for TV, AC, or fan — the button is the same,
Polymorphism
but the result differs.
Summary
Inheritance:
Enables code reuse.
Subclass inherits fields and methods from the superclass.
Polymorphism:
Enables flexibility.
Same method name can behave differently (overloading/overriding).