0% found this document useful (0 votes)
26 views21 pages

Oops Unit 4

Uploaded by

Khushie Leish
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)
26 views21 pages

Oops Unit 4

Uploaded by

Khushie Leish
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/ 21

Java

● Currently, Java is being used in Internet programming, e-business solutions, mobile devices,
games, etc.
● Introduced by James Gosling in 1991. The small team of Sun engineers was called Green
Team.
● Originally designed was small, embedded systems in electronic appliances like set-top
boxes.
● Firstly, it was called “Greentalk” by James Gosling
● After that , it was called Oak.
Why Oak for Java Language?
1. Oak is a symbol of strength and chosen as a national tree in many countries like France,
USA, Romania, Germany, etc.
2. In 1995, Oak was renamed as Java because it was already a trademark for Oak
technologies.
Why Java name for Java language?
● Java is an island of Indonesia where first coffee was produced.
● Originally released by James Gosling at Sun Microsystems in 1995.
● In 1995, Time Magazine called Java as one of the Ten Best Products of 1995.
● The team gathered to choose a new name. The suggested words were Silk, dynamic,
revolutionary, DNA, etc. But Java was unique.

Some of the applications of Java are:


1) Desktop-based applications like acrobat reader, antivirus, media player, etc.
2) Smart cards
3) Robotics
4) Games
5) Web applications
6) Enterprise applications
7) Mobile, etc.

Characteristics of Java:
1. Simple
2. Portable
3. Object-oriented
4. Secure: Java doesn't support pointer explicitly, But Java uses pointer implicitly.
Java is used in a networked and distributed environment. The following features make Java
a secure language:

● No use of explicit pointers


● Java Program runs inside a virtual sandbox (Java Virtual Machine or JVM).
● Classloader: The Java Runtime Environment (JRE) includes a classloader that is used
to dynamically load Java classes into the Java Virtual Machine. It improves security
by isolating the package for local file system classes from those imported from
network sources.
● Byte code verifier
● Security Manager: It determines the resources a class has access to, such as reading
and writing to the local disc.
5. Platform independent: If we use pointers the address of the variable varies in different
machines. Thus using pointers becomes invalid and provides different result in different
machine.
6. Robust- Java use strong memory management. Lack of pointers that avoid security
problem. Automatic garbage collection. Exception handling and type checking
7. Dynamic
8. Interpreted
9. High performance: Java’s performance and efficiency are remarkable since byte codes
are very close to machine code. However, it is still slower than languages like C++ which
are compiled. The fundamental reason is that Java applications, unlike C and C++
programs, run on a Java virtual machine (JVM) after compiling rather than directly on
the computer’s CPU as native code.
10. Architectural Neutral: In C programming, the int data type takes up two bytes in 32-bit
architecture and four bytes in 64-bit architecture. In Java, however, it takes up 4 bytes
of memory on both 32-bit and 64-bit architectures
11. Distributed- We can create distributed applications in Java. EJB are used for creating
distributed applications. We can access the files by calling the methods from any
machine on internet. Distributed computing involves the collaboration of multiple
computers over a network. Java was created with the goal of making distributed
computing simple. Because networking is inherent in Java, developing network
programs is as simple as sending and receiving data to and from a file.
12. Multithreaded- A thread is like a separate program executing concurrently. We can
write Java programs that can deal multiple tasks at once by creating multiple threads.
Threads share memory. Important in multimedia and web applications. For example,
while surfing the web, a user can listen to an audio recording. A server can serve many
clients at the same time in network programming. Similarly, there are a lot of things
going on in GUI programming at the same time. These simultaneous processes can be
implemented in Java through multi-threading.
● Java is not considered a pure object-oriented programming language.
● The main reason is it supports primitive type values. For an object-oriented programming
language, data should be represented in the form of objects. As Java uses primitive data
types, it is not considered a pure object-oriented programming language.
● It supports the use of the static keyword. Static variables and methods can be accessed
without an object or without creating an object of a class.
According to Sun, Java removed many features of C++ like operator overloading, explicit
pointers, etc.
Why Java is Secure?
Java is the most popular object-oriented programming language. It provides a variety of salient
features that are preferred by the developers. It is the reason that a billion of devices runs on Java.

