Class 11 | Java Fundamentals | Java Programming Notes

UNIT 1 CLASS 11 • JAVA PROGRAMMING

Java Fundamentals

Original Scanned PDF – View Notes

History of Java

Java is a general-purpose, object-oriented programming language.
1990

Sun Microsystems decided to develop special software for consumer electronic devices.

1991

Java was developed by Sun Microsystems in the USA by James Gosling. Using C++, the team announced a new language named Oak.

1992

The Green Project team of Sun had a new language to control home appliances using hand-held devices with a tiny, touch-sensitive screen.

1993

The WWW appeared on the Internet and transformed the text-based Internet into a graphics-rich environment using web applets.

1994

The team developed a web browser called Hot Java for web applets.

1995

“Oak” was renamed “Java”. Netscape and Microsoft supported Java.

1996

Java established itself as a leader for Internet and general-purpose programming.

Features of Java

1. Platform Independent

Java programs use the Java Virtual Machine as an abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program can run unmodified on all supported platforms, for example Windows or Linux.

2. Object-Oriented Programming Language

Except the primitive data types, all elements in Java are object.

3. Strongly-Typed Programming Language

Java is a strongly-typed language. The types of the stored variables must be predefined, and conversion to other objects is relatively strict.

4. Interpreted and Compiled Language

Usually a computer language is either compiled or interpreted. Java combines both approaches, thus making a two-stage system. Java source code is translated by a compiler into byte code, which does not depend on the target platform. These byte codes (intermediate code) are interpreted by the Java Virtual Machine (JVM), which generates machine code that can be directly executed by the computer.

Compilation and interpretation process from source code to CPU execution Source Code compiler Byte Code intermediate code Java / JVM Object Code Execute CPU
Fig.: Compilation & Interpretation Process

5. Multithreading and Interactive

Multithreading means handling multiple tasks simultaneously. Java supports multithreading programs. This means we do not wait for other applications to finish one task before beginning. This feature greatly improves the interactive performance of graphical applications.

Thread: Thread is the flow of execution of the process code.
FIFO: First In First Out

6. Scalability and Performance

Java ensures a significant increase in scalability and performance by improving the startup time and reducing the amount of memory used in the runtime environment.

Java Environment

Java Environment includes a large number of development tools and hundreds of classes and methods for developing and running Java programs.

Java development tools are part of the system known as Java Development Kit (JDK), and the classes and methods are part of the Java Standard Library (JSL), also known as Application Programming Interface (API).

Java Development Kit (JDK)

The Java Development Kit (JDK) comes with a collection of tools that are used for developing and running Java programs. It includes:

  1. Appletviewer: It enables us to run Java applets without using a Java-compatible browser.
  2. Javac: The Java compiler, which translates Java source code into a bytecode file the interpreter can understand.
  3. Java: The Java interpreter, which runs applets and applications by reading and interpreting the bytecode file.
  4. Javadoc: Creates HTML-format documentation from a Java source code file.
  5. Javah: Produces header files for use with native methods.
  6. Javap: Java disassembler, which enables bytecode files to be converted into a program description.
  7. Jdb: Java debugger, which helps to find errors in the program.

Java Standard Library (JSL) or Application Programming Interface (API)

API includes hundreds of classes and methods grouped into several functional packages.

Package: A package is a group of related classes and methods.

Common Packages

  1. Language Support Package (java.lang): Includes classes and methods to implement basic features of Java. This package is automatically imported.
  2. Utility Package (java.util): Includes classes to provide utility functions such as date and time.
  3. Input/Output Package (java.io): Includes classes for I/O manipulation.
  4. Networking Package (java.net): Includes classes for supporting networking operations.
  5. Abstract Window Tool (AWT) Package (java.awt): Includes classes for implementing components of a graphical user interface, such as buttons and menus.
  6. Applet Package (java.applet): Includes classes for creating applet programs.
Note: If we use any API classes and methods in a program, we must import the package related to the classes or methods.

The import keyword is used to import a package in programs.

import java.io.*;
import java.applet.*;

Basic Program Structure of Java

A typical structure of a Java program consists of the following parts:

  1. Documentation section
  2. Package declaration
  3. Import statement
  4. Interface section
  5. Class definition
  6. Class variables
  7. Main method class
  8. Methods and behaviours

1. Documentation Section

This section includes basic information about Java programs. The information includes author name, creation, version, programmer name, etc. It increases the readability of the program but is optional in Java programs. To write a statement in the documentation section, we use comments.

The comments can be single-line, multiline and documentation comments.

a) Single-Line Comment

A single-line comment starts with a pair of forward slashes (//).

// This is first Java program

b) Multiline Comment

A multiline comment starts with /* and ends with */.

/* This is the example of Multiline
   Comment */

c) Documentation Comment

A documentation comment starts with the delimiter /** and ends with */.

/** This is the example of documentation
    comment */

2. Package Declaration

It is optional and is placed just after the documentation section.

In this section, we declare the package name in which the class is placed.

