Java Quick revision

UNIT I



ParametersJavaC++
First ReleaseThe Java language came into existence on 23rd May 1995.The C++ language first came into existence in October 1985.
A stable form of ReleaseThe JDK 14 or Java SE was finally released on 17th March 2020.The C++ 17 was released back in December 2017.
FounderJames Gosling developed Java at Sun Microsystems.Bjarne Stroustrup developed C++ at Bell Labs back in 1979 in the form of an extension to the C language.
Platform DependencyThe Java bytecode can easily work on any given OS (operating system). It is very much platform-independent.The C++ language is platform-dependent. It means that we need to compile it for a different platform.
Official WebsiteThe official website for Java is oracle.com/javaThe official website for C++ is isocpp.org
Influenced ByThe C#, C++, Pascal, Ada 83, and many more languages have an influence on the Java language.Smalltalk, Simula, ML, C, ALGOL 68, Ada, and many more languages have an influence on the C++ language.
Influenced ToThe Java language gets influenced to develop the BeanShell, Python, PHP, Kotlin, J#, Hack, Groovy, Scala, C#, Clojure, and many more languages.The C++ language gets influenced to develop the Seed7, Rust, Python, PHP, Perl, Lua, JS++, Java, C99, and many more languages.
PortabilityIt is a portable language. We can easily run Java on any given platform.It is not a portable language. It is because the C++ language is platform-dependent.
Memory ManagementIt has system-controlled memory management.It has a manual form of memory management.
CompilationThe Java language is both- interpreted as well as combined.The C++ language is only a compiled language.
Virtual KeywordJava does not contain a virtual keyword.C++ contains a virtual keyword.
OverloadingJava only provides support for method overloading, and it does not come with operator overloading.C++ provides support for both- operator overloading as well as method overloading.
PointersJava provides very limited support for pointers.C++ provides strong support for pointers.
Multiple InheritanceJava provides support only for single inheritance.C++ can partially achieve multiple inheritance using interfaces. It provides support for both multiple as well as single inheritance.
TypeIt is only an object-oriented type of programming language.It is both- an object-oriented and a procedural programming language.
Global ScopeJava does not have support for global scope.C++ provides support for both namespace scope and global scope.
Management of ObjectsJava has automatic object management and also a garbage collection.C++ uses delete and supports manual object management using new and delete.
LibrariesThere is no support for direct native library calls. It uses the Java Native Interfaces.C++ comes with support for direct system library calls. Thus, it is very suitable for system-level programming.
Unions and StructuresThere is no support for Unions and Structures in Java.There is support for Unions and Structures in C++.
Passing ParameterJava provides support for only the technique of Pass by Value.C++ provides support for both Pass by Reference and Pass by Value.
Thread SupportIt provides support for documentation comment for source code (e.g, /**.. */).It does not come with built-in support for threads. It depends a lot on the third-party threading libraries.
Documentation CommentJava provides support for documentation comment for source code (e.g, /**.. */).C++ does not provide any support for documentation comments for the source code.


What is Java?

What is Java?

Java is a popular programming language, created in 1995.


It is owned by Oracle, and more than 3 billion devices run Java.


It is used for:


Mobile applications (specially Android apps)

Desktop applications

Web applications

Web servers and application servers

Games

Database connection

Why Use Java?

Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)

It is one of the most popular programming languages in the world

It has a large demand in the current job market

It is easy to learn and simple to use

It is open-source and free

It is secure, fast and powerful

It has huge community support (tens of millions of developers)

Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs

As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice versa


The internet is defined as a global network of linked computers, servers, phones, and smart appliances that communicate with each other using the transmission control protocol (TCP) standard to enable the fast exchange of information and files, along with other types of services.

What is World Wide Web?

World Wide Web, which is also known as a Web, is a collection of websites or web pages stored in web servers and connected to local computers through the internet. These websites contain text pages, digital images, audios, videos, etc. Users can access the content of these sites from any part of the world over the internet using their devices such as computers, laptops, cell phones, etc. The WWW, along with internet, enables the retrieval and display of text and media to your device.

What is World Wide Web

The building blocks of the Web are web pages which are formatted in HTML and connected by links called "hypertext" or hyperlinks and accessed by HTTP. These links are electronic connections that link related pieces of information so that users can access the desired information quickly. Hypertext offers the advantage to select a word or phrase from text and thus to access other pages that provide additional information related to that word or phrase.

A web page is given an online address called a Uniform Resource Locator (URL). A particular collection of web pages that belong to a specific URL is called a website, e.g., www.facebook.comwww.google.com, etc. So, the World Wide Web is like a huge electronic book whose pages are stored on multiple servers across the world.

Small websites store all of their WebPages on a single server, but big websites or organizations place their WebPages on different servers in different countries so that when users of a country search their site they could get the information quickly from the nearest server.

So, the web provides a communication platform for users to retrieve and exchange information over the internet. Unlike a book, where we move from one page to another in a sequence, on World Wide Web we follow a web of hypertext links to visit a web page and from that web page to move to other web pages. You need a browser, which is installed on your computer, to access the Web.

Difference between World Wide Web and Internet:

Some people use the terms 'internet' and 'World Wide Web' interchangeably. They think they are the same thing, but it is not so. Internet is entirely different from WWW. It is a worldwide network of devices like computers, laptops, tablets, etc. It enables users to send emails to other users and chat with them online. For example, when you send an email or chatting with someone online, you are using the internet.

What is World Wide Web

But, when you have opened a website like google.com for information, you are using the World Wide Web; a network of servers over the internet. You request a webpage from your computer using a browser, and the server renders that page to your browser. Your computer is called a client who runs a program (web browser), and asks the other computer (server) for the information it needs.

