Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

JAVA

1.1 Basics of Java, Background/History of Java,


Java and the Internet, Advantages of Java
Basics of Java
Java is a high-level, object-oriented programming language known for its simplicity
and ease of use. It was designed to be platform-independent, allowing developers to
write code once and run it on any device or operating system that supports Java
Virtual Machine (JVM).

Background/History of Java
Java was developed by James Gosling and his team at Sun Microsystems in the
early 1990s. It was initially named "Oak" but later renamed "Java." The language's
design was inspired by the C++ programming language but aimed to eliminate
some of its complexities and security flaws.

Java and the Internet


Java's connection with the internet was a crucial factor in its popularity. Java
applets, small programs written in Java, could be embedded in web pages and run
on a client's browser. However, the use of Java applets has decreased over time due
to security concerns and advancements in web technologies.

Advantages of Java
Platform Independence: Java code can run on any device or operating system
with a JVM, making it highly portable.
Object-Oriented: Java's object-oriented approach allows for better code
organization and promotes reusability.
Rich Standard Library: Java comes with a vast standard library that provides
numerous pre-built classes and functions for various tasks.
Garbage Collection: Java's automatic garbage collection feature manages
memory, reducing the burden on developers to handle memory management
manually.
Security: Java's design includes security features that help protect against
malicious code and unauthorized access.
Community and Support: Java has a large and active community, leading to
extensive documentation, libraries, and tools.

1.2 Java Virtual Machine & Byte Code


The Java Virtual Machine (JVM) is an essential part of the Java Runtime
Environment (JRE). It interprets Java bytecode, which is generated by compiling
Java source code. JVM allows Java programs to run on any platform that supports
the JVM, providing the "write once, run anywhere" capability.

1.3 Java Environment Setup


To start developing and running Java programs, you need to set up the Java
Development Kit (JDK) on your computer. The JDK includes essential tools like the
Java compiler (javac) and the Java Virtual Machine (JVM) needed for Java
development.

Steps for Java Environment Setup:


1. Download the JDK: Visit the official Oracle website (or the JDK provider of your
choice) to download the appropriate JDK version for your operating system.
Make sure to download the JDK, not just the Java Runtime Environment (JRE),
as the JDK includes additional development tools.
2. Installation: Once the JDK is downloaded, run the installation executable and
follow the on-screen instructions to install it on your computer.
3. Environment Variables: After the installation is complete, you need to set up
environment variables to tell your computer where to find the Java executables.
The environment variables are "JAVA_HOME" (the path to the JDK installation
directory) and "PATH" (to include the JDK's "bin" directory). The exact steps for
setting up environment variables depend on your operating system. Ensure that
the changes take effect by either restarting your computer or opening a new
command prompt or terminal.
4. Verify Installation: To verify that the JDK is correctly installed, open a
command prompt or terminal and run the following commands:
java -version
javac -version

These commands should display the installed Java version and Java compiler
version, respectively.

Integrated Development Environments (IDEs):


While you can write Java code using a simple text editor and compile it manually,
many developers prefer using Integrated Development Environments (IDEs) that
provide comprehensive tools for Java development. Popular Java IDEs include
Eclipse, IntelliJ IDEA, and NetBeans.

Using an IDE can simplify the development process, providing features like code
auto-completion, syntax highlighting, debugging, and project management.

1.4 Java Program Structure


In Java, a program is organized into classes and methods. A class serves as a
blueprint for creating objects with shared characteristics and behaviors. Methods
define the actions and operations that objects of the class can perform.

Java Class:
A Java class is a template or blueprint for creating objects. It encapsulates data
(also known as fields or instance variables) and methods (also known as functions
or behaviors) that operate on that data.

Here's the general syntax for defining a Java class:

public class MyClass {


// Instance variables (data)
private int age;
private String name;

// Constructor
public MyClass(int age, String name) {
this.age = age;
this.name = name;
}

// Methods (behaviors)
public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

Java Methods:
Methods in Java are blocks of code that perform specific tasks or actions. They can
take input parameters and return values. Methods are defined within a class and
can be accessed and invoked on objects of that class.

Here's the general syntax for defining a Java method:

public returnType methodName(parameterType parameterName) {


// Method body
// Perform actions here
return result; // If the method has a return type
}

For example, consider the following class with a method:

public class Calculator {


public int add(int num1, int num2) {
return num1 + num2;
}
}

In this example, the "add" method takes two integer parameters, "num1" and "num2,"
and returns their sum as an integer.

1.4 Java Program Structure


A Java program is organized into classes and methods. A class serves as a
blueprint for creating objects with shared characteristics and behaviors. Methods
define the actions and operations that objects of the class can perform.
Here's a basic example of a Java program with a class and a method:

public class MyClass {


public void printMessage() {
System.out.println("This is a method in MyClass.");
}
}

1.5 Procedure-Oriented vs. Object-Oriented


Programming Concept
Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP)
are two different paradigms for organizing and designing software systems. Let's
explore the key differences between these two approaches:

Procedure-Oriented Programming (POP):


Procedure-oriented programming focuses on writing procedures or functions to
perform tasks. In this paradigm, the program is divided into smaller, reusable
routines that interact with each other through function calls.

Key characteristics of POP include:

Programs are organized around procedures or functions.


Emphasis on a step-by-step algorithmic approach.
Data is often global and shared among procedures.
Procedures are used to manipulate data.
Limited reusability as functions are tightly coupled with data.

Object-Oriented Programming (OOP):


Object-Oriented Programming revolves around the concept of objects. An object is
an instance of a class, which encapsulates both data and behavior within it. The
data is represented as attributes or properties, and behavior is represented as
methods or functions.

Key characteristics of OOP include:

Programs are organized around objects and their interactions.


Emphasis on modeling real-world entities and relationships.
Data is encapsulated and hidden within objects.
Objects communicate with each other through methods.
High reusability and modularity due to the use of classes and inheritance.

Example to Illustrate the Difference:


Let's consider a simple example of a car program:

// Procedure-Oriented Approach
int calculateSpeed(int distance, int time) {
return distance / time;
}

void displaySpeed(int speed) {


System.out.println("The speed is: " + speed + " km/h");
}

int distance = 100; // in kilometers


int time = 2; // in hours
int speed = calculateSpeed(distance, time);
displaySpeed(speed);

// Object-Oriented Approach
class Car {
private int distance;
private int time;

public Car(int distance, int time) {


this.distance = distance;
this.time = time;
}

public int calculateSpeed() {


return distance / time;
}

public void displaySpeed() {


System.out.println("The speed is: " + calculateSpeed() + " km/h
}
}

Car myCar = new Car(100, 2);


myCar.displaySpeed();
In the procedure-oriented approach, we have separate functions to calculate and
display the car's speed. In the object-oriented approach, we encapsulate the car's
attributes and behavior within a Car class. The class has methods to calculate and
display the speed, making the code more organized and modular.

1.5 Procedure-Oriented vs. Object-Oriented


Programming Concept
Procedure-oriented programming focuses on writing procedures or functions to
perform tasks. It is based on dividing the program into smaller reusable routines.
However, it lacks the concept of encapsulation and data hiding.

On the other hand, Object-Oriented Programming (OOP) revolves around the


concept of objects. Objects are instances of classes, and they encapsulate both
data and behavior within them, promoting better organization and modularity in the
code.

Here's a simple example to illustrate the difference between the two approaches:

// Procedure-Oriented Approach
int calculateSum(int a, int b) {
return a + b;
}

// Object-Oriented Approach
class Calculator {
private int result;

public Calculator(int a, int b) {


result = a + b;
}

public int getResult() {


return result;
}
}
1.6 Basics of OOP: Abstraction, Inheritance,
Encapsulation, Classes, subclasses, and
superclasses, Polymorphism, and Overloading,
message communication
Abstraction:
Abstraction is a fundamental concept in Object-Oriented Programming (OOP) that
allows you to define the essential features of an object while hiding the unnecessary
details. It focuses on the behavior and properties of objects rather than their
implementation.

In Java, abstraction is achieved using abstract classes and interfaces. Abstract


classes provide a blueprint for other classes to inherit from, while interfaces define
a contract for classes to implement certain methods.

Example - Abstract Class:

abstract class Shape {


int sides;
abstract void draw();

void showSides() {
System.out.println("Number of sides: " + sides);
}
}

In this example, the "Shape" class is abstract and has an abstract method "draw()"
that must be implemented by its subclasses. It also has a concrete method
"showSides()" with a default implementation.

Inheritance:
Inheritance is a powerful mechanism in OOP that enables a class (subclass) to
inherit properties and behaviors from another class (superclass). The subclass can
extend or specialize the functionality of the superclass while inheriting its common
features.

Example - Superclass and Subclass:


class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Dog barks");
}
}

