0% found this document useful (0 votes)
5 views

Java Crash Course

Java is a high-level, object-oriented programming language known for its platform independence and robust features. The document covers key concepts such as Java syntax, variables, data types, control flow statements, methods, object-oriented programming principles, and exception handling. It provides examples and explanations to help understand the fundamentals of Java programming.

Uploaded by

lavanyasingh0908
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Crash Course

Java is a high-level, object-oriented programming language known for its platform independence and robust features. The document covers key concepts such as Java syntax, variables, data types, control flow statements, methods, object-oriented programming principles, and exception handling. It provides examples and explanations to help understand the fundamentals of Java programming.

Uploaded by

lavanyasingh0908
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

INTRODUCTION

TO JAVA
WHAT IS JAVA?
Java is a high-level, object-oriented
programming language.

Developed by James Gosling at Sun


Microsystems (now owned by Oracle).

Write Once, Run Anywhere (WORA) – Java


programs run on any platform that
supports Java.
WHAT IS JAVA?
Key Features of Java:
✔ Platform-independent (Runs on any OS)
✔ Secure and robust
✔ Multi-threaded
✔ Supports OOP principles
HOW JAVA WORKS?
(COMPILATION & EXECUTION
PROCESS)
1. Writing Code: We write Java code in a file
with a .java extension.
2. Compilation: Java Compiler (javac) converts
the code into Bytecode (.class file).
3. Execution: The JVM (Java Virtual Machine)
interprets the bytecode and runs the program
on any platform.
WRITING YOUR FIRST JAVA
PROGRAM ("HELLO WORLD")
Code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
WRITING YOUR FIRST JAVA
PROGRAM ("HELLO WORLD")
Explanation:
✔ public class HelloWorld → Defines a class
named HelloWorld.
✔ public static void main(String[] args) →
Main method, program execution starts here.
✔ System.out.println("Hello, World!"); →
Prints output to the console.
BASICS OF
JAVA SYNTAX
VARIABLES IN JAVA
✔ A variable is a container that holds data.
✔ Java variables must be declared with a type
before use.

Declaration Syntax:
dataType variableName = value;
RULES FOR NAMING
VARIABLES:
Can start with a letter, $, or _ (but not a
number).
Cannot use Java keywords (e.g., int, class).
Uses camelCase naming convention (e.g.,
studentAge).
TYPES OF VARIABLES IN JAVA
Local Variables: Declared inside methods,
accessible only within that method.
Instance Variables: Belong to an object,
declared inside a class but outside
methods.
Static Variables: Declared with static,
shared across all instances of a class.
TYPES OF VARIABLES IN JAVA
Example:

class Student {
String name; // Instance variable
static String school = "ABC School"; // Static variable

void show() {
int age = 20; // Local variable
System.out.println(name + " studies at " + school);
}
}
DATA TYPES IN JAVA
✔ Java has two categories of data types:
⿡ Primitive Data Types (stores simple values)
⿢ Non-Primitive Data Types (stores objects and
complex structures)
DATA TYPES IN JAVA
DATA TYPES IN JAVA
Important Points About Data Types
✔ By default, decimal values are stored as double.
✔ To store a float value, add f or F at the end
(float x = 5.6f;).
✔ Integer values are stored as int by default.
✔ long values must have an L at the end (long
num = 100000L;).
✔ boolean can only be true or false (not 0 or 1).
DATA TYPES IN JAVA
Non-Primitive Data Types
✔ Non-primitive types are user-defined or Java-
built objects.
✔ Examples: Strings, Arrays, Classes, Interfaces,
etc.

Example:
String name = "Java";
int[] numbers = {10, 20, 30}; // Array
OPERATORS IN JAVA
Operators are used to perform operations on
variables and values.
INTRODUCTION TO
CONTROL FLOW
STATEMENTS
CONTROL FLOW STATEMENT
✔ Control flow statements determine how Java
programs execute instructions.

✔ Three main types of control flow statements:


⿡ Conditional Statements (Decision-making)
⿢ Loops (Repetitive execution)
⿣ Jump Statements (Altering normal flow)
CONDITIONAL STATEMENTS
Used to execute a block of code based on a
condition.

Java provides three types:


1. if-else
2. else-if ladder
3. switch-case
CONDITIONAL STATEMENTS
if-else
" if " executes a block if the condition is true,
otherwise " else " executes.
Syntax:
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
CONDITIONAL STATEMENTS
else-if ladder Syntax:
Used to check multiple if (condition1) {
// Code executes if condition1 is true
conditions sequentially.
✔ If one condition is
} else if (condition2) {
// Code executes if condition2 is true
true, remaining
} else {
conditions are skipped.
// Code executes if no conditions are true
}
CONDITIONAL STATEMENTS
switch-case Syntax:
Used when a switch (expression) {
variable is case value1:
compared against // Code executes if expression == value1
break;
multiple fixed
case value2:
values.
// Code executes if expression ==
Faster than
value2
multiple if-else in
break;
cases with many default:
conditions. // Code executes if no cases match
}
LOOPS IN JAVA
Loops execute a block of code multiple times.

✔ Three types of loops in Java:


1.for Loop
2.while Loop
3.do-while Loop
LOOPS IN JAVA
for loop
✔ Used when number of iterations is known.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
⿢ while loop
✔ Used when number of iterations is unknown, and the loop
should run while a condition is true.
Syntax:
while (condition) {
// Code executes as long as condition is true
}
LOOPS IN JAVA
do-while loop
✔ Executes at least once, even if the condition is false.
Syntax:
do {
// Code executes at least once
} while (condition);
JUMP STATEMENTS
Jump statements alter the normal flow of loops or
conditions.

Java provides two main jump statements:


break(keyword) - Exits the loop immediately.
continue(keyword) - Skips the current iteration and
continues the loop.
STRINGS AND
ARRAYS
INTRODUCTION TO STRINGS
Strings are sequences of Strings can be created using:
characters used for text 1. String Literal
processing. Example:
String str1 = "Hello";
A String in Java is an immutable 2. New Keyword
sequence of characters stored Example:
as a char array internally. String str2 = new String("Hello");

Strings in Java are objects of the


String class.
DIFFERENT STRING METHODS
DIFFERENT STRING METHODS
INTRODUCTION TO ARRAYS
An array is a collection of elements of the same data
type stored in contiguous memory.
Arrays can be single-dimensional or multi-dimensional.
The size of an array is fixed in Java.

Syntax:
dataType [ ] var_name = new dataType[number];
DIFFERENT ARRAYS METHOD
ITERATING OVER ARRAYS
(FOR-EACH LOOP)
Enhanced for-loop simplifies array traversal.

Syntax:
for (dataType var_name : array_name) {
//perform desired operation
}
MULTI-DIMENSIONAL ARRAYS
2D Arrays (Matrix Representation)

Elements are stored in row-column format.


Syntax:
int [ ][ ] matrix = new int [row_size][column_size];
INTRODUCTION
TO METHODS
METHODS IN JAVA
A method in Java is a block of code that performs a
specific task. Methods help in code reusability, modularity,
and better organization of code.
DEFINING AND CALLING
METHODS
A method in Java is defined using the following syntax:

returnType methodName(parameter1, parameter2, ...) {


// Method body
return value; // If returnType is not void Example:
} public class Main {
// Method definition
static void greet() {
System.out.println("Hello, welcome to Java!");
}
public static void main(String[] args) {
greet(); // Calling the method
}
}
METHOD OVERLOADING
Method Overloading allows multiple methods with the
same name but different parameter lists in a class.

Example: Key Points:


public class MathOperations { (1) Overloaded methods must differ in
// Method with two parameters the number or type of parameters.
static int add(int a, int b) { (2) They cannot differ only in the
return a + b; return type
}
// Overloaded method with three parameters
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(5, 10)); // Calls first method
System.out.println(add(5, 10, 15)); // Calls overloaded method
}
}
VARIABLE ARGUMENTS
(VARARGS)
Varargs (Variable Arguments) allow a method to accept
multiple arguments of the same type without specifying
the exact number of parameters.

Syntax:
returnType methodName(dataType...variableName) {
// Method body
}

Key Points:
(1) int... numbers allows multiple arguments of type int.
(2) Inside the method, numbers behaves like an array.
RECURSION IN JAVA
Recursion is a technique where a method calls itself until a
base condition is met. It is useful for problems like factorial,
Fibonacci series, and tree traversal.

Key Points:
(1) Every recursive function must have a base case to stop
recursion.
(2) Recursion is useful but can cause stack overflow if not
handled correctly.
RECURSION IN JAVA
RECURSION IN JAVA
INTRODUCTION
TO OOP
INTRODUCTION TO OOP
Object-Oriented Programming (OOP) is a
programming paradigm that organizes code using
objects and classes. Java follows the OOP
approach, which helps in modularity, reusability,
and maintainability of code.
CLASSES AND OBJECTS
What is a Class?
A class is a blueprint for creating objects. It defines
attributes (variables) and behaviors (methods)
that objects of that class will have.

What is an Object?
An object is an instance of a class. It represents a
real-world entity with properties and behaviors.
CONSTRUCTORS
A constructor is a special method used to initialize
objects. It has the same name as the class and is
automatically called when an object is created.

Types of Constructors:

1. Default Constructor - Automatically provided by


Java if no constructor is defined.
2. Parameterized Constructor - Allows passing
values when creating an object.
CONSTRUCTORS
Example of a Constructor: public class Main {
public static void main(String[] args) {
class Student { Student s1 = new Student("Alice", 20);
String name; s1.display();
int age; }
// Constructor }
Student(String studentName, int studentAge) {
name = studentName; Output:
age = studentAge; Student: Alice, Age: 20
}
void display() {
System.out.println("Student: " + name + ", Age: " + age);
}
}
ACCESS MODIFIERS
Access modifiers define the visibility of a class, method, or
variable.

1. public - Accessible from anywhere.


2. private - Accessible only within the same class.
3. protected - Accessible within the same package and
subclasses.
4. default (no modifier) - Accessible within the same package
only.
ACCESS MODIFIERS
Example of Access Modifiers:

class Example {
public int publicVar = 10;
private int privateVar = 20;
protected int protectedVar = 30;
int defaultVar = 40; // Default access

void display() {
System.out.println("Private Variable: " + privateVar);
}
}
ACCESS MODIFIERS
public class Main {
public static void main(String[] args) {
Example obj = new Example();
System.out.println("Public Variable: " + obj.publicVar);
// System.out.println(obj.privateVar); // Error: privateVar
is private
System.out.println("Protected Variable: " +
obj.protectedVar);
System.out.println("Default Variable: " + obj.defaultVar);
}
}
GETTERS AND SETTERS
Since private variables cannot be accessed directly
outside the class, we use getter and setter methods to
access and modify them.
INHERITANCE
Inheritance allows a class to acquire the properties
and behaviors of another class. The existing class is
called the parent (superclass), and the new class is
called the child (subclass).

Example of Inheritance:

class Animal {
void sound() {
System.out.println("Animals make sounds");
}
}
INHERITANCE
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Inherited method
myDog.bark();
}
}
POLYMORPHISM
Polymorphism allows one method to have
different behaviors depending on the object
calling it.

Types of Polymorphism in Java:


1. Compile-time polymorphism (Method
Overloading)
2. Runtime polymorphism (Method
Overriding)
ENCAPSULATION
Encapsulation is the process of hiding data
using private variables and controlling access
using getters and setters.

Example of Encapsulation:

class BankAccount {
private double balance;
// Setter method
void setBalance(double amount) {
if (amount > 0)
balance = amount;
}
ENCAPSULATION
// Getter method
double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.setBalance(1000);
System.out.println("Account Balance: " + acc.getBalance());
}
}
Output:
Account Balance: 1000.0
ABSTRACT CLASS
An abstract class is a class that cannot be instantiated and may contain both abstract
(unimplemented) and concrete (implemented) methods.

Key Features of Abstract Classes:

✔ Can have both abstract and concrete methods (with implementation).


✔ Can have constructors.
✔ Can have instance variables (fields with data).
✔ Supports method overriding.
✔ Uses the abstract keyword.
✔ A subclass must override abstract methods, or it also remains abstract.
ABSTRACT CLASS
Example of Abstract Class

abstract class Animal {


String name; // Instance variable
// Constructor
Animal(String name) {
this.name = name;
}
// Abstract method (must be implemented by subclasses)
abstract void makeSound();
// Concrete method (has implementation)
void sleep() {
System.out.println(name + " is sleeping.");
}
}
ABSTRACT CLASS
class Dog extends Animal {
Dog(String name) {
super(name);
}
// Implementing abstract method
@Override
void makeSound() {
System.out.println(name + " barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.makeSound(); // Output: Buddy barks.
dog.sleep(); // Output: Buddy is sleeping.
}
INTERFACE IN JAVA
An interface is a fully abstract type that only contains abstract methods
(before Java 8).
From Java 8, interfaces can also have default methods and static methods.

Key Features of Interfaces :

✔ Only abstract methods (before Java 8).


✔ No constructors or instance variables (only constants).
✔ Multiple inheritance is supported (a class can implement multiple
interfaces).
✔ Uses the interface keyword instead of class.
✔ Methods are public and abstract by default.
INTERFACE IN JAVA
Example of Interface

interface Animal {
// Abstract method (public & abstract by default)
void makeSound();
// Default method (introduced in Java 8)
default void sleep() {
System.out.println("Animal is sleeping.");
}
}
INTERFACE IN JAVA
class Dog implements Animal {
// Implementing abstract method
@Override
public void makeSound() {
System.out.println("Dog barks.");
}
} public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // Output: Dog barks.
dog.sleep(); // Output: Animal is sleeping.
}
}
EXCEPTION
HANDLING IN JAVA
EXCEPTION HANDLING IN JAVA
Exception Handling in Java is a mechanism to handle runtime errors and
prevent program crashes. It allows the program to continue execution
smoothly.

Types of Exceptions in Java

1. Checked Exceptions – Exceptions that occur at compile time (e.g.,


IOException, SQLException).
2. Unchecked Exceptions – Exceptions that occur at runtime (e.g.,
NullPointerException, ArithmeticException).
3. Errors – Serious problems that should not be handled (e.g.,
OutOfMemoryError, StackOverflowError).
EXCEPTION HANDLING IN JAVA
Keywords Used in Exception Handling

try – Defines a block of code that might throw an exception.


catch – Handles the exception if one occurs.
finally – A block that always executes (even if an exception
occurs).
throw – Used to explicitly throw an exception.
throws – Declares exceptions that a method might throw.
MULTITHREADING IN
JAVA
What is Multithreading?

Multithreading is the process of executing multiple threads (lightweight


processes) simultaneously to improve application performance.

Thread Lifecycle
1. New – Thread created but not started.
2. Runnable – Ready to run but waiting for CPU allocation.
3. Running – Thread is executing.
4. Blocked/Waiting – Waiting for another thread to release resources.
5. Terminated – Thread has finished execution.
CREATING A THREAD IN
JAVA
Method 1: Extending Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}
Output: Thread is running...
PACKAGES IN
JAVA
PACKAGES IN
JAVA
What is a Package in Java?
A package in Java is a way to group related classes,
interfaces, and sub-packages together. It helps in:
✔ Organizing large projects.
✔ Avoiding class name conflicts.
✔ Controlling access using access modifiers.

You might also like