There can be only one package statement in Java programs.

It is necessary because a Java class can be placed in different packages and directories based on the module they are used in.

The package keyword is used to declare a package name.

package package_name;

// Examples
package student;
package school.student;

3. Import Statement

A package contains many predefined classes and interfaces.

If you want to use any class of a particular package, you need to import that class.

The import keyword is used to import the class in programs.

In Java, an import statement is used in two ways: either import a specific class or import all classes of a particular package.

import java.util.Scanner;
// import Scanner class only

import java.util.*;
// import all the classes of java.util package

4. Interface Section

It is optional.

An interface is created in this section.

An interface is slightly different from a class and contains only constants and method declarations.

The interface keyword is used to create an interface.

interface Car
{
    void start();
    void stop();
}

5. Class Definition

The class is a blueprint of a Java program.

It contains user-defined methods, variables and constants.

A Java program contains one or more classes.

The class keyword is used to define a class.

class student
{
    // body of class
}

6. Class Variables and Constant

After class definition, variables and constants are defined.

Variables and constants store values of parameters.

The scope of variables can also be defined by access modifiers.

class student
{
    int age;            // variable definition
    String name;
    double percentage;
}

7. Main Method Class

In this section, the main() method is defined.

It must be defined inside one class.

Execution of all Java programs starts from the main() method.

Inside the main() method, objects of classes are created and methods are called.

public static void main(String args[])
{
}
public

public is an access specifier. It must be written before the main method so that JVM can identify the execution point of programs.

static

static is a keyword that makes the main() method callable without creating an object. Static methods are invoked without creating objects, so we do not need an object to call the main method.

void

void is a return type that acknowledges the compiler that the main() method does not return any value.

main()

main() is a default signature which is predefined in the Java (JVM) Virtual Machine.

String args[]

It is the String-type argument accepted by the main() method. It accepts a group of Strings, which is called a String argument.

Sample Java Program

// program to display own name
import java.lang.*;

class Test
{
    public static void main(String args[])
    {
        System.out.println("My name is Bipana.");
    }
}

Compiling and Running Java Program

Using command prompt:

  1. First install JDK in your computer.
  2. Open a text editor such as Notepad and type code.
  3. Save it with Java extension, e.g. Myfile.java.
  4. Open command prompt.
  5. Use the following command to compile the Java program. It generates a class file in the same folder:
javac Myfile.java
  1. Use the following command to run the Java program:
java Myfile
  1. Output will appear like this: My name is Bipana.
Note: Java programs can be compiled and run using Integrated Development Environments (IDEs) such as NetBeans.
Source note: The scan lists “Methods and behaviours” as item 8 in the typical Java program structure, but it moves to “Illustration of class” without a separate item-8 explanation.

Illustration of Class

  • A class is a blueprint for the object.
  • It encapsulates field (data) and methods (functions) in a single unit.
  • It is designed before creating an object.
  • It is created using the class keyword.

Syntax

class class_name
{
    // fields
    // methods
}

Fields (variables) and methods represent the state and behaviour of an object respectively.

Fields are used to store data.

Methods are used to perform some operation.

Example

class Rectangle
{
    int length;
    int breadth;

    int Area(int l, int b)
    {
        return (l * b);
    }
}

Illustration of Object

  • An object is called an instance of a class.
  • A Java object is a member of a Java class.
  • Each object has an identity, a behaviour and a state.
  • The state of an object is stored in fields (variables), whereas methods display the object’s behaviour.
  • Objects are created using the new operator.

Syntax

ClassName object = new ClassName();

Here, ClassName() is a constructor. A constructor is similar to a method and has the same name as the class and no return type.

Example

Rectangle obj1 = new Rectangle();

Program Illustrating Class and Object

class Rectangle
{
    int length;
    int breadth;

    void SetData(int l, int b)
    {
        length = l;
        breadth = b;
    }

    int RectArea()
    {
        int area;
        area = length * breadth;
        return area;
    }
}

class RectangleArea
{
    public static void main(String args[])
    {
        Rectangle obj = new Rectangle();   // creating object
        obj.SetData(10, 5);                // methods calling
        int result = obj.RectArea();

        System.out.println("Area of Rectangle=" + result);
    }
}

Data Abstraction (Data Hiding)

Data abstraction is the process of hiding certain details and showing only essential information to the user.

Abstraction can be achieved with either an abstract class or an interface.

The abstract keyword is a non-access modifier used for classes and methods.

  • An abstract class is a restricted class that cannot be used to create objects. To access it, it must be inherited from another class.
  • An abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass.
  • An abstract class can have both abstract and regular methods.

Program Illustrating Data Abstraction in Java

abstract class Animal
{
    public abstract void animalsound();

    public void sleep()
    {
        System.out.println("zzz");
    }
}

class Pig extends Animal
{
    public void animalsound()
    {
        System.out.println("The pig sound");
    }
}

class AbstractionTest
{
    public static void main(String args[])
    {
        Pig obj = new Pig();
        obj.animalsound();
        obj.sleep();
    }
}

