Unit I
Unit I
Unit I
In Java, every line of code that can actually run needs to be inside a class. This line declares a
class named Main, which is public, that means that any other class can access it.
Notice that when we declare a public class, we must declare it inside a file with the same
name (Main.java), otherwise we'll get an error when compiling.
1
The next line is:
public static void main(String[] args) {
This is the entry point of the Java program. The main method has to have this exact signature in
order to be able to run our program.
public again means that anyone can access it.
static means that we can run this method without creating an instance of Main . (We do
not need to create object for static methods to run. They can run itself)
void means that this method doesn't return any value.
main is the name of the method.
The arguments we get inside the method are the arguments that we will get when running the
program with parameters. It's an array of strings.
System.out.println("Hello, World!");
System is a pre-defined class that Java provides us and it holds some useful methods
and variables.
out is a static variable within System that represents the output of our program (stdout).
println is a method of out that can be used to print a line.
1.1.1 Class
A class is a user defined blueprint or prototype a program from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
Example 2:
}
void hungry() {
}
void sleeping() {
2
}
}
Modifiers : A class can be public or has default access.
Class name : The name should begin with an initial letter (capitalized by convention).
Body : The class body surrounded by braces, { }.
Methods : The sub functions a may have in their body.
Variables : A class can contain any number of variables.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
1.1.2 Objects
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which interact by invoking methods. An object consists of :
Example :
public class Point {
int x;
int y;
}
In order to create an instance of this class, we need to use the keyword new .
Point p = new Point();
3
1.2 Abstraction
Abstract method
Abstract classes may or may not contain abstract methods, i.e., methods without body (public
void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract. If a class
is declared abstract, it cannot be instantiated. A method that is declared as abstract and does not
have implementation is known as abstract method.
Example:
abstract void printStatus();//no body and abstract
4
// Main class which invokes the class Honda
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}
Understanding the real scenario of abstract class with an example:
Example 1:
File: TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by the end user
class Rectangle extends Shape{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[])
{
Shape s=new Circle1();//In real scenario, object is provided through method e.g.
//getShape() method
s.draw();
}
}
Output
drawing circle
5
In the above example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden
to the end user) and object of the implementation class is provided by the factory method. (A
factory method is the method that returns the instance of the class.)
In this example, if we create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
Example 2:
File: TestBank.java
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest()
{
return 7;
}
}
class IOB extends Bank{
int getRateOfInterest()
{
return 8;
}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new IOB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Output
Rate of Interest is: 7 %
Rate of Interest is: 8 %
6
1.3 Encapsulation
Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data
members of the class private. Now we can use setter and getter methods to set and get the data in
it. By providing only setter or getter method, we can make the class read-only or write-only. It
provides the control over the data.
Example :
//Student.java
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
//Test.java
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
Output:
vijay
Example 2:
To understand what is encapsulation in detail consider the following bank account class with
deposit and show balance methods:
7
class Account {
private int account_number;
private int account_balance;
Usually, a variable in a class are set as "private" as shown below. It can only be accessed with
the methods defined in the class. No other class or object can access them.
class Account {
private int account_number;
private int account_balance;
8
If a data member is private, it means it can only be accessed within the same class. No outside
class can access private data member or variable of other class.
So in our case hacker cannot deposit amount -100 to our account.
Approach 2: Hacker's first approach failed to deposit the amount. Next, he tries to do deposit an
amount -100 by using "deposit" method.
Class Hacker()
{
Account a = new Account();
a.account_balance=-100;
a.deposit(-100)
}
But method implementation has a check for negative values. So the second approach also fails.
public void deposit(int a) {
Method implementation has checked for negative values (-100) and throws an exception
if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
Thus, we never expose our data to an external party. Which makes our application secure.
The entire code can be thought of a capsule, and we can only communicate through the
messages. Hence the name encapsulation.
9
1.4 Inheritance
The aim of inheritance is to provide the reusability of code so that a class has to write only the
unique features and rest of the common properties and functionalities can be extended from the
another class.
Important terminology:
Super Class : The class whose features are inherited is known as super class (or a base class or
a parent class).
Sub Class : The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Reusability : Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want,
we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
The keyword used for inheritance is extends.
Syntax :
Example:
In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since
class PhysicsTeacher extends the designation and college properties and work() method from
base class, we need not to declare these properties and method in sub class.
Here we have collegeName, designation and work() method which are common to all the
teachers so we have declared them in the base class, this way the child classes
like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be
used directly from base class.
class Teacher {
String designation = "Teacher";
String collegeName = "XYZ College";
void does(){
System.out.println("Teaching");
}
}
10
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:
Beginnersbook
Teacher
Physics
Teaching
Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means
that a child class has IS-A relationship with the parent class. This inheritance is known as IS-
A relationship between child and parent class
There are five types of Inheritance in OOP concept. However Java support only four types.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Multiple Inheritances
1. Single Inheritance: refers to a child and parent class relationship where a class extends
another class.
11
Example:
TestInheritance.java
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();
}
}
Output:
barking...
eating...
2. Multilevel inheritance: refers to a child and parent class relationship where a class extends
the child class. For example class C extends class B and class B extends class A.
12
Example
TestInheritance2.java
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();
}}
Output:
weeping...
barking...
eating..
3. Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class A.
13
Example
TestInheritance3.java
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
}
}
Output:
meowing...
eating...
14
4. Multiple Inheritance: refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both classes
A and B. Java doesn’t support multiple inheritance
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 same method and we call it from child class object, there will be ambiguity
to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if we
inherit 2 classes. So whether we have same method or different, there will be compile time error
now.
class A{
void msg(){
System.out.println("Hello");
}
}
class B{
void msg(){
System.out.println("Welcome");
}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
15
obj.msg();//Now which msg() method would be invoked?
}
}
------ Execute and see the output of this program
5. Hybrid inheritance: It is a mix of two or more of the above types of inheritance. Since
java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not
possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
16
1.5 Polymorphism
Polymorphism in java is a concept by which we can perform a single action by different
ways. For example, we have a smartphone for communication. The communication mode we
choose could be anything. It can be a call, a text message, a picture message, mail, etc. So, the
goal is common that is communication, but their approach is different. This is called
Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
Polymorphism is one of the OOPs feature that allows us to perform a single action in
different ways. For example, lets say we have a class Animal that has a method sound(). Since
this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had
to give a generic message.
Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance)
Animal class. We can provide the implementation to the same method like this:
public class Horse extends Animal{
...
@Override
public void sound(){
System.out.println("Neigh");
}
}
and
17
Note : The @Override means that the method is overriding the parent class (in this case
createSolver ). When a method is marked with the @Override annotation, the compiler will
perform a check to ensure that the method does indeed override or implement a method in
super class or super interface.
As we can see that although we had the common action for all subclasses sound() but there were
different ways to do the same action. This is a perfect example of polymorphism (feature that
allows us to perform a single action in different ways). It would not make any sense to just call
the generic sound() method as each Animal has a different sound. Thus we can say that the
action this method performs is based on the type of object.
Example:
Method Overloading on the other hand is a compile time polymorphism example.
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
18
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first method has 1 int parameter, second method
has 2 int parameters and third one is having double parameter. Which method is to be called is
determined by the arguments we pass while calling methods. This happens at runtime so this
type of polymorphism is known as compile time polymorphism.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Example:
Animal.java
public class Animal{
public void sound(){
System.out.println("Animal is making a sound");
}
}
Horse.java
class Horse extends Animal{
@Override
public void sound(){
System.out.println("Neigh");
}
public static void main(String args[]){
Animal obj = new Horse();
obj.sound();
}
}
Output:
Neigh
Cat.java
public class Cat extends Animal{
@Override
public void sound(){
System.out.println("Meow");
}
public static void main(String args[]){
Animal obj = new Cat();
obj.sound();
19
}
}
Output:
Meow
Difference between Static & Dynamic Polymorphism (Difference between Overloading and
Overriding)
Static Polymorphism Dynamic Polymorphism
It relates to method overloading. It relates to method overriding.
In case a reference variable is calling an
overridden method, the method to be invoked is
Errors, if any, are resolved at compile time.
determined by the object, our reference variable
Since the code is not executed during
is pointing to. This is can be only determined at
compilation, hence the name static.
runtime when code in under execution, hence
the name dynamic.
Ex:
Ex:
void sum (int a , int b);
void sum (float a, double b);
//reference of parent pointing to child
int sum (int a, int b); //compiler gives
object
error.
Doctor obj = new Surgeon();
// method of child called
obj.treatPatient();
20
Method overriding is when one of the methods
in the super class is redefined in the sub-class.
In this case, the signature of the method
Method overloading is in the same class, remains the same.
where more than one method have the same Ex:
class X{
name but different signatures. public int sum(){
// some code
Ex: }
}
void sum (int a , int b); class Y extends X{
void sum (int a , int b, int c); public int sum(){
void sum (float a, double b); //overridden method
//signature is same
}
Important points
Polymorphism is the ability to create a variable, a function, or an object that has more
than one form.
In java, polymorphism is divided into two parts : method overloading and method
overriding.
Another term operator overloading is also there, e.g. “+” operator can be used to add
two integers as well as concat two sub-strings. We cannot have our own custom
defined operator overloading in java.
21
Simple :
Platform Independent:
java is 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.
Java code can be run on multiple platforms e.g. 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).
Portable:
Java programs can execute in any environment for which there is a Java run-time
system.(JVM – Java Virtual Machine)
Java programs can be run on any platform (Linux,Window,Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
22
Java programming is object-oriented programming language.
Like C++ java provides most of the object oriented features.
Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :
Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded :
Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time.
23
The Java Runtime Environment (JRE) is a set of software tools for development of Java
applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting
libraries. JRE is part of the Java Development Kit (JDK) was developed by Sun Microsystems.
Java Source File
A Java source file is a plain text file containing Java source code and having .java extension.
The .java extension means that the file is the Java source file. Java source code file contains
source code for a class, interface, enumeration, or annotation type. There are some rules
associated to Java source file. The following rules to be followed while writing Java source code.
There can be only one public class per source code file.
Comments can appear at the beginning or end of any line in the source code file; they are
independent of any of the positioning rules. Java comment can be inserted anywhere in a
program code where a white space can also be.
If there is a public class in a file, the name of the file must match the name of the public
class. For example, a class declared as public class Student { } must be in a source code
file named Student.java.(i.e the file name and the class name must be same)
If the class is part of a package, the package statement must be the first line in the source
code file, before any import statements that may be present.
If there are import statements, they must go between the package statement (if there is
one) and the class declaration. If there isn't a package statement, then the import
statement(s) must be the first line(s) in the source code file. If there are no package or
import statements , the class declaration must be the first line in the source code file.
import and package statements apply to all classes within a source code file. In other
words, there's no way to declare multiple classes in a file and have them in different
packages, or use different imports.
A file can have more than one non~public class.
Files with non~public classes can have a name that does not match any of the classes in
the file
Example
24
Example Program:
package javatutorial;
/**
* My first Java HelloWorld class prints the Hello World message.
*
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World : I am learning java @ f5java.com");
}
}
1.7.2 Compile and Run Java Program
Sample Java Program
25
How to compile and run the above program
Step 1: Open a text editor, like Notepad on windows. Write the program in the text editor.
Step 2: Save the file as FirstJavaProgram.java. We should always name the file same as
the public classname. In our program, the public class name is FirstJavaProgram, that’s why our
file name should be FirstJavaProgram.java.
Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on
Windows.
To compile the program, type the following command and hit enter.
javac FirstJavaProgram.java
Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can
run the program. To run the program, type the following command and hit enter:
java FirstJavaProgram
This is the first line of our java program. Every java application must have at least one class
definition that consists of class keyword followed by class name. When we say keyword, it
means that it should not be changed, we should use it as it is. However the class name can be
anything.
We have made the class public by using public access modifier, we will cover access modifier in
a separate post, all we need to know now that a java file can have any number of classes but it
can have only one public class and the file name should be same as public class name.
This is the next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside
the class.
static: We do not need to create object for static methods to run. They can run itself.
26
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run our
program.
(String[] args): Used for command line arguments that are passed as strings.
This method prints the contents inside the double quotes into the console and inserts a newline
after.
Documentation Section: It includes the comments to tell the program's purpose. It improves the
readability of the program.
Single line (or end-of line) comment : It starts with a double slash symbol (//) and
terminates at the end of the current line. The compiler ignores
everything from // to the end of the line. For example:
// Calculate sum of two numbers
Multiline Comment : Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is
ignored by the compiler. This style of comments can be used on part of a
line, a whole line or more commonly to define multi-line comment. For
example.
/*calculate sum of two numbers */
Comments cannot be nested. In other words, we cannot comment a line that already includes
traditional comment. For example,
/* x = y /* initial value */ + z; */ is wrong.
28
A class is the basic building block of an object-oriented language such as Java. The class
is a template that describes the data and the behavior associated with instances of that class.
When we instantiate a class we create an object that looks and feels like other instances of the
same class. The data associated with a class or object is stored in variables; the behavior
associated with a class or object is implemented with methods. Methods are similar to the
functions or procedures in procedural languages such as C.
class Name {
...
}
The keyword class begins the class definition for a class named Name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The "Hello World" application has no variables and has a single method named main.
Example
public class Cat {
int age;
String color;
void barking() {
Objects
An object is a software module that has state and behavior. An object's state is contained in its
member variables and its behavior is implemented through its methods. When an object of a
class is created, the class is said to be instantiated. All the instances share the attributes and the
behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
A single class may have any number of instances.
1.9 Constructors
29
In Java, constructor is a block of codes similar to method. It is called automatically when an
instance of object is created and memory is allocated for the object.
Constructor
It is called constructor because it constructs the values at the time of object creation.
It is not necessary to write a constructor for a class.
It is because java compiler creates a default constructor if our class doesn't have any.
Note:the constructor name matches with the class name and it doesn’t have a return type.
30
public class Hello {
Keyword this is a reference variable in
String name;
//Constructor Java that refers to the current object.
Hello(){ It can be used to refer instance
this.name = "Hello how are you?"; variable of current class
} It can be used to invoke or initiate current
public static void main(String[] args) class constructor
{ It can be passed as an argument in
Hello obj = new Hello(); the method call
System.out.println(obj.name);
It can be passed as argument in the
}
constructor call
}
Output It can be used to return the current class
instance
Hello how are you?
31
1. Default constructor
If we do not implement any constructor in our class, Java compiler inserts a default constructor
into our code automatically. This constructor is known as default constructor. We cannot find it
in our source code (the java file) as it would be inserted into the code during compilation and
exists in .class file. This process is shown in the diagram below:
If we implement any constructor then we no longer receive a default constructor from Java
compiler.
2. No-arg constructor:
Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.
Example: no-arg constructor
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor
32
3. Parameterized constructor
Constructor with arguments (or we can say parameters) is known as Parameterized constructor.
int empId;
String empName;
33
1.10 Methods in Java
A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code.
In general, method declarations has six components :
Modifier-: Defines access type of the method i.e. from where it can be accessed in our
application. In Java, there 4 type of the access specifiers.
public: accessible in all class in our application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible within same
class and package within which its class is defined.
The return type : The data type of the value returned by the the method or void if does not
return a value.
Method Name : the rules for field names apply to method names as well, but the convention
is a little different.
Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, we must use
empty parentheses ().
Exception list : The exceptions we expect by the method can throw, we can specify these
exception(s).
Method body : it is enclosed between braces. The code we need to be executed to perform
wer intended operations.
myMethod();
34
1. While Java is executing the program code, it encounters myMethod(); in the code.
2. The execution then branches to the myFunction() method, and executes code inside
the body of the method.
3. After the codes execution inside the method body is completed, the program returns
to the original state and executes the next statement.
35
1.11 Access Specifiers
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes,
fields and methods in Java.These Specifiers determine whether a field or method in a class, can
be used or invoked by another method in another class or sub-class. Access Specifiers can be
used to restrict access. Access Specifiers are an integral part of object-oriented programming.
from m1
36
Advantage of static variable: It makes our program memory efficient (i.e it saves memory).
Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.
1. Single-line Comments
A beginner level programmer uses mostly single-line comments for describing the code
functionality. Its the most easiest typed comments.
Syntax:
Example:
//Java program to show single line comments
class Scomment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}
2. Multi-line Comments
To describe a full method in a code or a complex snippet single line comments can be tedious
to write, since we have to give ‘//’ at every line. So to overcome this multi line comments can be
used.
Syntax:
/*Comment starts
continues
continues
Commnent ends*/
Example:
37
//Java program to show multi line comments
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}
1.13 Data types in Java
38
1. boolean
boolean data type represents only one bit of information either true or false . Values of
type boolean are not converted implicitly or explicitly (with casts) to any other type. But
the programmer can easily write conversion code.
// A Java program to demonstrate boolean data type
class GeeksforGeeks
{
public static void main(String args[])
{
boolean b = true;
if (b == true)
System.out.println("Hi Geek");
}
}
2. byte
The byte data type is an 8-bit signed two’s complement integer.The byte data type is
useful for saving memory in large arrays.
Size: 8-bit
Value: -128 to 127
// Java program to demonstrate byte data type in Java
class Testbyte
{
public static void main(String args[])
{
byte a = 126;
// byte is 8 bit value
System.out.println(a);
39
a++;
System.out.println(a);
// It overflows here because
// byte can hold values from -128 to 127
a++;
System.out.println(a);
// Looping back within the range
a++;
System.out.println(a);
}
}
Output:
126
127
-128
-127
3. short
The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to
save memory in large arrays, in situations where the memory savings actually matters.
Size: 16 bit
Value: -32,768 to 32,767 (inclusive)
4. int
It is a 32-bit signed two’s complement integer.
Size: 32 bit
Value: -231 to 231-1
Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer,
which has value in range [0, 232-1]. Use the Integer class to use int data type as an unsigned
integer.
5. long:
The long data type is a 64-bit two’s complement integer.
Size: 64 bit
Value: -263 to 263-1.
40
The float data type is a single-precision 32-bit. Use a float (instead of double) if we need to
save memory in large arrays of floating point numbers.
Size: 32 bits
Suffix : F/f Example: 9.8f
7. double
The double data type is a double-precision 64-bit. For decimal values, this data type is
generally the default choice.
8. char
The char data type is a single 16-bit Unicode character. A char is a single character.
Value: ‘\u0000’ (or 0) to ‘\uffff’ 65535
// Java program to demonstrate primitive data types in Java
class Testchar
{
public static void main(String args[])
{
// declaring character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i=89;
// use byte and short if memory is a constraint
byte b = 4;
// this will give error as number is a larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is larger than short range
// short s1 = 87878787878;
// by default fraction value is double in java
double d = 4.355453532;
// for float use 'f' as suffix
float f = 4.7333434f;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}
41
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
String
Objects and Array
Objects and Array are non-primitive data types because it refers to the memory location
42
1.14 Java Identifiers
In programming languages, identifiers are used for identification purpose. In Java an
identifier can be a class name, method name, variable name or a label. For example :
There are certain rules for defining a valid java identifiers. These rules must be followed,
otherwise we get compile-time error.
The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9])
Identifiers should not start with digits([0-9]). For example “123students” is a not a valid
java identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example “int while = 20;” is an
invalid statement as while is a reserved word.
Variables in Java
A variable is the name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
In Java, all the variables must be declared before they can be used.
43
How to declare variables?
We can declare variables in java as follows:
Types of variables
1.15.1 Local Variables: A variable defined within a block or method or constructor is called local
variable.
These variable are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
Sample Program 1:
44
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}
Output:
Student age is : 5
In the above program the variable age is local variable to the function StudentAge(). If we use
the variable age outside StudentAge() function, the compiler will produce an error as shown in
below program.
Sample Program 2:
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
}
public static void main(String args[])
{
//using local variable age outside it's scope
System.out.println("Student age is : " + age);
}
}
Output:
45
Sample Program:
import java.io.*;
class Marks
{
//These variables are instance variables.
//These variables are in a class and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}
class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
//second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60;
obj2.phyMarks = 85;
//displaying marks for first object
System.out.println("Marks for first object:");
System.out.println(obj1.engMarks);
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);
//displaying marks for second object
System.out.println("Marks for second object:");
System.out.println(obj2.engMarks);
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks);
}
}
Output:
46
80
60
85
1.15.3 Static Variables: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
Static variables are created at start of program execution and destroyed automatically
when execution ends.
To access static variables, we need not to create any object of that class, we can simply
access the variable as:
class_name.variable_name;
Sample Program:
import java.io.*;
class Emp {
// static variable salary
public static double salary;
public static String name = "Harsh";
}
public class EmpDemo
{
public static void main(String args[]) {
//accessing static variable without object
Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}
}
output:
47
1.16 Operators
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Ternary Operators
7. Bitwise Operators
8. Shift Operators
Java Arithmetic operators are used for simple math operations, they are
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulo (%)
48
Example
2. Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
49
Example 1: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Output:
10
12
12
10
Example 2: ++ and --
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}
}
Output:
22
21
Example: ~ and !
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//11 (minus of total positive value //whic
h starts from 0)
System.out.println(~b);//9 (positive of total minus, positive /
/starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
50
}
Output:
-11
9
false
true
3. Assignment Operators
Assignment operators are used to assigning values to the left operand.
Operator Name Description
To add the right and left operator and then assigning the result to the left
+=
operator
To subtract the two operands on left and right and then assign the value to
-=
the left operand
To multiply the two operands on left and right and then assign the value to
*=
the left operand
To divide the two operands on left and right and then assign the value to the
/=
left operand
^= To raise the value of left operand to the power of right operator
%= To apply modulo operator
General format is
variable = value;
Example 1:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Output:
14
16
Example 2:
class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
51
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:
13
9
18
Example 3:
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
52
>= (greater than or equal to) ex. x>=y True if x is greater than or equal to y, otherwise false
<= (less than or equal to) ex. x<=y True if x is less than or equal to y, otherwise false
Example
// Java program to illustrate
// relational operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10;
String x = "Thank", y = "Thank";
int ar[] = { 1, 2, 3 };
int br[] = { 1, 2, 3 };
boolean condition = true;
//various conditional operators
System.out.println("a == b :" + (a == b));
System.out.println("a < b :" + (a < b));
System.out.println("a <= b :" + (a <= b));
System.out.println("a > b :" + (a > b));
System.out.println("a >= b :" + (a >= b));
System.out.println("a != b :" + (a != b));
// Arrays cannot be compared with
// relational operators because objects
// store references not the value
System.out.println("x == y : " + (ar == br));
System.out.println("condition==true :" + (condition == true));
}
}
Output :
a==b :false
a=b :true
a!=b :true
x==y : false
condition==true :true
5. Logical Operators :
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, i.e. it has short-circuiting effect. Used
extensively to test for several conditions for making a decision.
Conditional operators are-
&& Logical AND : returns true when both conditions are true.
|| Logical OR : returns true if at least one condition is true.
53
// Java program to illustrate
// logical operators
public class operators
{
public static void main(String[] args)
{
String x = "Sher";
String y = "Locked";
Scanner s = new Scanner(System.in);
System.out.print("Enter username:");
String uuid = s.next();
System.out.print("Enter password:");
String upwd = s.next();
// Check if user-name and password match or not.
if ((uuid.equals(x) && upwd.equals(y)) ||
(uuid.equals(y) && upwd.equals(x))) {
System.out.println("Welcome user.");
} else {
System.out.println("Wrong uid or password");
}
}
}
Output :
Enter username:Sher
Enter password:Locked
Welcome user.
6. Ternary operator :
Ternary operator is a shorthand version of if-else statement. It has three operands and hence the
name ternary. General format is-
Example
minVal = (a < b) ? a : b;
The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.
7. Bitwise Operators :
54
These operators are used to perform manipulation of individual bits of a number. They can be
used with any of the integer types. They are used when performing update and query operations
of Binary indexed tree.
& Bitwise AND operator: returns bit by bit AND of input values.
| Bitwise OR operator: returns bit by bit OR of input values.
^ Bitwise XOR operator: returns bit by bit XOR of input values.
~ Bitwise Complement Operator: This is a unary operator which returns the one’s
compliment representation of the input value, i.e. with all bits inversed.
// bitwise operators
public class operators
{
public static void main(String[] args)
{
int a = 0x0005;
int b = 0x0007;
// bitwise and
// 0101 & 0111=0101
System.out.println("a&b = " + (a & b));
// bitwise and
// 0101 | 0111=0111
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010
System.out.println("a^b = " + (a ^ b));
// bitwise and
// ~0101=1010
System.out.println("~a = " + ~a);
// can also be combined with
// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
55
a= 5
8. Shift Operators :
These operators are used to shift the bits of a number left or right thereby multiplying or
dividing the number by two respectively. They can be used when we have to multiply or divide a
number by two. General format-
number shift_op number_of_places_to_shift;
<< Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as of multiplying the number with some power of two.
>> Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect
as of dividing the number with some power of two.
>>> Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.
// shift operators
public class operators
{
public static void main(String[] args)
{
int a = 0x0005;
int b = -10;
// left shift operator
// 0000 0101<<2 =0001 0100(20)
// similar to 5*(2^2)
System.out.println("a<<2 = " + (a << 2));
// right shift operator
// 0000 0101 >> 2 =0000 0001(1)
// similar to 5/(2^2)
System.out.println("a>>2 = " + (a >> 2));
// unsigned right shift operator
System.out.println("b>>>2 = "+ (b >>> 2));
}
}
Output :
a2 = 1
b>>>2 = 1073741821
Operator Precedence
56
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Precedence and associative rules are used when dealing with hybrid
equations involving more than one type of operator. In such cases, these rules determine which
part of equation to consider first as there can be many different valuations for the same equation.
Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator
Example
x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so
it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
57
1.17 Control Flow Statements
When we write a program, we type statements into a file. Without control flow
statements, the interpreter executes these statements in the order they appear in the file from left
to right, top to bottom. We can use control flow statements in the programs to conditionally
execute statements, to repeatedly execute a block of statements, and to otherwise change the
normal, sequential flow of control.
The Java programming language provides several control flow statements, which are listed in the
following table.
Decision making statement statements is also called selection statement. That is depending on
the condition block need to be executed or not while is decided by condition. If the condition is
"true" statement block will be executed, if condition is "false" then statement block will not be
executed.
if
if-else
switch
58
if-then Statement
if-then is the most basic statement of the decision making statement. It tells to program to
execute a certain part of code only if a particular condition or test is true.
Syntax
if(condition)
{
Statement(s)
}
Constructing the body if always optional, that is recommended to create the body when
we are having multiple statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition parts will be terminated with
next semicolon ;.
Else
It is a keyword, by using this keyword we can create an alternative block for "if" part.
Using else is always optional i.e, it is recommended to use when we are having alternate
block of condition.
When we are working with if else among those two block at any given point of time only
one block will be executed.
59
When if condition is false, then else part will be executed, if part is executed, then
automatically else part will be ignored.
if-else statement
In general, it can be used to execute one block of statement among two blocks, in Java language
if and else are the keyword in Java.
Syntax
if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
Statement(s)
In the above syntax whenever the condition is true all the if block statement are executed
remaining statement of the program by neglecting else block statement. If the condition is false
else block statement remaining statement of the program are executed by neglecting if block
statements.
A Java program to find the addition of two numbers if first number is greater than the second
number otherwise find the subtraction of two numbers.
Example
import java.util.*;
class Num
{
public static void main(String args[])
{
int a=10,b=20, c;
System.out.println("Enter any two num");
if(a>b)
{
c=a+b;
}
else
{
c=a-b;
}
System.out.println("Result="+c);
}
}
60
3. Switch Statement
A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
With switch statement use only byte, short, int, char data type. We can use any number of case
statements within a switch. The value for a case must be same as the variable in a switch.
Example
case k>=20:
is not allowed
Switch case variables can have only int and char data type. So float data type is not allowed. For
instance in the switch syntax given below:
Syntax
switch(ch)
{
case 1:
statement-1;
break;
case 2:
statement-2;
break;
}
In this ch can be integer or char and cannot be float or any other data type.
61
1.17.2 Looping statement
These are the statements execute one or more statement repeatedly a several number of times. In
Java programming language there are three types of loops are available, that is, while, for and
do-while.
Conditional statement executes only once in the program were as looping statement executes
repeatedly several numbers of time.
1. While loop
When we are working with while loop always pre-checking process will be occurred.
Pre-checking process means before the evolution of statement block condition parts will
be executed.
While loop will be repeated in clockwise direction.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}
Example
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<10)
{
System.out.println(+i);
i++;
}
62
Output
1
2
3
4
5
6
7
8
9
10
2. for loop
for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts.
Initialization
Condition
Increment or Decrements
Syntax
Initialization: step is executed first and this is executed only once when we are entering
into the loop first time. This step allows to declare and initialize any loop control
variables.
Condition: is the next step after initialization step, if it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control goes
outside the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is executed. This
statement allows to update any loop control variables.
63
Flow Diagram
64
First Initialize the variable
In second step check condition
In third step control goes inside loop body and execute.
At last increase the value of variable
Same process is repeat until condition not false.
Example
class hello
{
public static void main(String args[])
{
int i;
for (i=0: i<10; i++)
{
System.out.println("Hello Friends");
}
}
}
3. do-while
65
when we need to repeat the statement block at least 1 then go for do-while.
In do-while loop post-checking process will be occur, that is after execution of the
statement block condition part will be executed.
Syntax
do
{
Statement(s)
Example
class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;
}
While(i<10);
}
}
Output
1
2
3
4
5
6
7
8
9
10
66
1.17.3 Exception Handling Statements
The Java programming language provides a mechanism known as exceptions to help programs
report and handle errors. When an error occurs, the program throws an exception. It means that
the normal flow of the program is interrupted and that the runtime environment attempts to find
an exception handler, which is a block of code that can handle a particular type of error. The
exception handler can attempt to recover from the error or, if it determines that the error is
unrecoverable, provide a gentle exit from the program.
The try statement identifies a block of statements within which an exception might be
thrown.
The catch statement must be associated with a try statement and identifies a block of
statements that can handle a particular type of exception. The statements are executed if
an exception of a particular type occurs within the try block.
The finally statement must be associated with a try statement and identifies a block of
statements that are executed regardless of whether or not an error occurs within the try
block.
try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}
The break statement and the continue statement, which are covered next, can be used with or
without a label. A label is an identifier placed before a statement. The label is followed by a
colon (:)
statementName: someJavaStatement;
The break statement has two forms: unlabeled and labeled. We saw the unlabeled form of the
break statement used with switch earlier. As noted there, an unlabeled break terminates the
enclosing switch statement, and flow of control transfers to the statement immediately
following the switch. We can also use the unlabeled form of the break statement to terminate a
for, while, or do-while loop.
67
// break statement for a while loop
public class BreakStatement {
while (true) {
if (num == 22) {
break;
}
}
System.out.print('\n');
}
}
The unlabeled form of the break statement is used to terminate the innermost switch, for,
while, or do-while.
The labeled form terminates an outer statement, which is identified by the label specified in the
break statement.
Output
2
3
5
7
11
13
17
19
23
68
29
31
37
Continue Statement
The continue statement is used to skip a part of the loop and continue with the next iteration of
the loop. It can be used in combination with for and while statements.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between
1 to 10.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "\t");
}
}
}
Output
Odd Numbers
1
3
5
7
9
return is a reserved keyword in Java and we can’t use it as an identifier. It is used to exit from a
method, with or without a value.
69
return can be used with methods in two ways:
For methods that define a return type, return statement must be immediately followed by return
value.
Output:
6.0
For methods that don’t return a value, return statement can be skipped.
70
}
Output
Password: basketball
Password: cat
Password too short!
1.18 Array
Array is a collection of similar type of elements that have contiguous memory location.
Java array is an object that contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
To use an array in a program, we must declare a variable to reference the array, and we must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // correct but not preferred way.
71
Example
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
We can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList −
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
72
arr[0] = 10;
// initialize the second elements of the array
arr[1] = 20;
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
2. Multidimensional Array
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays. A multidimensional array is
created by appending one set of square brackets ([]) per dimension.
Examples:
Example
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]+" ");
}
73
System.out.println();
}
}
}
Output:1 2 3
2 4 5
4 4 5
Like variables, we can also pass arrays to methods. For example, below program pass array to
method sum for calculating sum of array's values.
Output :
As usual, a method can also return an array. For example, below program returns an array from
method m1.
// Java program to demonstrate
// return of array from method
class Test
{
// Driver method
public static void main(String args[])
74
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{
// returning array
return new int[]{1,2,3};
}
}
Output:
1 2 3
A 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.
Reusability: While developing a project in java, we often feel that there are few things
that we are writing again and again in our code. Using packages, we can create such
things in form of classes inside a package and whenever we need to perform that same
task, just import that package and use the class.
Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful package
name so that we can organize our project better and when we need something we can
quickly locate it and use it, which improves the efficiency.
Name Conflicts: We can define two classes with the same name in different packages so
to avoid name collision, we can use packages
As mentioned in the beginning of this guide that we have two types of packages in java.
User defined package : The package we create is called user-defined package.
Built-in package : The already defined package like java.io.*, java.lang.* etc are
known as built-in packages.
75
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some
of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
Example
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If we use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
76
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using packagename.classname
If we import package.classname then only declared class of this package will be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
77
1.20 JavaDoc Comments
One of the nice things about Java is javadoc. The javadoc utility lets us to put our comments
right next to our code, inside our ".java" source files. Javadoc is a tool which comes with JDK
and it is used for generating Java code documentation in HTML format from Java source code,
which requires documentation in a predefined format.
1 /* text */
The compiler ignores everything from /* to */.
2 //text
The compiler ignores everything from // to the end of the line.
3 /** documentation */
This is a documentation comment and in general its called doc comment. The JDK
javadoc tool uses doc comments when preparing automatically generated
documentation.
We can include required HTML tags inside the description part. For instance, the following
example makes use of <h1>....</h1> for heading and <p> has been used for creating paragraph
break.
Example
/**
* <h1>Hello, World!</h1>
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
* <p>
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
*
*
* @author Author_Name
* @version 1.0
* @since 2018-03-31
*/
public class HelloWorld {
78
public static void main(String[] args) {
/* Prints Hello, World! on standard output.
System.out.println("Hello World!");
}
}
79
Adds a "Returns" section with the description
@return @return description
text.
80