In this example, the "Animal" class has a method "makeSound()", and the "Dog"
class extends the "Animal" class. The "Dog" class overrides the "makeSound()"
method with its own implementation.

Encapsulation:
Encapsulation is the concept of restricting direct access to data, providing methods
(getters and setters) to manipulate the data. It helps protect the internal state of an
object from being modified by external entities and ensures data integrity.

Example - Encapsulation:

class Person {
private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


if (age >= 0) {
this.age = age;
}
}
}

In this example, the "Person" class has private fields "name" and "age." The access
to these fields is controlled through getter and setter methods, allowing controlled
access and modification of the data.

Classes, Subclasses, and Superclasses:


In Java, a class is a blueprint for creating objects with shared characteristics and
behaviors. A subclass is a class that inherits from another class, known as its
superclass. The subclass can inherit fields and methods from the superclass and
add its own unique features.

Example - Superclass and Subclass:

class Vehicle {
void start() {
System.out.println("Vehicle starts");
}
}

class Car extends Vehicle {


void start() {
System.out.println("Car starts with a key");
}
}

class Bicycle extends Vehicle {


void start() {
System.out.println("Bicycle starts by pedaling");
}
}

In this example, the "Vehicle" class is the superclass, and both "Car" and "Bicycle"
classes are its subclasses. Each subclass overrides the "start()" method with its
own implementation.

Polymorphism and Overloading:


Polymorphism is the ability of objects of different classes to be treated as objects
of a common superclass. In Java, this is achieved through method overriding and
method overloading.
Example - Polymorphism and Overloading:

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

In this example, the "Calculator" class has two "add()" methods, one for integers and
another for doubles. Java will automatically choose the appropriate method based
on the data types of the arguments during method invocation.

Message Communication:
In OOP, objects interact with each other by sending messages. A message is a
request for an object to perform a particular action or method. Objects
communicate and collaborate by invoking methods on each other, leading to the
flow of control between different objects in the program.

Example - Message Communication:

class Person {
void greet() {
System.out.println("Hello, I am a person.");
}
}

class Greeting {
void greetPerson(Person person) {
person.greet();
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person();
Greeting greeting = new Greeting();
greeting.greetPerson(person);
}
}
In this example, the "Person" class has a "greet()" method that prints a greeting. The
"Greeting" class has a method "greetPerson()" that takes a "Person" object as an
argument and calls its "greet()" method.

1.7 Compiling and Running a Simple "Hello World"


Program
Let's go through the steps to compile and run a simple "Hello World" program in
Java:

1. Setting Up Your Computer: Install the Java Development Kit (JDK) and set up
the environment variables.
2. Writing a Program: Create a Java source code file with the correct class and
method structure. Save it with a .java extension.
3. Compiling: Use the Java compiler (javac) to convert the Java source code into
bytecode. Open a terminal or command prompt and run:
javac HelloWorld.java

4. Interpreting and Running the Program: Execute the compiled bytecode using
the Java Virtual Machine (JVM). Run:
java HelloWorld

5. Common Errors: Be aware of common mistakes such as typos, missing


semicolons, or mismatched brackets that may cause compilation or runtime
errors.

© 2023 Your Company. All rights reserved.

You might also like