Encapsulation

  1. Encapsulation is the process or mechanism of wrapping the data (variables) and code acting on the data (method) together as a single unit.
  2. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of the current class.
  3. Therefore, it is also known as data hiding.

To Achieve Encapsulation in Java

  1. Declare the variables of a class as private.
  2. Provide public getter and setter methods to modify and view variable values.

Program to Illustrate Encapsulation in Java

public class EncapTest
{
    private String name;
    private int age;

    public int getAge()
    {
        return age;
    }

    public String getName()
    {
        return name;
    }

    public void setAge(int newage)
    {
        age = newage;
    }

    public void setname(String newname)
    {
        name = newname;
    }
}

class Encapun
{
    public static void main(String args[])
    {
        EncapTest obj = new EncapTest();
        obj.setName("Bipana");
        obj.setAge(17);

        System.out.println("Name:" + obj.getName());
        System.out.println("Age:" + obj.getAge());
    }
}
Possible source issue preserved: The scan defines setname(...) with a lowercase “n”, but later calls setName(...) with an uppercase “N”. The typed version keeps that casing difference instead of silently correcting it.

Polymorphism

Polymorphism refers to the ability of a class to provide different implementations of a method depending on the type of object passed to the method.

The same entity (method or operation on a subject) can perform different operations in different scenarios.

So, polymorphism is the ability of an object to take many forms.

The most common use of polymorphism occurs when a parent class reference is used to refer to a child class object.

Program to Illustrate Polymorphism in Java

class Polygon
{
    public void input()
    {
        System.out.println("I am the polygon");
    }
}

class Square extends Polygon
{
    public void input()
    {
        System.out.println("I am the square");
    }
}

class Circle extends Polygon
{
    public void input()
    {
        System.out.println("I am the circle");
    }
}

class PolyResult
{
    public static void main(String args[])
    {
        Square S1 = new Square();
        S1.input();

        Circle C1 = new Circle();
        C1.input();

        Polygon P1 = new Polygon();
        P1.input();
    }
}

Types of Polymorphism

  1. Method overloading
  2. Method overriding

Method Overloading

Method overloading is the process that can create multiple methods of the same name in the same class, and all methods work in different ways.

It occurs when there is more than one method of the same name in the class.

Example Illustrating Method Overloading

class CalculateArea
{
    public void area()
    {
        System.out.println("Calculating area");
    }

    public void area(int r)
    {
        System.out.println("The area of Circle =" + 3.14 * r * r);
    }

    public void area(int l, int b)
    {
        System.out.println("The area of rectangle =" + l * b);
    }
}

class Test
{
    public static void main(String args[])
    {
        CalculateArea obj = new CalculateArea();

        obj.area();
        obj.area(6);
        obj.area(6, 7);
    }
}

Program to Input Two Integer Numbers from User and Find Sum

// using Java scanner class
import java.util.*;

class CalculateSum
{
    public static void main(String[] args)
    {
        int a, b, sum;

        Scanner Sc = new Scanner(System.in);
        // System.in is a standard input stream

        System.out.println("Enter first number:");
        a = Sc.nextInt();

        System.out.println("Enter second number:");
        b = Sc.nextInt();

        sum = a + b;

        System.out.println("Total sum =" + sum);
    }
}

Java Scanner Class

  • Scanner class allows us to take input from the user.
  • This class belongs to the java.util package.
  • It is used to input primitive data types such as int, double, long, short, float and byte.

Syntax

Scanner Sc = new Scanner(System.in);

This creates a constructor of the Scanner class having System.in as an argument. It means it is going to read from the standard input stream of the program.

Sc is an object of class Scanner.

Methods of Scanner Class

S.N. Method Meaning in the Source
1 nextInt() Reads integer value
2 nextFloat() Reads floating value
3 nextDouble() Reads double value
4 nextByte() Reads byte value
5 nextLine() Reads single line or string
6 nextBoolean() Boolean value, either true or false
7 nextLong() Reads long value

Method Overriding

Method overriding enables methods to be defined and used repeatedly in a subclass without defining them in the superclass.

Example

class Super
{
    int x;

    Super(int x)
    {
        this.x = x;
    }

    void Display()
    {
        System.out.println("Super x =" + x);
    }
}

class Sub extends Super
{
    int y;

    Sub(int x, int y)
    {
        super(x);
        this.y = y;
    }

    void Display()
    {
        System.out.println("Super x =" + x);
        System.out.println("Super y =" + y);
    }
}

class Override-Test
{
    public static void main(String args[])
    {
        Sub S1 = new Sub(10, 20);
        S1.Display();
    }
}

In short, if a subclass has the same method as declared in the superclass, it is known as method overriding.

Possible source issue preserved: The scan writes the final class name as Override-Test. The hyphen is retained here because the supplied PDF is the source of truth.
Scan note: PDF page 26 is an exact duplicate of page 25, so the repeated page is acknowledged here rather than duplicating the same typed code a second time.

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play