Oops Unit 4
Oops Unit 4
● 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.
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:
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
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
// 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
// Class 1
// Parent class
class Parent {
}
// Class 2
// Child class
class Child extends Parent {
}
// Class 3
// Main class
class GFG {
// 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");
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.
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.
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
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.
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
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).
import java.io.*;
class ABC {
public static void main(String[ ] args)
{
String s1 = "java";
s1.concat(" rules");
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.
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.
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.
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.
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.
// 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 {
// 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.
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.
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.