Java is secure due to the following reasons:

o Java programs run inside a virtual machine which is known as a sandbox.


o Java does not support explicit pointer.
o Byte-code verifier checks the code fragments for illegal code that can violate access right to
object.
o It provides java.security package implements explicit security.
o It provides library level safety.
o Run-time security check takes place when we load new code.

Java provides some other features that make Java more secure.

o JVM
o Security API's
o Security Manager
o Auto Memory Management: Java automatically manages memory which is known as
garbage collection. The JVM manages memory itself. The programmers are free from
memory management.
o No Concept of Pointers: Java does not provide support for pointers concept. It is the main
security features of Java. The use of pointers may lead to unauthorized read or write
operations. Therefore, the user cannot point to any memory locations.
o Compile-time Checking: Compile-time checking also makes the Java secure. Consider a
scenario in which an unauthorized method is trying to access the private variable, in this
case, the JVM gives the compile-time error. It prevents the system from the crash.
o Cryptographic Security
o Java Sandbox
o Exception Handling: The exception handling feature adds more security in Java. The feature
reports the error to the programmer during the runtime. The code will not run until the
programmer will not rectify it.
o ClassLoader

Introduced Garbage Collector


Java code can run on multiple platforms. Its code is compiled and converted into bytecode
which is platform independent, i.e., Write Once and Run Anywhere (WORA).
JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

Java Variables:
1. Local variables: Variables declared inside the body of a method
2. Instance variables: Variables declared inside the class but outside the body of method.
3. Static variable: Variable declared as static. It cannot be local. They are allocated
memory only one time when the class is loaded.

Java Tokens
1. Keywords
2. Identifiers
3. Constants/Literals
4. Special Symbols: [] () {}, ; * =
5. Operators
6. Comments
7. Separators

1.Keywords:
abstract assert boolean
break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
to transient transitive
try uses void
volatile while with

1. Constants: Constants are also like normal variables. But the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to
fixed values.
final int PI = 3.14; //Here final keyword is used to define the constant PI
2. Operators:
● Arithmetic Operators
● Unary Operators
● Assignment Operator
● Relational Operators
● Logical Operators
● Ternary Operator: variable = Expression1 ? Expression2: Expression3
● Bitwise Operators
● Shift Operators
● instance of operator
● Precedence and Associativity

instanceof Keyword in Java

// Java Program to Illustrate instanceof Keyword


// Importing required I/O classes
import java.io.*;

// Main class
class ABC {
public static void main(String[] args)
{
// Creating object of class inside main()
ABC object = new ABC();
// Returning instanceof
System.out.println(object instanceof ABC);
}
}

Output
true

// Java program to demonstrate working of instanceof Keyword

// Class 1
// Parent class
class Parent {
}

// Class 2
// Child class
class Child extends Parent {
}

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of child class


Child cobj = new Child();

// A simple case
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");

// instanceof returning true for Parent class also


if (cobj instanceof Parent)
System.out.println("cobj is instance of Parent");
else
System.out.println("cobj is NOT instance of Parent");

// instanceof returns true for all ancestors

// Note : Object is ancestor of all classes in Java


if (cobj instanceof Object)
System.out.println("cobj is instance of Object");
else
System.out.println("cobj is NOT instance of Object");
}
}
Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance


variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog( );
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property, we
need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat( ){
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat( ){
System.out.println("eating bread...");
}
void bark( ){
System.out.println("barking...");
}
void work( ){
super.eat( );
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from
Dog class, it will call the eat() method of Dog class by default because priority is given to local. To
call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal( ){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog( ){
super( );
System.out.println("dog is created");
}
}
class Main{
public static void main(String args[]){
Dog d=new Dog();
}
}
Output:
animal is created
dog is created
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super( ) as the first statement.

Another example of super keyword where super( ) is provided by the compiler implicitly.

class Animal{
Animal ( ){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog( ){
System.out.println("dog is created");
}
}
class Main{
public static void main(String args[ ]){
Dog d=new Dog( );
}}
Output:
animal is created
dog is created

Creating a Multilevel Inheritance Hierarchy


in Java
Example
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}

Output
This is class A
This is class B
This is class C
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:

1. String s="javatpoint";
The java.lang.String class is used to create a string object.
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't
exist in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in a heap (non-pool).

A String in Java that is specified as immutable

import java.io.*;
class ABC {
public static void main(String[ ] args)
{
String s1 = "java";
s1.concat(" rules");

// Yes, s1 still refers to "java"


System.out.println("s1 refers to " + s1);
}
}
Output
s1 refers to java
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
An abstract class is a class that is declared abstract —it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed. When an
abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.

Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract
method.

1. abstract void print( );//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike{


abstract void run( );
}
class Honda extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[ ]){
Bike obj = new Honda();
obj.run();
}
}
Any class that contains one or more abstract methods must also be declared abstract. To declare a class
abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class
declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract class is not fully
defined. Also, you cannot declare abstract constructors, or abstract static methods.

Using final with Inheritance


The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The
other two uses of final apply to inheritance.
Using final to Prevent Overriding While method overriding is one of Java’s most powerful features,
there will be times when you will want to prevent it from occurring. To disallow a method from being
overridden, specify final as a modifier at the start of its declaration.