Java support system includes:


1. Java Development Kit (JDK):
The JDK is a software development kit provided by Oracle Corporation for developing Java applications.
It includes the Java compiler (javac) for compiling Java source code into bytecode.
The JDK also includes other tools and utilities for debugging, documentation generation, and more.
2. Java Virtual Machine (JVM):
The JVM is a key component of the Java platform. It is responsible for executing Java bytecode.
It provides platform independence, allowing Java programs to run on any system with a compatible JVM.
The JVM handles memory management, garbage collection, and runtime environment for Java applications.
3. Standard Library:
Java has a rich and comprehensive Standard Library (also known as the Java API) that provides a wide range of pre-built classes and functions.
The Standard Library includes classes for data structures, input/output operations, networking, multithreading, GUI development, and more.
Developers can leverage these classes to build robust and feature-rich applications without having to implement everything from scratch.
4. Integrated Development Environments (IDEs):
IDEs are software applications that provide comprehensive development environments for writing, debugging, and testing Java code.
Popular Java IDEs include Eclipse, IntelliJ IDEA, and NetBeans.
These IDEs offer features like code completion, syntax highlighting, debugging tools, and project management capabilities.
5. Build Tools:
Java build tools simplify the process of compiling, testing, and packaging Java applications.
Apache Maven and Gradle are popular build automation tools for Java projects.
These tools manage dependencies, automate build processes, and enable easy project configuration and deployment.
6. Java Community and Documentation:
Java has a vast and active community of developers, which provides support, forums, tutorials, and open-source libraries.
The official Java documentation, including the Java API documentation, is a valuable resource for understanding Java language features and classes.
7. Enterprise Support:
Java is widely used in enterprise applications, and there are various frameworks and technologies available to support Java-based enterprise development.
Java Enterprise Edition (Java EE) provides a set of specifications and APIs for building enterprise-scale applications.
Frameworks like Spring, JavaServer Faces (JSF), and Java Persistence API (JPA) simplify the development of enterprise applications.

What is the Java Runtime Environment?

The Java Runtime Environment (JRE) is software that Java programs require to run correctly. Java is a computer language that powers many current web and mobile applications. The JRE is the underlying technology that communicates between the Java program and the operating system. It acts as a translator and facilitator, providing all the resources so that once you write Java software, it runs on any operating system without further modifications.

Why is the JRE important?

A software program needs a runtime environment that provides access to memory and other system resources such as program files and dependencies. In the past, most software used the operating system directly as its runtime environment. However, this meant that developers had to write different code for each operating system that they wanted their applications to run on. The Java Runtime Environment (JRE) technology was created as a solution to this problem.

 

The JRE is actually one of three Java platform components that are required for any Java program to run successfully. The Java Development Kit (JDK) and Java Virtual Machine (JVM) are the other two components.

Java Development Kit

The JDK is a collection of software tools that you can use for developing Java applications. You can set up the JDK in your development environment by downloading and installing it. Select the JDK software version that matches the Java version you want to use. For example, Java Standard Edition, or Java SE, requires the Java SE JDK.

Java Virtual Machine

The JVM is software that runs the Java program line by line. Developers configure the JVM settings to manage program resources when the Java application runs. For example, you can change the JVM memory setting and check how much internal memory your Java applications use at runtime.

Role of the JRE in Java programming language

The JRE combines the Java code that you create by using the JDK with additional built-in code called libraries. It then creates a JVM instance, or local copy, that finally runs the Java programs. JVMs are available for multiple operating systems, and the JRE generates a single copy of your Java code that runs on all types of JVMs. In this way, the JRE facilitates platform independence for Java applications. You can write them once and run them anywhere.

Difference between the JRE, JVM, and JDK

The JDK is a software layer above the JRE that contains a compiler, a debugger, and other tools commonly found in any software development environment. You write code in English-like syntax in the JDK. The JDK compiles it and passes the byte code to the JRE. In contrast, the JRE contains class libraries, supporting files, and the JVM. It uses these software components to run the byte code on any device.

How does the JRE work?

The Java Runtime Environment (JRE) runs on top of the operating system, providing additional Java-specific resources. The Java Development Kit (JDK) and JRE interact to create a sustainable runtime environment that runs Java program files on any machine. The JRE uses three core components to work.

ClassLoader

Java class libraries contain collections of pre-written code that you can call as needed. They simplify the job of Java developers by providing built-in methods for common and non-trivial tasks such as taking input from users, displaying output to users, and more. All Java programs reference several class libraries. The Java ClassLoader dynamically loads all class files necessary into the Java Virtual Machine (JVM) on demand.

Bytecode verifier

The JDK has a compiler that converts the English-like code you write into a machine language version called Java bytecode. They bytecode verifier in the JRE checks the format and accuracy of the Java code before loading it into the JVM. For example, if the code violates system integrity or access rights, the JRE will not load the class file.

Interpreter

After the bytecode successfully loads, the Java interpreter creates the JVM instance that runs the Java program on the underlying machine.


Structure of Java Program

Java is an object-oriented programming, platform-independent, and secure programming language that makes it popular. Using the Java programming language, we can develop a wide variety of applications. So, before diving in depth, it is necessary to understand the basic structure of Java program in detail. In this section, we have discussed the basic structure of a Java program. At the end of this section, you will able to develop the Hello world Java program, easily.


What Are Tokens In Java?



In Java, tokens are the basic building blocks of a program. They are the smallest individual units of a program that have meaning to the compiler and are used to represent the various elements of a program, such as keywords, identifiers, operators, and literals.

Here are the different types of java tokens that can be found:


Keywords:

These are reserved words that have a specific meaning in the Java language. Examples of keywords in Java include class, public, private, if, else, while, for, switch, case, break, continue, return, and static, among others.

In Java, a keyword is a reserved word that has a specific meaning and purpose within the language. Keywords are used to define various constructs, such as control flow statements, data types, access modifiers, and more.

As a token in Java, a keyword is a sequence of characters that are treated as a single unit by the Java compiler. When Java code is compiled, the compiler recognizes keywords as special words with a predefined meaning and function within the language.

Examples of Java keywords include:

  • public, private, protected: access modifiers used to control access to class members.
  • class, interface, enum: used to define different types of Java classes.
  • if, else, switch, while, do, for: used to define control flow statements.
  • int, float, boolean, char: used to define data types.

As a programmer, it’s important to be familiar with Java keywords and their usage in order to write correct and effective Java code.

Identifiers:

These are names that are used to identify variables, methods, classes, and other elements of a program. An identifier must start with a letter or underscore and can contain letters, digits, and underscores. Identifiers are case-sensitive in Java.

In Java, an identifier is a sequence of characters used to name a variable, method, class, or another program element. Identifiers are used to refer to these program elements throughout the code, allowing programmers to access and manipulate them.

An identifier in Java must follow certain rules:

  1. It can only contain letters, digits, underscores (_), and dollar signs ($).
  2. It must begin with a letter, an underscore (_), or a dollar sign ($).
  3. It cannot be a Java keyword.

Examples of valid identifiers in Java include:

  • myVariable
  • _myVariable
  • $myVariable
  • MyClass
  • myMethod

Identifiers are case-sensitive in Java, meaning that myVariable and myvariable are considered two different identifiers.

It’s important to choose meaningful and descriptive names for identifiers to make the code easier to read and understand. Good naming conventions also help make the code more maintainable and easier to modify java tokens in the future.

Operators:

These are symbols or token bus that are used to perform operations on operands, such as arithmetic operations (+, -, *, /, %), logical operations (&&, ||, !), relational operations (==, !=, <, >, <=, >=), and assignment operations (=, +=, -=, *=, /=, %=, etc.).

In Java, an operator is a symbol that represents a specific action or computation that can be performed on one or more operands. Operators are used to manipulate and compare data values in Java programs.

Java operators can be classified into several categories based on their functionality:

  1. Arithmetic Operators: Used to perform arithmetic operations such as addition, subtraction, multiplication, division, and modulo. Examples: +, -, *, /, %.
  2. Relational Operators: Used to compare values and determine the relationship between them. Examples: ==, !=, <, >, <=, >=.
  3. Logical Operators: Used to perform logical operations on boolean values. Examples: && (logical AND), || (logical OR), ! (logical NOT).
  4. Bitwise Operators: Used to perform bitwise operations on binary values. Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift), >>> (unsigned right shift).
  5. Assignment Operators: Used to assign values to variables. Examples: =, +=, -=.

Separators:

These are symbols that are used to separate different parts of a program, such as commas (,), semicolons (;), parentheses (()), braces ({ }), and brackets ([]).

In Java, separators are characters used to separate or group parts of a Java program. Separators are not operators and do not perform any operations on data values.

Java has several types of separators:

  1. Semicolons (;): Used to separate statements in Java. Every statement in Java must end with a semicolon.
  2. Commas (,): Used to separate multiple arguments or parameters in method calls or definitions or to separate multiple variable declarations.
  3. Parentheses (( and )): Used to group expressions, define method parameters, and control the order of evaluation.
  4. Braces ({ and }): Used to define a block of code, such as a method body or a class definition.
  5. Brackets ([ and ]): Used to define arrays or to access individual elements of an array.
  6. Periods (.): Used to access class members or invoke methods on objects.
  7. Colon (:): Used in switch statements and for-each loops to separate case values or to define iteration variables.

Separators play an important role in structuring and organizing Java code, and using them correctly is crucial for writing correct and readable programs.

Literals:

These are values that are directly specified in the program, such as integer literals (e.g., 42), floating-point literals (e.g., 3.14), boolean literals (true or false), character literals (e.g., ‘a’), and string literals (e.g., “Hello, world!”).

In Java, a literal is a notation used to represent a fixed value in the source code. Literals are used to represent values of data types such as integers, floating-point numbers, characters, and strings.

Java supports several types of literals:

  1. Integer literals: Used to represent integer values, such as 42 or 0xFF.
  2. Floating-point literals: Used to represent floating-point values, such as 3.14159 or 1.0e-6.
  3. Boolean literals: Used to represent boolean values, such as true or false.
  4. Character literals: Used to represent single characters, enclosed in single quotes, such as ‘a’ or ‘9’.
  5. String literals: Used to represent sequences of characters enclosed in double quotes, such as “Hello, World!”.
  6. Null literal: Used to represent a reference that does not refer to any object, represented by the keyword null.


Literals are used to initialize variables and constants, as well as to specify values in expressions and statements. They are constant values and cannot be changed during the execution of the program.

It’s important to choose the appropriate type of literal to represent a value to avoid data loss or unexpected results in the program.

When a Java program is compiled, the compiler breaks it down into a sequence of token bus, which are then used to generate the executable code.

https://www.youtube.com/watch?v=PwluCd0drqY

What is statement in Java?

In Java, a statement is an executable instruction that tells the compiler what to perform. It forms a complete command to be executed and can include one or more expressions. A sentence forms a complete idea that can include one or more clauses.

Types of Statements

Java statements can be broadly classified into the following categories:

  • Expression Statements
  • Declaration Statements
  • Control Statements

Declaration Statements

In declaration statements, we declare variables and constants by specifying their data type and name. A variable holds a value that is going to use in the Java program.

