java unit 1
java unit 1
1. Introduction to Java
Java is a high-level, class-based, object-oriented programming
language developed by James Gosling in 1991 at Sun Microsystems
(later acquired by Oracle Corporation). It was officially released in 1995.
Desktop Applications
Web Applications
Mobile Applications
Enterprise Applications
Smart Cards
Embedded Systems
Games
Robotics
Java Specifications:
Process:
1. Java source code (.java) is compiled by javac into
bytecode (.class).
2. This bytecode is then platform-independent and can
be verified and executed by the JVM on any operating
system.
"If I just want to run any Java program on my laptop, I will only
install JRE."
System.out.println("Hello World");
void: A return type indicating that "the method will not return
anything."
main: The method name and the starting point of any Java
program, recognized by the JVM.
String[] args: Command-line arguments, which are an array of
String objects used to hold command-line arguments.
"Class does not take any memory or space." It's a logical entity.
Object:
"Object is an instance of a class."
6. Constructors
A special member function used to initialize objects within a
class.
Return Type: "It should not have any return type (it is void)."
Types of Constructors:
7. Methods
"A method is a block of code which only runs when it is called."
(Similar to functions in C/C++).
8. Access Modifiers
Access modifiers "specify the accessibility or scope of fields, methods,
constructors, or classes." They control how elements can be accessed
from different parts of a program.
"You can access this member without creating an object of the class
".
Final Members:
10. Comments
"A part of the code that the compiler and interpreter do not
execute."
Types:
12. Variables
Assigned a data type that dictates the type and quantity of value it
can hold.
1. Types of Operators:
Syntax:
if (condition) {
// Code to execute if the condition is true
}
.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
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
}
// ... more else if conditions
else {
// Code to execute if none of the above conditions are true}
Syntax:
if (outerCondition) {
// Code to execute if outerCondition is true
if (nestedCondition) {
// Code to execute if both outerCondition and
nestedCondition are true
} else {
// Code to execute if outerCondition is true, but
nestedCondition is false
}
} else {
// Code to execute if outerCondition is false
}
Switch Statement: "Similar to if-else if statement" but uses
case blocks.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
// ... more cases
default:
// code
}
o Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
o Example:
public class DoWhileExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 5);
System.out.println("Loop finished.");
}
}
o Usage:
1. Exiting Loops: It's commonly used within loops when a specific
condition is met, and you want to stop the loop's execution
prematurely.
o Example
o Example :
public class SkipEvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
// Check if the number is even
if (i % 2 == 0) {
// If it's even, skip the rest of this iteration
continue;
}
// If it's not even, print the number
System.out.println(i);
}
}
}
15. Arrays
An object in Java that represents a "sequence of character values."
Types:
Declaration:dataType[] arrayName;
dataType arrayName[];
dataType [] arrayName;
o Example :
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};
// Access and print an element at a specific index
System.out.println("Element at index 2: " + numbers[2]); //
Outputs: Element at index 2: 30
// Modify an element at a specific index
numbers[2] = 35; // Changes the 3rd element to 35
System.out.println("Modified element at index 2: " +
numbers[2]); // Outputs: Modified element at index 2: 35
16. Strings
In Java, a String is an object that represents a "sequence of
character values."
You can create String objects using the new operator and
the String class constructor.
new Keyword: String s = new String("Welcome"); (Creates a new
object in heap memory).
1. Inheritance:
"An important pillar of OOPs."
o Example:
// Base class (Superclass for Single and Hierarchical Inheritance)
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
// Single Inheritance
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
// Multilevel Inheritance
class SportsCar extends Car {
void boost() {
System.out.println("Sports car boosting performance");
}
}
// Hierarchical Inheritance
class Bus extends Vehicle {
void carryPassengers() {
System.out.println("Bus is carrying passengers");
}
}
interface Rechargeable {
void recharge();
}
@Override
public void charge() {
System.out.println("Electric car charging");
}
@Override
public void recharge() {
System.out.println("Electric car recharging battery");
}
// Single Inheritance
Car myCar = new Car();
myCar.start(); // Inherited from Vehicle
myCar.drive(); // Defined in Car
// Multilevel Inheritance
SportsCar mySportsCar = new SportsCar();
mySportsCar.start(); // Inherited from Vehicle
mySportsCar.drive(); // Inherited from Car
mySportsCar.boost(); // Defined in SportsCar
System.out.println();
// Hierarchical Inheritance
Bus myBus = new Bus();
myBus.start(); // Inherited from Vehicle
myBus.carryPassengers(); // Defined in Bus
System.out.println();
// Hybrid Inheritance
ElectricCar myElectricCar = new ElectricCar();
myElectricCar.start(); // Inherited from Vehicle
myElectricCar.drive(); // Overridden in ElectricCar
myElectricCar.boost(); // Inherited from SportsCar
myElectricCar.charge(); // Implemented from Electric
interface
myElectricCar.recharge(); // Implemented from Rechargeable
interface
}
}
1. Polymorphism:
Derived from "Poly" (many) and "Morphism" (forms). Meaning:
"having many forms."
Types:
o Example :
// Example for Compile-Time Polymorphism (Method Overloading)
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal making a generic sound..."); //
Default behavior
}
}
// Subclass 1
class Dog extends Animal {
@Override // Annotation indicating method overriding
void makeSound() {
System.out.println("Dog barking: Woof!"); // Specific
behavior for Dog
}
}
// Subclass 2
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meowing: Meow!"); // Specific
behavior for Cat
}
}
1. Encapsulation:
1. Abstraction:
Analogy: Using an ATM – you know how to withdraw money, but not
the internal processes. Driving a car – you know how to drive, but
not the engine's internal workings.
18. Packages
"A mechanism to encapsulate a group of classes, sub-
packages, and interfaces."
Purpose:
Types:
Classpath: "Describes the location where all the required files are
available which are used in the application."
Used by the Java compiler (javac) and JVM to locate .class files and
libraries.
"With the help of static import, we can access the static member of
a class directly without class name or any object."
void: Indicates that the main method does not return any value.
For example, Vehicle could be a class, and Car, Truck, or Bicycle would be
objects of that Vehicle class. In a university context, B.Tech Second Year
could be a class, and individual students like "Ravi" or "Saloni" would be
objects.
convert_to_textConvert to source
Quiz: Short-Answer Questions
Answer each question in 2-3 sentences.
1. Why is Java considered a platform-independent language?
Java is platform-independent because of its "Write Once, Run
Anywhere" (WORA) principle. Code written in Java is compiled into
bytecode, which can then be executed on any operating system or
hardware environment that has a Java Virtual Machine (JVM),
eliminating the need for recompilation across different platforms.
5. What are Java comments and why are they used? Java
comments are non-executable statements in a program ignored by
the compiler and interpreter. They are used to add explanatory
notes to the code, improve readability, make code maintenance
easier, and temporarily disable parts of the code during testing
without deleting them.
Answer Key