Internet and java
Internet and java
Java is strongly associated with the Internet because the first application program written in
Java was HotJava,a browser to run the applet on Internet . So the Internet users use the Java
to create the applet programs and run them locally using a 'Java-enabled browsers' like
HotJava..
Java is a platform-independent, object-oriented programming language (OOP). It is not to be
confused with JavaScript, a scripting language used to create dynamic web pages. Due to its
reliability and ease of use, Java is one of the most popular programming languages in the
world.
Java Internet security :
Although a firewall is a good defense against most general Internet security risks, it does not
provide protection for many risks that using Java presents. Your security policy should
include details for protecting your system against three areas of concern for Java:
applications, applets, and servlets. Also, you should understand how Java and resource
security interact in terms of authentication and authorization for Java programs.
Java applications
As a language, Java has some characteristics that protect Java programmers from unintentional
errors that can cause integrity problems. (Other languages that are commonly used for PC
applications, such as C or C++, do not protect the programmers from unintentional errors as
strongly as Java does.) For example, Java uses strong typing, the strict enforcement of type
rules with no exceptions, to protect the programmer from using objects in unintended ways.
Java does not allow pointer manipulation, which protects the programmer from accidentally
going outside the memory boundaries of the program. From an application development
perspective, you can view Java as you do other high-level languages. You need to apply the
same security rules for application design that you apply with other languages on your system.
Java applets
Java applets are small Java programs that you can include in HTML pages that run on the
client but have the potential to access your i5/OS operating system. An Open Database
Connectivity (ODBC) program or an advanced program-to-program communications (APPC)
program that operates on a PC in your network can also potentially access your operating
system when, for example, your system is being used to serve applications or is being used as
a Web server. In general, Java applets can establish a session only with the i5/OS operating
system from which the applet originated. Therefore, a Java applet can access your i5/OS
operating system from a connected PC only when the applet comes from that i5/OS operating
system.
An applet can attempt to connect to any TCP/IP port on a system. It does not need to talk to a
software server that is written in Java. But, for systems that are written with the IBM®
Toolbox for Java, the applet must provide a user ID and password when it establishes
connections back to the system. In this material, the systems described are all i5/OS operating
systems. (A Java application server does not need to use the IBM Toolbox for Java.)
Typically, the IBM Toolbox for Java class prompts the user for a user ID and password for
the first connection.
The applet can perform functions on the i5/OS operating system only if the user profile has
authorization to those functions. Therefore, a good resource security scheme is essential when
you begin to use Java applets to provide new application functions. When the system
processes the requests from applets, it does not use the limited capability value that is
specified in the user profile.
The applet viewer allows you to test an applet on the i5/OS operating system; however, it is
not subject to browser security restrictions. Therefore, you need to use the applet viewer to
test only your own applets, never to run applets from outside sources. Java applets often write
to the PC drive of the user, which might provide the applet with the opportunity to perform a
destructive action. However, you can use a digital certificate to sign a Java applet to establish
its authenticity. The signed applet can write to the PC's local drives, even though the default
setting for the browser prevents it. The signed applet can also write to mapped drives on your
system because they appear to the PC to be local drives.
For Java applets that originate from your system, you might need to use signed applets.
However, you need to instruct your users, in general, not to accept signed applets from
unknown sources.
Beginning with V4R4, you can use the IBM Toolbox for Java to set up a Secure Sockets
Layer (SSL) environment. You can also use the IBM Developer Toolkit for Java to make a
Java application secure with SSL. Using SSL with your Java applications ensures encryption
of the data, including the user IDs and passwords that pass between the client and server. You
can use Digital Certificate Manager (DCM) to configure registered Java programs to use
SSL.
Java servlets
Servlets are server-side components that are written in Java, which dynamically extend the
function of a Web server without changing Web server code. The IBM WebSphere®
Application Server that is included in IBM Web Enablement for i5/OS provides support for
using servlets on the i5/OS operating systems.
You must use resource security on servlet objects that the system uses. However, applying
resource security to a servlet does not sufficiently secure it. After a Web server loads a
servlet, resource security does not prevent others from running it too. Consequently, you need
to use resource security in addition to using HTTP server security controls and directives. For
example, do not allow servlets to run under the profile of the Web server only. You also need
to use the security features provided by your servlet development tools, such as those found
in the WebSphere Application Server for i5/OS.
Review these resources to know more about general security measures for Java:
IBM Toolbox for Java contains security classes to provide verification of the identity of the
user and optionally to assign that identity to the operating system thread for an application or
servlet that is running on an i5/OS operating system. Subsequent checks for resource security
occur under the assigned identity.
The IBM Developer Kit for Java provides support for the Java Authentication and
Authorization Service (JAAS), which is a standard extension to the Java 2 Software
Development Kit (J2SDK), Standard Edition. Currently, J2SDK provides access controls that
are based on where the code originated and who signed the code (code source-based access
controls).
You can use Secure Sockets Layer (SSL) to secure communications for i5/OS applications
that you develop with IBM Developer Kit for Java. Client applications that use IBM Toolbox
for Java can also take advantage of SSL. The process for enabling SSL for your own Java
applications is somewhat different from the process for enabling SSL for the other
applications.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
o
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java
supports dynamic compilation and automatic memory management (garbage collection).
Overview
Bytecode in Java is a set of instructions for the Java Virtual Machine that is responsible for
interpreting them. Upon compiling a Java program, Java bytecode is generated that can be
executed on any platform (platform-independent) using the JVM. It is present in a .class file.
Can you imagine a world where we have to write code multiple times for each device with
varying specifications like operating system, processor architecture, etc.? It will be a tedious
process. Keeping these things in mind, Java developers came up with the concept of Write
Once Read Anywhere, which got incorporated as a feature in the Java language. To achieve
this, a code known as bytecode gets generated after compiling our Java source code. We will
now discuss the same.
Bytecode in Java is a set of instructions for the Java Virtual Machine. Java Virtual Machine,
abbreviated as JVM, enables a computer to run code written in Java. When a Java program is
compiled, the bytecode gets generated. It is equivalent to the assembler in C++.
Bytecode lies in-between low-level and high-level sets of instructions. Since we write our
code in a high-level language, it gets compiled into bytecode, and later, JVM interprets it into
machine code, a low-level set of instructions ready to be executed. Hence, we call bytecode a
code between low-level and high-level language.
• The code we write in Java is called the source code, which is written in a high-level
language. A high-level language is a programmer-friendly language with statements
written in English and is closer to human languages. The extension of the Java file is
".java".
• When we compile the program, the compiler compiles the ".java" file and generates a
".class" file. It contains the bytecode.
• The bytecode allows us to run the ".class" file on any other platform.
• But this bytecode requires an interpreter to execute it. Here the JVM comes into the
picture. JVM has an interpreter. It executes the code piece by piece, i.e., one statement
at a time, until it finds an error or is done with executing the end of the code.
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Primitive Data Types in Java
Primitive data are only single values and have no special capabilities. There are 8 primitive
data types. They are depicted below in tabular format below as follows:
Example
Type Description Default Size Literals Range of values
twos-
8
complement 0 (none) -128 to 127
bits
byte integer
twos-
16
complement 0 (none) -32,768 to 32,767
bits
short integer
Example
Type Description Default Size Literals Range of values
twos- -2,147,483,648
32
complement 0 -2,-1,0,1,2 to
bits
int intger
2,147,483,647
twos- -9,223,372,036,854,775,808
64 -2L,-
complement 0 to
bits 1L,0L,1L,2L
integer
long 9,223,372,036,854,775,807
1.23e100f , -
IEEE 754 32
0.0 1.23e-100f , .3f upto 7 decimal digits
floating point bits
float ,3.14F
1.23456e300d ,
IEEE 754 64
0.0 -123456e-300d upto 16 decimal digits
floating point bits
double , 1e1d
Let us discuss and implement each one of the following data types that are as follows:
1. Boolean Data Type
Boolean data type represents only one bit of information either true or false which is intended
to represent the two truth values of logic and Boolean algebra, but the size of the boolean data
type is virtual machine-dependent. Values of type boolean are not converted implicitly or
explicitly (with casts) to any other type. But the programmer can easily write conversion
code.
Syntax:
boolean booleanVar;
Size: Virtual machine dependent
1. Strings
Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single variable
whereas, a character array is a collection of separate char-type entities. Unlike C/C++, Java
strings are not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2. Class
A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
1. Modifiers: A class can be public or has default access. Refer to access specifiers
for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by
convention).
3. 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.
4. 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.
5. Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :
1. State: It is represented by the attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the class.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies
a set of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
• A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays
in Java work differently than they do in C/C++. The following are some important points
about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using size.
• A Java array variable can also be declared like other variables with [] after the
data type.
• The variables in the array are ordered and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Variables
Objects store their individual states in “non-static fields”, that is, fields declared without
the static keyword.
Non-static fields are also known as instance variables because their values are unique to each
instance of a class. For example, the currentSpeed of one bicycle is independent from
the currentSpeed of another.
A class variable is any field declared with the static modifier; this tells the compiler that there
is exactly one copy of this variable in existence, regardless of how many times the class has
been instantiated. A field defining the number of gears for a particular kind of bicycle could
be marked as static since, conceptually, the same number of gears will apply to all instances.
The code static int numGears = 6; would create such a static field.
3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;). There is no special
keyword designating a variable as local; that determination comes entirely from the location
in which the variable is declared—between the opening and closing braces of a method. As
such, local variables are only visible to the methods in which they are declared; they are not
accessible from the rest of the class.
4. Parameters
They are the variables that are passed to the methods of a class.
Variable Declaration :
Identifiers are the names of variables. They must be composed of only letters, numbers, the
underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only
begin with a letter, the underscore, or the dollar sign. A variable cannot begin with a number.
All variable names are case sensitive.
For example:
Variable Initialisation :
ch='a';
a=0;
Java Arrays
An array is a group of variables that share the same data type, and are referred to by a
common name. Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index. The array index ranges from 0 to n−1;
therefore, in an array of size 10, the first element is stored at index 0 and the last or the 10th
element at index 9.
The following program, Printarr, creates an array of integers, puts some values in it, and
prints each value to standard output.
class Printarr {
public static void main(String[] args) {
// declares an array of integers
int[ ] A;
// initialize elements
A[0] = 15;//first element
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use the length property to
specify how many times the loop should run.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
o/p
Volvo
BMW
Ford
Mazda
Multidimensional Arrays
Multidimensional arrays are useful when you want to store data as a tabular form, like a table
with rows and columns.
To create a two-dimensional array, add each array within its own set of curly braces:
Example :-
To access the elements of the myNumbers array, specify two indexes: one for the array, and
one for the element inside that array. This example accesses the third element (2) in the
second array (1) of myNumbers:
Example
System.out.println(myNumbers[1][2]); // Outputs 7
Remember that: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which objects
are created. For example, Student is a class while a particular student named Ravi is an
object.
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and
methods of a class. A typical Java program creates many objects, which as you know,
interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Java Objects
Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, and “menu”. An online shopping system might
have objects such as “shopping cart”, “customer”, and “product”.
Java Methods
•
The••method in Java or Methods of Java is a collection of statements that perform some
specific task and return the result to the caller. A Java method can perform some specific task
without returning anything. Java Methods allow us to reuse the code without retyping the
code. In Java, every method must be part of some class that is different from languages like
C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Advantage of Method
• Code Reusability
• Code Optimization
Note: Methods are time savers and help us to reuse the code without retyping the code.
Method Declaration
// Instance Method
void method_name(){
body // instance area }
2. Static Method: Access the static data using class name. Declared inside class
with static keyword.
Syntax:
//Static Method
static void method_name(){
body // static area }
Method Signature
It consists of the method name and a parameter list (number of parameters, type of the
parameters, and order of the parameters). The return type and exceptions are not considered
as part of it.
Method Signature of the above function:
max(int x, int y) Number of parameters is 2, Type of parameter is int.
How to Name a Method?
A method name is typically a single word that should be a verb in lowercase or a multi-word,
that begins with a verb in lowercase followed by an adjective, noun….. After the first word,
the first letter of each word should be capitalized.
Rules to Name a Method
• While defining a method, remember that the method name must be a verb and
start with a lowercase letter.
• If the method name has more than two words, the first name must be a verb
followed by an adjective or noun.
• In the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example, findSum, computeMax, setX,
and getX.
Generally, a method has a unique name within the class in which it is defined but sometimes
a method might have the same name as other method names within the same class as method
overloading is allowed in Java.
Method Calling
The method needs to be called for use its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
• It completes all the statements in the method
• It reaches a return statement
• Throws an exception
Example:
// Java Program to Illustrate Methods
// Importing required classes
import java.io.*;
// Class 1
// Helper class
class Addition {
// Initially taking sum as 0
// as we have not started computation
int sum = 0;
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{ // Adding two integer value
sum = a + b;
// Returning summation of two values
return sum;
}}
// Class 2
// Helper class
class GFG {
// Main driver method
public static void main(String[] args) {
// Creating object of class 1 inside main() method
Addition add = new Addition();
// Calling method of above class
// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);
// Printing the sum of two numbers
System.out.println("Sum of two integer values :+ s);
}}
Output
Sum of two integer values :3
Java Constructors
•
Java•• constructors or constructors in Java is a terminology used to construct something in our
programs. A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.
What are Constructors in Java?
In Java, 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.Example
// Java Program to demonstrate
// Constructor
import java.io.*;
class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}
// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
Output
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a
default constructor (constructor with no arguments) if your class doesn’t have any.
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-
class or an overloaded constructor), if you don’t type in the call to super in your constructor
the compiler will provide you with a non-argument call to super at the first line of your code,
the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don’t say extends object in your class definition.
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).
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.
Rules for writing constructors are as follows:
• The constructor(s) of a class must have the same name as the class name in which
it resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state. Like methods,
a constructor also contains a collection of statements(i.e. instructions) that are executed at the
time of Object creation.
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
// Driver class
class GFG {
// Default Constructor
GFG() { System.out.println("Default constructor"); }
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}
Output
Default constructor
Note: Default constructor provides the default values to the object like 0, null, etc. depending
on the type.
Example:
// 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);
}
}
Output
First Object
GeekName :avinash and GeekId :68
Consider the following Java program, in which we have used different constructors in the class.
Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5. Student(){
6. System.out.println("this a default constructor");
7. }
8. Student(int i, String n){
9. id = i;
10. name = n;
11. }
12. public static void main(String[] args) {
13. //object creation
14. Student s = new Student();
15. System.out.println("\nDefault Constructor values: \n");
16. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
17. System.out.println("\nParameterized Constructor values: \n");
18. Student student = new Student(10, "David");
19. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
20. }
21. }
Output:
this a default constructor
Default Constructor values:
Student Id: 0
Student Name: null
Parameterized Constructor values:
Student Id: 10
Student Name: David
In the above example, the Student class constructor is overloaded with two different
constructors, I.e., default and parameterized.
Constructor overloading in Java serves several important purposes that contribute to code
flexibility, maintainability, and ease of use. Here are the key reasons why we need constructor
overloading:
• Multiple Initialization Options: Different scenarios may require different sets of
initial values for objects. Constructor overloading allows you to provide multiple ways
to initialize objects based on the needs of the user or the context in which the object is
created. This leads to a more versatile and adaptable code.
• Code Readability: Constructor overloading enhances code readability by providing
constructors with descriptive parameter names. This makes it easier for other
developers (and your future self) to understand the purpose and usage of each
constructor without referring to extensive documentation.
• Default Values: With constructor overloading, you can set default values for certain
parameters. This is especially useful when some attributes of an object may not be
known or relevant during object creation. Constructors with default values simplify
object creation by reducing the number of required parameters.
• Encapsulation and Abstraction: By offering multiple constructors, you can
do encapsulation to the details of object initialization within the class. This way, the
users of your class don’t need to know the internal complexities; they can create objects
using the constructors you’ve provided, making your class easier to use and understand.
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
// static method
public static returnType methodName(parameters) {
// implementation not shown
}
}
// To call a static method or variable, use the Class Name
System.out.println(ClassName.staticVariable);
ClassName.staticMethod();
Static methods only have access to other static variables and static methods (unless the static
method creates an object through which to access instance variables and methods). Static
methods cannot access or change the values of instance variables or use the “this” reference
(since there is no calling object for them), and static methods cannot call non-static methods.
However, non-static methods have access to all variables (instance or static) and methods
(static or non-static) in the class.
Since there is only 1 copy of a static variable or method, static variables are often used to
count how many objects are generated. In the following class Person, there is a static variable
called personCounter that is incremented each time the Person constructor is called to
initialize a new Person object. The static method printCounter() prints out its value.
public class Person
{
// instance variables
private String name;
private String email;
private String phoneNumber;
// Static counter variable
public static int personCounter = 0;
// static method to print out counter
public static void printPersonCounter() {
System.out.println("Person counter: " + personCounter);
}
// constructor: construct a Person copying in the data into the instance variables
public Person(String initName, String initEmail, String initPhone)
{
name = initName;
email = initEmail;
phoneNumber = initPhone;
personCounter++;
}
// toString() method
public String toString()
{
return name + ": " + email + " " + phoneNumber;
}
// main method for testing
public static void main(String[] args)
{
// call the constructor to create a new person
Person p1 = new Person("Sana", "[email protected]", "123-456-7890");
Person p2 = new Person("Jean", "[email protected]", "404 899-9955");
Person.printPersonCounter();
}
}
Person counter: 2
Static variables and static methods are two important concepts in Java.
Whenever a variable is declared as static, this means there is only one copy of it for the entire
class, rather than each instance having its own copy. A static method means it can be called
without creating an instance of the class.
Static variables and methods in Java provide several advantages, including memory
efficiency, global access, object independence, performance, and code organization.
In this article, you will learn how static variables work in Java, as well as why and how to use
static methods.
The Static Keyword in Java
The static keyword is one of the most essential features in the Java programming language.
We use it to define class-level variables and methods.
Here is an example of how to use the static keyword:
public class StaticKeywordExample {
private static int count = 0; // static variable
public static void printCount() { // static method
System.out.println("Number of Example objects created so far: " + count);
}
}
As you can see above, we declared the count variable as a static variable, while we declared
the printCount method as a static method.
When a variable is declared static in Java programming, it means that the variable belongs to
the class itself rather than to any specific instance of the class. This means that there is only
one copy of the variable in memory, regardless of how many instances of the class are
created.
Here's an example. Say we have a Department class that has a static variable
called numberOfWorker. We declare and increment the static variable at the constructor level
to show the value of the static variable whenever the class object is created.
public class Department{
public static int numberOfWorker= 0;
public String name;
public Department(String name) {
this.name = name;
numberOfWorker++; // increment the static variable every time a new
//Person is created
}
}
The results of the above code show that as we create new Department objects, the static
variable numberOfWorker retains its value.
When we print out the value of numberOfWorker in the console, we can see that it retains its
value across all instances of the Department class. This is because there is only one copy of
the variable in memory, and any changes to the variable will be reflected across all instances
of the class.
Department dpt1 = new Department("Admin");
System.out.println(Department.numberOfWorker); // output: 1
The main() method in Java is an example of a static method. The main() method is a special
static method that is the entry point for Java applications. The Math class in Java also
provides many static methods that perform mathematical operations.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
int result = Math.max(5, 10);
System.out.println(result); // Output: 10
The above code shows that the entry point for Java applications is a static method. It also
shows that the max() method is a static method of the Math class and does not require an
instance of the Math class to be created.
As you can see, static methods can be useful in providing utility functions that do not
necessitate the creation of a class object.
Final variable in Java
A final variable can be explicitly initialized only once. A reference variable declared final can
never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed
but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example
public class Test {
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
}
OR
Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Compile by: javac Bike9.java
186.181/Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
Java Command Line Arguments
-The java command-line argument is an argument i.e. passed at the time of running the java
program.
-The arguments passed from the console can be received in the java program and it can be used
as an input.
-So, it provides a convenient way to check the behavior of the program for the different values.
-You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
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.
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Output:Compile Time Error
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Output:running...
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working with Collection objects,
such as ArrayList, where primitive types cannot be used (the list can only store objects):
Example
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
Example
public class Main {
Integer myInt = 5;
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}o/p
5
5.99
A
Exception in Java
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why
we use exception handling in Java.
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch
or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with method
signature.
Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.
JavaExceptionExample.java
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions. In this section, we will focus
on the types of exceptions in Java and the differences between the two.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it, the program would not give a compilation
error. Usually, it occurs when the user provides bad data during the interaction with the
program.
UncheckedExceptionExample1.java
1. class UncheckedExceptionExample1 {
2. public static void main(String args[])
3. {
4. int postive = 35;
5. int zero = 0;
6. int result = positive/zero;
7. //Give Unchecked Exception here.
8. System.out.println(result);
9. }
10. }
In the above program, we have divided 35 by 0. The code would be compiled successfully, but
it will throw an ArithmeticException error at runtime. On dividing a number by 0 throws the
divide by zero exception that is a uncheck exception.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at uncheckedException.main(uncheckedException.java:7)
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
Example 1:
Let's see a simple example of Java custom exception. In the following code, constructor of
InvalidAgeException takes a string as an argument. This string is passed to constructor of
parent class Exception using the super() method. Also the constructor of Exception class can
be called without using a parameter and calling super() method is not mandatory.
TestCustomException1.java
Output:-
Example 1
MultipleCatchBlock1.java
Output:-
In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Multithreading
A thread can have one of the following states during its lifetime:
1. New: In this state, a Thread class object is created using a new operator, but the thread is not
alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method. However, the
thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state, and the
thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the other
thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run() method exits.
2) Write the difference between notify() and notifyAll() in Java.u
Both notify and notifyAll are the methods of thread class and used to provide notification
for the thread.But there are some significant differences between both of these methods
which we would discuss below.
Sr.
Key notify notifyAll
No.
In case of multiThreading
notify() method sends the While notifyAll() methods in the
notification to only one same context sends the
1 Notification
thread among the multiple notification to all waiting threads
waiting threads which are instead of single one thread.
waiting for lock.
o Multithreading provides better utilization of cache memory as threads share the common
memory resources.
o Multithreading reduces the number of the required server as one server can execute multiple
threads at a time.
4) What do you understand by inter-thread communication?
o The thread is paused running in its critical section, and another thread is allowed to enter (or
lock) in the same critical section to be executed.
5) write an importance of wait(), notify() and notifyAll() methods in Java with its
proper syntax?
6) Differentiate between the Thread class and Runnable interface for creating a
Thread?
However, the primary differences between both the ways are given below:
o By extending the Thread class, we cannot extend any other class, as Java does not allow multiple
inheritances while implementing the Runnable interface; we can also extend other base class(if
required).
o By extending the Thread class, each of thread creates the unique object and associates with it
while implementing the Runnable interface; multiple threads share the same object
o Thread class provides various inbuilt methods such as getPriority(), isAlive and many more while
the Runnable interface provides a single method, i.e., run().
wait() sleep()
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) The wait() method releases the lock. The sleep() method doesn't release the lock.
Synchronization is the capability to control the access of multiple threads to any shared resource. It is
used:
When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence
to remove this issue, Java uses the process of synchronization which allows only one thread to be
executed at a time. Synchronization can be achieved in three ways:
o by synchronized block
o by static synchronization
Multiple inheritance creates ambiguity. For example, assume there is a Sub class and two classes
named Cat and Dog, each with a method called sample( ). And if the class Sub inherits
both Cat and Dog, there will be two copies of the sampling method, one from each superclass,
making it impossible to decide which method to use.
In Java, we can achieve multiple inheritance through the concept of interface. An interface is
like a class that has variables and methods, however, unlike a class, the methods in an interface are
abstract by default. Multiple inheritance through interface occurs in Java when a class implements
multiple interfaces or when an interface extends multiple interfaces.
In this example, we’ll see how a Java program illustrates multiple inheritance via an interface.
o Each interface, Dog and Cat, has one abstract method, i.e., bark() and meow(), respectively. The
Animal class implements the interfaces Dog and Cat.
o The main() method of the Demo class creates an object of the Animal class. Then, the bark() and
meow() functions are called.
o Implementation of Multiple inheritance in Java through Interface
interface Dog {
void bark();
interface Cat {
void meow();}
System.out.println("Dog is barking");}
public void meow() {
System.out.println("Cat is meowing");
}}
class Main {
a.bark();
a.meow();
}
Output of the above code:
Dog is barking
Cat is meowing