Control Statement

Control statements decide the flow (order or sequence of execution of statements) of a Java program. In Java, statements are parsed from top to bottom. Therefore, using the control flow statements can interrupt a particular section of a program based on a certain condition.


There are the following types of control statements:

  1. Conditional or Selection Statements
    • if Statement
    • if-else statement
    • if-else-if statement
    • switch statement
  2. Loop or Iterative Statements
    • for Loop
    • while Loop
    • do-while Loop
    • for-each Loop
  3. Flow Control or Jump Statements
    • return
    • continue
    • break

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.

What is JVM

It is:

  1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
  3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JVM provides definitions for the:

  • Memory area
  • Class file format
  • Register set
  • Garbage-collected heap
  • Fatal error reporting etc.

constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution, i.e., the value is variable.

Understanding Constants

constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant.

variable is a data item whose value can change during the program’s execution. Thus, as its name implies – the value can vary.

Constants are used in two ways. They are:

  1. literal constant
  2. defined constant


type Casting in Java

In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. In this section, we will discuss type casting and its types with proper examples.

Type casting

Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are two types of type casting:

  • Widening Type Casting
  • Narrowing Type Casting

Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes place when:

  • Both data types must be compatible with each other.
  • The target type must be larger than the source type.

Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error.

Operators in Java

There are many types of operators in Java which are given below:

  • Unary Operator,
  • Arithmetic Operator,
  • Shift Operator,
  • Relational Operator,
  • Bitwise Operator,
  • Logical Operator,
  • Ternary Operator and
  • Assignment Operator.
Unary: postfix expr++ expr--
    prefix ++expr --expr +expr -expr ~ !
Arithmetic: * / % + -
Shift: << >> >>>
Relational: < > <= >= instanceof == !=
Bitwise: ^
Logical: && ||
Ternary: ? :
Assignment:  = += -= *= /= %= &= ^= |= <<= >>= >>>=

Loops in Java


Java Simple for Loop

A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:

  1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
  2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
  3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
  4. Statement: The statement of the loop is executed each time until the second condition is false.

  5. Java Nested for Loop

    If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.

Java for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined variable.

Java Labeled For Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.



import java.io.*;


class GFG {

public static void main (String[] args) {

int i=0;

while (i<=10)

{

System.out.println(i);

i++;

}

}

}

NEXT EXAMPLE:


import java.io.*;

class GFG {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}
NEXT EXAMPLE 
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
public static void main (String[] args) {
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
NEXT EXAMPLE


import java.io.*;

class GFG {
public static void main (String[] args) {
while (true)
{
// statement 
}
}
}
NESTED LOOP EXAMPLE BELOW
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
public static void main (String[] args) {
for(int i = 0; i < 3; i++){
for(int j = 0; j < 2; j++){
System.out.println(i);
}
System.out.println();
}
}
}

UNIT 2

Defining a Class in Java

Java provides a reserved keyword class to define a class. The keyword must be followed by the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:

  1. Modifiers: A class can be public or has default access.
  2. class keyword: The class keyword is used to create a class.
  3. Class name: The name must begin with an initial letter (capitalized by convention).
  4. Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  6. Body: The class body surrounded by braces, { }.
// class definition  
public class Calculate {  
     
   // instance variables  
   int a;  
   int b;  
  
   // constructor to instantiate  
   public Calculate (int x, int y) {  
      this.a = x;  
      this.b = y;  
   }  
  
   // method to add numbers  
   public int add () {  
      int res = a + b;  
      return res;  
   }  
  
   // method to subtract numbers  
   public int subtract () {  
      int res = a - b;  
      return res;  
   }  
  
   // method to multiply numbers  
   public int multiply () {  
      int res = a * b;  
      return res;  
   }  
  
   // method to divide numbers  
   public int divide () {  
      int res = a / b;  
      return res;  
   }  
  
  
   // main method  
   public static void main(String[] args) {  
      // creating object of Class  
      Calculate c1 = new Calculate(45, 4);  
        
      // calling the methods of Calculate class  
      System.out.println("Addition is :" + c1.add());  
      System.out.println("Subtraction is :" + c1.subtract());  
      System.out.println("Multiplication is :" + c1.multiply());  
      System.out.println("Division is :" + c1.divide());  
  
  
   }  

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.


How to Create Object in Java

The object is a basic building block of an OOPs language. In Java, we cannot execute any program without creating an object. There is various way to create an object in Java that we will discuss in this section, and also learn how to create an object in Java.

Java provides five ways to create an object.