Methods declared as final cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() {
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time
error will result.

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too.

Here is an example of a final class:

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
● Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
● Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
● Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
● Packages can be considered as data encapsulation (or data-hiding).
Example :
import java.util.*;
util is a subpackage created inside java package.

This is the general form of the package statement:


package pkg;
Accessing classes inside a package
Consider following two statements :
// import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import package.classname;

// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
Interface in Java
An interface in Java defines a contract that a class must adhere to. It contains
method signatures without implementations. The Classes that implement an
interface must provide concrete implementations for all the methods declared in that
interface. The Interfaces are used to achieve abstraction and support multiple
inheritances in Java.
Syntax
public interface MyInterface {
// Method signatures (without implementations)
void method1();
void method2();
}
Example of Interface in Java

interface ABC {
void myMethod();
}
class MyClass implements ABC {
public void myMethod() {
System.out.println("Method implementation in MyClass.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod();
}
}

output :
Method implementation in MyClass.

In Java, an interface is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. It defines a contract or a set of
abstract methods that a class implementing the interface must provide concrete implementations
for. Interfaces play a crucial role in achieving abstraction, encapsulation, and polymorphism in Java
programming. Here are the key aspects of interfaces in Java:

1. Declaration: An interface is declared using the interface keyword followed by the interface name
and a code block containing method signatures and constant declarations.
public interface MyInterface {

void method1( ); // Method signatures


void method2( ); // Method signatures

int CONSTANT1 = 10; // Constants


String CONSTANT2 = "Hello"; // Constants
default void defaultMethod( ) { // Default methods
// Method body
}

static void staticMethod( ) { // Static methods


// Method body
}
}
2. Method Signatures: Interfaces can contain method signatures without method bodies. These
methods are implicitly public and abstract, meaning they are meant to be implemented by
classes that implement the interface. For example:
public interface MyInterface {
void method1();
void method2();
}
3. Constants: Interfaces can declare constants, which are implicitly public, static, and final. These
constants can be accessed using the interface name followed by the constant name.
4. Default Methods: Java 8 introduced default methods in interfaces, which allow interfaces to
provide default implementations for methods. Classes that implement the interface can override
these default methods if needed.
5. Static Methods: Java 8 also introduced static methods in interfaces, which allow interfaces to
define utility methods that can be invoked without creating an instance of the interface.
6. Implementing Interfaces: A class implements an interface by providing concrete implementations
for all the abstract methods declared in the interface. The implements keyword is used to indicate
that a class implements an interface. For example:
7. Multiple Inheritance: Unlike classes, Java allows a class to implement multiple interfaces. This
enables a class to inherit behavior from multiple sources. For example:

public class MyClass implements Interface1, Interface2 {

// Class implementation

Access Protection
Access to a private member of a class is granted only to other members of that class. Packages
add another dimension to access control. As you will see, Java provides many levels of
protection to allow fine-grained control over the visibility of variables and methods within
classes, subclasses, and packages. Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods. Packages act as containers for
classes and other subordinate packages. Classes act as containers for data and code. The class is
Java’s smallest unit of abstraction.
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.
Anything declared public can be accessed from anywhere.
Anything declared private cannot be seen outside of its class. When a member does not have
an explicit access specification, it is visible to subclasses as well as to other classes in the same
package. This is the default access. If you want to allow an element to be seen outside your
current package, but only to classes that subclass your class directly, then declare that element
protected.

Multi-threaded Programming
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Java Thread Model
Thread exists in several states. A thread can be running. It can be ready when waiting for the
CPU time. A thread can be suspended, which temporarily suspends its activities. A suspended
thread can be resumed, allowing it to pick up where it left off. A thread can be blocked, waiting
for a resource. A thread can be terminated, which halts its execution immediately. A terminated
thread cannot be resumed.
Thread is a class in Java. It's part of the java.lang package, which means you don't need to import
it explicitly in your Java code.

The Thread Class and the Runnable Interface


Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface

Methods in Thread class:


Method Meaning
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
You can use the Thread class directly by extending it and overriding its run() method with your
custom logic, or you can create threads by implementing the Runnable interface and passing an
instance of your Runnable implementation to a Thread constructor.
Below is a basic example demonstrating how to implement threads in Java using both the Thread
class and the Runnable interface:

1. Using the Thread class:


class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}
2. Using the Runnable interface:thread
class MyRunnable implements Runnable {
public void run( ) {
System.out.println("Runnable running");
}
}
public class Main {
public static void main(String[ ] args) {
MyRunnable myRunnable = new MyRunnable( );
Thread thread = new Thread(myRunnable); // Creating a thread with the Runnable object
thread.start(); // Start the thread
}
}

Both examples create a thread that prints a message when it runs. The first example extends the
Thread class and overrides the run() method directly. The second example implements the
Runnable interface, defines the task in the run() method, and then passes an instance of the
MyRunnable class to the Thread constructor.

In both cases, calling the start() method initiates the execution of the thread, and the code inside
the run() method runs concurrently.

Multi-threading: Below is a simple example of thread-based multitasking in Java. In this example,


we create two threads that perform different tasks concurrently:
class Task1 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Task 1: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Task2 extends Thread {


public void run() {
for (char i = ‘A’; i <= ‘E’; i++) {
System.out.println("Task 2: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
// Create instances of the tasks
Task1 task1 = new Task1();
Task2 task2 = new Task2();

// Start the threads


task1.start();
task2.start();
}
}
Output:
Task 1: 0
Task 2: A
Task 1: 1
Task 2: B
Task 1: 2
Task 2: C
Task 1: 3
Task 2: D
Task 1: 4
Task 2: E

In this example:

● We define two classes Task1 and Task2, both of which extend the Thread class.
● Each class overrides the run() method to define its own task. Task1 prints numbers from
0 to 4, while Task2 prints letters from 'A' to 'E'.
● In the main() method, we create instances of Task1 and Task2 and start their execution by
calling the start() method.
● Both tasks run concurrently, and their output is interleaved because they execute
independently on separate threads.

You might also like