  • Using new Keyword
  • Using clone() method
  • Using newInstance() method of the Class class
  • Using newInstance() method of the Constructor class
  • Using Deserialization

Using new Keyword

Using the new keyword is the most popular way to create an object or instance of the class. When we create an instance of the class by using the new keyword, it allocates memory (heap) for the newly created object and also returns the reference of that object to that memory. The new keyword is also used to create an array. 


CreateObjectExample1.java


public class CreateObjectExample1   

{    

void show()    

{    

System.out.println("WELCOME TO VIKATU");    

}    

public static void main(String[] args)   

{    

//creating an object using new keyword   

CreateObjectExample1 obj = new CreateObjectExample1();   

//invoking method using the object  

obj.show();    

}    

}   


Using clone() Method

The clone() method is the method of Object class. It creates a copy of an object and returns the same copy. The JVM creates a new object when the clone() method is invoked. It copies all the content of the previously created object into new one object. Note that it does not call any constructor. We must implement the Cloneable interface while using the clone() method. The method throws CloneNotSupportedException exception if the object's class does not support the Cloneable interface. The subclasses that override the clone() method can throw an exception if an instance cannot be cloned.


Accessing Class Members in Java

Java classes consist of various variables and instance members (or methods). Before accessing class members in Java like variables and instance members, it is essential to declare them. So, let us first understand how to declare variables and methods.

Declaration of Instance Variables

All variables which are defined in a class are known as instance variables as each object of the class will have its own copy of the variables. Hence the data in various objects are unique and are separate from one another.

When declaring variables, there are three Access Level Modifiers. These are:


ModifierAccess Level
ClassPackageSubclassWorld
publicYYYY
protectedYYYN
privateYNNN

The public modifier is the default modifier and the easiest access specifier. It is used to specify that the member is visible to all the classes and can be accessed from everywhere. We should declare public members only if such access does not produce undesirable results. These act like secrets which can be known by anybody.

The protected modifier specifies that the member can be accessed by its own members or the members of its sub-class only. These act as family secrets which only the concerned family knows but no outsiders know about it.

The private modifier is the most restrictive access level. It specifies that the members can only be accessed by its own class i.e. the class where it is defined. This is used with those variables or methods that contain information that need not be accessed by an outsider as it could make the program inconsistent. This modifier is the main way by which an object encapsulates itself and hides its data from the outside world. Hence, these act as secrets which we do not tell anybody.

The syntax for declaration is as follows:

Access_modifier data_type var_name;

For example: public int students;

Declaration of Methods:

A method is that part of the program that contains the code regarding the action to be taken or the task to be carried out. A class can contain any number of functions depending on the functionality of that program and each function can be called any number of times during program execution. The syntax to declare a method is as follows:

Access_modifier data_type method_name ([parameter1, parameter2 …]) {

// Body of the method

}

To execute a method you can invoke or call it from other methods as and when needed.

Accessing Class Members in Java-Instance Variables and Methods using Objects

Instance variables and methods are accessed via objects with the help of a dot (.) operator. The dot operator creates a link between the name of the instance variable and the name of the class with which it is used.

For example if salary class had a variable named basicsal and we wanted to initialize it to 10000, then we would use the following code:

s.basicsal = 10000;

Where, s is the name of the object and basicsal is the instance variable.

Now let us take up an example.

 class Employee
{
      String name;
      int age;
      float bsal, gsal;

      public void acceptDetails(String n, int a, int s)
      {
            name = n;
            age = a;
            bsal = s;
      }
      public void showData()
      {
            System.out.println("Employee Name = " + name);
            System.out.println("Employee Age = " + age);
            System.out.println("Employee Basic Salary = " + bsal);
            System.out.println("Employee Gross Salary = " + gsal);
      }
      void cal()            // public by default
      {
            gsal = bsal - (bsal*5/100);
      }

      public static void main(String args [])
      {
            Employee e1 = new Employee();      // object e1 created
            e1.acceptDetails("Nancy", 28, 12000);
            e1.cal();
            e1.showData();
      }
}

What are Constructors in Java?

In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.


// Java Program to demonstrate

// Constructor

import java.io.*;


// Driver Class

class Geeks {


// Constructor

Geeks()

{

super();

System.out.println("Constructor Called");

}


// main function

public static void main(String[] args)

{

Geeks geek = new Geeks();

}

}

Need of Constructors in Java

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).


Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

1. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.


// Java Program to demonstrate

// Default Constructor

import java.io.*;


// Driver class

class GFG {


// Default Constructor

GFG() { System.out.println("Default constructor"); }


// Driver function

public static void main(String[] args)

{

GFG hello = new GFG();

}

}

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.


// Java Program for Parameterized Constructor

import java.io.*;

class Geek {

// data members of the class.

String name;

int id;

Geek(String name, int id)

{

this.name = name;

this.id = id;

}

}

class GFG {

public static void main(String[] args)

{

// This would invoke the parameterized constructor.

Geek geek1 = new Geek("avinash", 68);

System.out.println("GeekName :" + geek1.name

+ " and GeekId :" + geek1.id);

}

}

3. Copy Constructor in Java

Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.

// Java Program for Copy Constructor

import java.io.*;


class Geek {

// data members of the class.

String name;

int id;


// Parameterized Constructor

Geek(String name, int id)

{

this.name = name;

this.id = id;

}


// Copy Constructor

Geek(Geek obj2)

{

this.name = obj2.name;

this.id = obj2.id;

}

}

class GFG {

public static void main(String[] args)

{

// This would invoke the parameterized constructor.

System.out.println("First Object");

Geek geek1 = new Geek("avinash", 68);

System.out.println("GeekName :" + geek1.name

+ " and GeekId :" + geek1.id);


System.out.println();


// This would invoke the copy constructor.

Geek geek2 = new Geek(geek1);

System.out.println(

"Copy Constructor used Second Object");

System.out.println("GeekName :" + geek2.name

+ " and GeekId :" + geek2.id);

}

}

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Different ways to overload the method

There are two ways to overload the method in java

  1. By changing number of arguments
  2. By changing the data type

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

  1. class Adder{  
  2. static int add(int a,int b){return a+b;}  
  3. static int add(int a,int b,int c){return a+b+c;}  
  4. }  
  5. class TestOverloading1{  
  6. public static void main(String[] args){  
  7. System.out.println(Adder.add(11,11));  
  8. System.out.println(Adder.add(11,11,11));  
  9. }}  

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.

  1. class Adder{  
  2. static int add(int a, int b){return a+b;}  
  3. static double add(double a, double b){return a+b;}  
  4. }  
  5. class TestOverloading2{  
  6. public static void main(String[] args){  
  7. System.out.println(Adder.add(11,11));  
  8. System.out.println(Adder.add(12.3,12.6));  
  9. }}  
  10. What are static members of a Java class?

In Java, static members are those which belongs to the class and you can access these members without instantiating the class.

The static keyword can be used with methods, fields, classes (inner/nested), blocks.

Static Methods − You can create a static method by using the keyword static. Static methods can access only static fields, methods. To access static methods there is no need to instantiate the class, you can do it just using the class name as 

public class MyClass {
   public static void sample(){
      System.out.println("Hello");
   }
   public static void main(String args[]){
      MyClass.sample();
   }
}

 Static Fields − You can create a static field by using the keyword static. The static fields have the same value in all the instances of the class. These are created and initialized when the class is loaded for the first time. Just like static methods you can access static fields using the class name (without instantiation).

public class MyClass {
   public static int data = 20;
   public static void main(String args[]){
      System.out.println(MyClass.data);
   }
   Java Arrays with Answers
   27
}
Static Blocks − These are a block of codes with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

Inheritance in Java

nheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.



 

  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.


class Animal{  

void eat(){System.out.println("eating...");}  

}  

class Dog extends Animal{  

void bark(){System.out.println("barking...");}  

}  

class TestInheritance{  

public static void main(String args[]){  

Dog d=new Dog();  

d.bark();  

d.eat();  

}}  


Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

class Animal{  

void eat(){System.out.println("eating...");}  

}  

class Dog extends Animal{  

void bark(){System.out.println("barking...");}  

}  

class BabyDog extends Dog{  

void weep(){System.out.println("weeping...");}  

}  

class TestInheritance2{  

public static void main(String args[]){  

BabyDog d=new BabyDog();  

d.weep();  

d.bark();  

d.eat();  

}}  

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

class Animal{  

void eat(){System.out.println("eating...");}  

}  

class Dog extends Animal{  

void bark(){System.out.println("barking...");}  

}  

class Cat extends Animal{  

void meow(){System.out.println("meowing...");}  

}  

class TestInheritance3{  

public static void main(String args[]){  

Cat c=new Cat();  

c.meow();  

c.eat();  

//c.bark();//C.T.Error  

}}  

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism
  • Rules for Java Method Overriding

    1. The method must have the same name as in the parent class
    2. The method must have the same parameter as in the parent class.
    3. There must be an IS-A relationship (inheritance)

//Java Program to illustrate the use of Java Method Overriding  
//Creating a parent class.  
class Vehicle{  
  //defining a method  
  void run(){System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle{  
  //defining the same method as in the parent class  
  void run(){System.out.println("Bike is running safely");}  
  
  public static void main(String args[]){  
  Bike2 obj = new Bike2();//creating object  
  obj.run();//calling method  
  }  
}  







Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component’s visibility low is more maintainable than one that exposes its component more. You’re not going to know it upfront, but when redesigning the application, you’re going to miss it terribly.

You end up patching and repeating the same errors, as maintaining backward compatibility is a must-have requirement for many applications. You will not do much because the class and interfaces are tightly integrated with a lot of other applications. Java has always prioritized encapsulation, providing access modifiers of support from the very beginning. By making them public, package-private or private provides ways to monitor the visibility of some type, such as class or interface.

Below are some rules to control the visibility:

  1. A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.
  2. A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.
  3. The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.
  4. Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.
  5. If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change.
How to control Visibility of Class or Interface in Java?

In addition to decreasing class or interface visibility using the access modifier, based on your runtime environment, there are many other ways to do so. At the component level, such as Websphere, Weblogic, or JBoss in Application Server, an interface class may be proxied or wrapped to reduce external visibility.

No matter what you do, there will still be certain types that need to be exposed to the outside world, but you can always handle them with proxy or wrapper. Although client programs will load proxied implementation classes, an immutable proxy or wrapper would often be obtained.

For example, the Java Servlet API (javax.servlet) getServletContext() returns an implementation of javax.servlet.ServletContext, which is typically an immutable proxy to satisfy the ServletContext framework promises. It is most possible that a separate version of the javax.servlet.ServletContext specification operates on the application server.

It is possible to use a similar pattern in the implementation of other externally accessible interfaces, e.g. Javax.ejb.EJBContext, Javax.ejb.TimerService, ServletRequest, ServletResponse, etc. To support these global interfaces, various application servers can use various applications.

JDK Example of Controlling Visibility of Java Class

EnumSet class is another fascinating example of managing visibility. In order to prevent instantiation, the Java designer made the abstract class and provided factory methods as the only way to create an instance of that class, e.g. Methods from EnumSet.of() or EnumSet.noneOf().

Internally, in the form of RegularEnumSet and JumboEnumSet, they have two separate implementations, which are automatically selected based on the size of the main universe by static factory methods.

For instance, if the number of values in Enum is less than 64, then RegularEnumSet is used, otherwise, the JumboEnumSet instance is returned. The beauty of this design is that package-private means that consumers have no idea about any of these implementations.

 UNIT III

Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.



Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.

Disadvantages

  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Example of Java Array

//Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Example of Multidimensional Java Array

//Java Program to illustrate the use of multidimensional array class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }}

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

  1. By string literal
  2. By new keyword

Java String Example

public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by Java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }}

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws the ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

  • Vector is synchronized.
  • Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector Example


import java.util.*; public class VectorExample { public static void main(String args[]) { //Create a vector Vector<String> vec = new Vector<String>(); //Adding elements using add() method of List vec.add("Tiger"); vec.add("Lion"); vec.add("Dog"); vec.add("Elephant"); //Adding elements using addElement() method of Vector vec.addElement("Rat"); vec.addElement("Cat"); vec.addElement("Deer"); System.out.println("Elements are: "+vec); } }


Wrapper classes in Java

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java

Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the wrapper classes.

  • Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
  • Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
  • Synchronization: Java synchronization works with objects in Multithreading.
  • java.util package: The java.util package provides the utility classes to deal with objects.
  • Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

Java Wrapper classes Example

//Java Program to convert all primitives into its corresponding //wrapper objects and vice-versa public class WrapperExample3{ public static void main(String args[]){ byte b=10; short s=20; int i=30; long l=40; float f=50.0F; double d=60.0D; char c='a'; boolean b2=true; //Autoboxing: Converting primitives into objects Byte byteobj=b; Short shortobj=s; Integer intobj=i; Long longobj=l; Float floatobj=f; Double doubleobj=d; Character charobj=c; Boolean boolobj=b2; //Printing objects System.out.println("---Printing object values---"); System.out.println("Byte object: "+byteobj); System.out.println("Short object: "+shortobj); System.out.println("Integer object: "+intobj); System.out.println("Long object: "+longobj); System.out.println("Float object: "+floatobj); System.out.println("Double object: "+doubleobj); System.out.println("Character object: "+charobj); System.out.println("Boolean object: "+boolobj); //Unboxing: Converting Objects to Primitives byte bytevalue=byteobj; short shortvalue=shortobj; int intvalue=intobj; long longvalue=longobj; float floatvalue=floatobj; double doublevalue=doubleobj; char charvalue=charobj; boolean boolvalue=boolobj; //Printing primitives System.out.println("---Printing primitive values---"); System.out.println("byte value: "+bytevalue); System.out.println("short value: "+shortvalue); System.out.println("int value: "+intvalue); System.out.println("long value: "+longvalue); System.out.println("float value: "+floatvalue); System.out.println("double value: "+doublevalue); System.out.println("char value: "+charvalue); System.out.println("boolean value: "+boolvalue); }}

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

  • How to declare an interface?

    An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Java Interface Example


interface printable{ void print(); } class A6 implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A6 obj = new A6(); obj.print(); } }

Java Package

java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

//save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }


Java Naming Convention

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of Naming Conventions in Java

By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.

CamelCase in Java naming conventions

Java follows camel-case syntax for naming the class, interface, method, and variable.

If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.

In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any Java program the java.lang package is imported by default. We need not to write the package name at the top of the program. We can also create our own package by providing the name that we want. In this section, we will learn how to create a package in Java.

We use package for the following reasons:

  • The package makes the search easier for the classes and interfaces.
  • It provides a fully qualified name that avoids naming conflicts.
  • It also controls access.
  • It organizes classes in a folder structure.
  • It improves code reusability.
  • Programmer can group classes and interfaces into a related package.

Creating a Package

To create a package, follow the steps given below:

  • Choose a package name according to the naming convention.
  • Write the package name at the top of every source file (classes, interface, enumeration, and annotations).
  • Remember that there must be only one package statement in each source file.

Package Naming Convention

We follow the naming convention rules to name a package. Java has some predefined packages and also allows us to create our own package. So, it is possible that a programmer can create a class with the same name as a package that already contains that type in a predefined package.

Let's take an example of the Rectangle class.

Suppose, a programmer creates a class with the name Rectangle in the package shape. The class with the same name is already present in java.awt package. The compiler allows both classes if they belong to the different packages. The fully qualified name of each class contains the package name that differentiate both Rectangle classes. Therefore, the package name of the user-defined class will be shape.Rectangle and the package name of the predefined class will be java.awt.Rectangle.

  • Package name must be in lower case that avoids conflict with the name of classes and interfaces.
  • Organizations used their internet domain name to define their package names. For example, com.javatpoint.mypackage. Sometimes, the organization also uses the region after the company name to name the package. For example, com.javatpoint.region.mypackage.
  • We use underscore in the package name if the domain name contains hyphen or other special characters or package names begin with a digit or reserved keyword.

UNIT IV

Java Threads

  1. By extending Thread class
  2. By implementing Runnable interface.
  3. Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

 Java Thread Example by extending Thread class

class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

The stop() method of thread class terminates the thread execution. Once a thread is stopped, it cannot be restarted by start() method.
public final void stop()
public final void stop(Throwable obj)

 

Priority of a Thread

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.

Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:

  1. New
  2. Active
  3. Blocked / Waiting
  4. Timed Waiting
  5. Terminated
  6. Explanation of Different Thread States

    New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution.

    Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is runnable, and the other is running.

    • Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
      A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
    • Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.

    Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state.

    For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.

    When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.

    If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.

    Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.

    Terminated: A thread reaches the termination state because of the following reasons:

    • When a thread has finished its job, then it exists or terminates normally.
    • Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.

Synchronization in Java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization?

The synchronization is mainly used to

  1. To prevent thread interference.
  2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

  1. Process Synchronization
  2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  1. Mutual Exclusive
    1. Synchronized method.
    2. Synchronized block.
    3. Static synchronization.
  2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:

  1. By Using Synchronized Method
  2. By Using Synchronized Block
  3. By Using Static Synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.





UNIT V

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

  • It works at client side so less response time.
  • Secured
  • It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

  • Plugin is required at client browser to execute applet.

Lifecycle of Java Applet

  1. Applet is initialized.
  2. Applet is started.
  3. Applet is painted.
  4. Applet is stopped.
  5. Applet is destroyed.



Local Applet

Local Applet is written on our own, and then we will embed it into web pages. Local Applet is developed locally and stored in the local system. A web page doesn't need the get the information from the internet when it finds the local Applet in the system. It is specified or defined by the file name or pathname. There are two attributes used in defining an applet, i.e., the codebase that specifies the path name and code that defined the name of the file that contains Applet's code.

Remote Applet

A remote applet is designed and developed by another developer. It is located or available on a remote computer that is connected to the internet. In order to run the applet stored in the remote computer, our system is connected to the internet then we can download run it. In order to locate and load a remote applet, we must know the applet's address on the web that is referred to as Uniform Recourse Locator(URL).

Types of Applets in Java

Difference Between a Java Application and a Java Applet

Java application and Java applet both are Java programs, but there is a slight difference between them. Like in any program, the execution of the Java application always begins with the main( ) method, while in the case of an applet, initialization takes through the init( ). There is no need to invoke the main( ) method.

Java applications are types of stand-alone applications that run directly on the underlying operating system with the help of virtual machine. These perform various general operations for their users and do not require any APIs or browsers enabled by Java. On the other hand, the applets are small programs that can be embedded into a web page. The applets are used to make the website more dynamic and entertaining. We can use the OBJECT or APPLET tag to embed an applet on an HTML page and manage it on any web server.

A web browser that is compatible with Java can easily run applets. Hardware and operating system of the devices does not effect Java applets. One thing is clear and that is the overall appearance of Java applications are always the same on different OS. If the affected system browser has a well-installed JVM, then it can easily work with the help of these JVMs.

Java Application

Java application is basically a Java program (collection of instructions) that runs stand alone in a client or server, and works on an underlying OS (operating system) that receives virtual machine support. Graphical User Interface (GUI) is not required for execution of a Java application.

Java Application Features

  • It resembles Java programs strongly.
  • We do not require any web browser for the execution of these programs. Execution can be easily done via the local system.
  • The implementation of these applications requires main( ) function.
  • The local file systems and networks are fully accessed by these applications.

Java Applet

The Java applet works on the client side, and runs on the web browser. It is a Java application that the user can easily embed on a web page.

Java Applet Features

  • Java applet is a small and easy-to-write Java program.
  • One can easily install Java applet along with various HTML documents.
  • One needs a web browser (Java based) to use applets.
  • Applet do not have access to the network or local disk and can only access browser-specific services.
  • It cannot perform system operations on local machines.
  • Java applet cannot establish access to local system.

Writing Applets 

The Writing Applets trail will cover everything you need to know about writing Java applets.

Overview of Applets gives a complete overview of how applets work, how you write an applet, and exactly what applets can and can't do. You should thoroughly understand this overview before going further in this trail.

Creating an Applet User Interface will talk about the various ways of getting input from the user and giving information to the user. It will include discussions of applet parameters, properties, user interface, sound, and interactive user input.

Communicating with Other Programs will talk about interapplet communication, as well as various forms of communication with other types of programs, such as server-side applications.

Understanding Applet Capabilities and Restrictions will give details about the security restrictions that can be placed on applets, how to find out what restrictions a particular browser puts on applets, and some safe ways of getting around applet restrictions. It will also discuss the capabilities that applets have that applications currently don't have, or that you might not expect applets to have.

Finishing an Applet describes the characteristics of a high-quality applet.


// A Hello World Applet

// Save file as HelloWorld.java


import java.applet.Applet;

import java.awt.Graphics;


// HelloWorld class extends Applet

public class HelloWorld extends Applet 

{

// Overriding paint() method

@Override

public void paint(Graphics g) 

{

g.drawString("Hello World", 20, 20);

}

}


 

There are five methods of an applet life cycle, and they are:

  • init(): The init() method is the first method to run that initializes the applet. It can be invoked only once at the time of initialization. The web browser creates the initialized objects, i.e., the web browser (after checking the security settings) runs the init() method within the applet.
  • start(): The start() method contains the actual code of the applet and starts the applet. It is invoked immediately after the init() method is invoked. Every time the browser is loaded or refreshed, the start() method is invoked. It is also invoked whenever the applet is maximized, restored, or moving from one tab to another in the browser. It is in an inactive state until the init() method is invoked.
  • stop(): The stop() method stops the execution of the applet. The stop () method is invoked whenever the applet is stopped, minimized, or moving from one tab to another in the browser, the stop() method is invoked. When we go back to that page, the start() method is invoked again.
  • destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the applet window is closed or when the tab containing the webpage is closed. It removes the applet object from memory and is executed only once. We cannot start the applet once it is destroyed.
  • paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like circle, square, trapezium, etc., in the applet. It is executed after the start() method and when the browser or applet windows are resized.
  • Applet Life Cycle Working

    • The Java plug-in software is responsible for managing the life cycle of an applet.
    • An applet is a Java application executed in any web browser and works on the client-side. It doesn't have the main() method because it runs in the browser. It is thus created to be placed on an HTML page.
    • The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
    • The paint() method belongs to the awt.Component class.
    • In Java, if we want to make a class an Applet class, we need to extend the Applet
    • Whenever we create an applet, we are creating the instance of the existing Applet class. And thus, we can use all the methods of that class.


How to build a Web Application Using Java

Java is one of the most used programming languages for developing dynamic web applications. A web application is computer software that utilizes the web browser and technologies to perform tasks over the internet. A web application is deployed on a web server.

Java provides some technologies like Servlet and JSP that allow us to develop and deploy a web application on a server easily. It also provides some frameworks such as Spring, Spring Boot that simplify the work and provide an efficient way to develop a web application. They reduce the effort of the developer.

We can create a website using static HTML pages and style them using CSS, but we need server-side technology when we want to create a dynamic website.

In this section, we will see how to create a website using Java Servlets and HTML. Further, we will see how these technologies are useful for developing a web application.

FOR MORE INFORMATION YOU CAN VISIT THIS





Comments

Popular posts from this blog

Quick Revision for Multimedia and Animation - Vikatu

Quick revision for software engineering by vikatu