JAVA Unit 1
JAVA Unit 1
Unit – I
What is Java?
Java is a high-Level programming language and it is also called as a platform. Java is a
secured and robust high level object-oriented programming language. Platform: Any
software or hardware environment in which a program runs is known as a platform. Java has
its own runtime environment (JRE) and API so java is also called as platform. Java follows the
concept of Write Once, Run Anywhere.
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games 8. Robotics etc
History of Java
James Gosling, Patrick Naughton and Mike Sheridan initiated the Java language project in
1991. Team of sun engineers designed for small, embedded systems in electronic appliances
like set-top boxes. Initially it was called "Greentalk" later it was called Oak.
Features of Java
1. Object Oriented –-Java implements basic concepts of Object-oriented programming
System (OOPS) i.e. Object, Class, Inheritance, Polymorphism, Abstraction,
Encapsulation.
2. Platform Independent - Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
3. Simple - Java follows the basic Syntax of C, C++. If you understand the basic concept
of OOPS then it is easy to master in java.
4. Secure -The primary reason for Java's security is its implementation of the Java
Virtual Machine (JVM). The JVM is responsible for making sure that all Java code
runs securely, regardless of the operating system it is running on. It does this by using
a set of security policies and rules that ensure only authorized code is allowed to run.
It means that malicious code is quickly detected and blocked, and any code that is
deemed to be unsafe is not executed.
5. Portable - Due to the concept of Write Once Run Anywhere (WORA) and platform
independence, Java is a portable language. By writing once through Java, developers
can get the same result on every machine. It is also very portable to various operating
systems and architectures.
6. Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking.
7. Multithreaded − With Java's multithreaded feature in java we can
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
8. High Performance - With the use of Just-In-Time compilers, Java enables high
performance.
9. Distributed − Java is designed for the distributed environment of the internet.
10. Compiled and Interpreted - Java offers both compilation and interpretation of
programs. It combines the power of compiled languages and the flexibility of
interpreted languages. When a Java program is created, the Java compiler (javac)
compiles the Java source code into byte code. The Java Virtual Machine (JVM) is an
interpreter that converts byte code to machine code, which is portable and can be
executed on any operating system.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware
and software platforms (i.e. JVM is platform dependent).
The JVM performs following operation:
1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment
Compilation Fundamental: First, the source ‘.java’ file is passed through the compiler,
which then encodes the source code into a machine-independent encoding, known as
Bytecode. The content of each class contained in the source file is stored in a separate ‘.class’
file.
Java Source File Structure: Java source file structure describes that the Java source code
file must follow a schema or structure.
A Java program has the following structure:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!"); }}
1. public class HelloWorld {
o This defines a class named HelloWorld.
o In Java, every program must have at least one class.
2. public static void main(String[] args) {
o This is the main method — the entry point of any Java program.
o Let’s break this down:
▪ public: It can be accessed from anywhere.
▪ static: It can run without creating an object of the class.
▪ void: It doesn't return any value.
▪ main: This is the name Java looks for when it runs a program.
▪ String[] args: This is used to take input from the command line
(optional for now).
3. System.out.println("Hello, World!");
o This prints the text "Hello, World!" to the console.
o System.out is Java's standard output stream.
o println() prints a message followed by a new line.
4. Closing Braces }
o These close the main method and the HelloWorld class.
PACKAGES: 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.
package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package.
There are two types of packages in java :
1. Built in package: In java, we already have various pre-defined packages and these
packages contain large numbers of classes and interfaces that we used in java are
known as Built-in packages.
Eg: java.util , java.lang , java.io, java.sql etc
2. User defined package: As the name suggests user-defined packages are a package that
is defined by the user or programmer.
eg: package test;
import statements: The import statement is used to import a package class, or interface.
From external sources into your current java file.
For example: if you want to use Scanner class which is use to get user input we need to
import the scanner class in current source code using import keyword so that we can access
all the method available in Scanner class.
Syntax:
import packagename.class; // for particular calss
import packagename.*; //for all class
class definition: A class is a user-defined blueprint or prototype from which objects are
created, and it is a passive entity.
Java allows us to create any number of classes in a program. But out of all the classes, at
most, one of them can be declared as a public class. In simple words, the program can contain
either zero public class, or if there is a public class present, it cannot be more than one.
First case
class Today {
}
class Learning {
}
class Programming {
}
In the above java Source file no class is defined as public. We can save this file with any
name. It will compiles successfully without any errors, and corresponding .class files are
generated.
Second case
public class Today {
}
class Learning {
}
class Programming {
}
In this case name of java source file will be Today.java. If we write another name compiler
will generate error
CONSTRUCTORS: Constructor is special member function, it has the same name as class
name. It is called when an instance of object is created and memory is allocated for the
object.
It is a special type of method which is used to initialize the object
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors in java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. The
default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
class Sample{
Sample()
{
System.out.println("Sample is created");
}
public static void main(String args [])
{
Sample b=new Sample();
}}
Output : Sample is created
A constructor which has a specific number of parameters is called parameterized
constructor.
public class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(11,"Anuj ");
Student s2 = new Student(22,"Preeti ");
s1.display();
s2.display();
}}
METHODS − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.
class Sample{
public void display(){
System.out.println("This is method");
}
public static void main(String args[]){
System.out.println("This is main method");
}}
ACCESS SPECIFIES OR ACCESS MODIFIER
In Java, access modifiers are essential tools that define how the members of a class, like
variables, methods, and even the class itself can be accessed from other parts of our program.
They are an important part of building secure and modular code when designing large
applications. Understanding default, private, protected, and public access modifiers is
essential for writing efficient and structured Java programs.
1. default
2. protected
3. public
4. private
Private: The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared. Any other class of the same package will not be able to access these members.
package p1; class B {
class A { public static void main(String args[])
private void display() {
{ A obj = new A();
System.out.println("Calling private obj.display();
Method"); }}
}}
STATIC MEMBERS: The static keyword can be used with methods, fields, classes (inner/nested),
blocks. you can access these members without instantiating the class.
The Static can be:
1. Static Methods − You can create a static method by using the keyword static. Static methods
can access only static fields, methods. To access static methods there is no need to instantiate
the class, you can do it just using the class name as:
public class MyClass {
public static void sample(){
System.out.println("This is static method");
}
public static void main(String args[]){
MyClass.sample();
}
}
Output : This is static method
2. Static Fields − You can create a static field by using the keyword static. The static fields
have the same value in all the instances of the class. These are created and initialized when
the class is loaded for the first time. Just like static methods you can access static fields using
the class name (without instantiation).
public class MyClass {
public static int data = 20;
public static void main(String args[]){
System.out.println(MyClass.data);
}
}
Output : 20
3. Static Blocks − These are a block of codes with a static keyword. In general, these are used to
initialize the static members. JVM executes static blocks before the main method at the time
of class loading.
public class MyClass {
static {
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Output : Hello this is a static block
This is main method
FINAL MEMBERS
Final keyword is used to indicate that a variable, method, or class cannot be modified
or extended
Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants or other values that should not be
modified.
Final methods: When a method is declared as final, it cannot be overridden by a subclass.
This is useful for methods that are part of a class’s public API and should not be modified by
subclasses.
Final classes: When a class is declared as final, it cannot be extended by a subclass. This is
useful for classes that are intended to be used as is and should not be modified or extended.
Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class. This ensures that the value of the variable is set and cannot be
changed.
COMMENTS: Comments can be used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.
2. Non-primitive data types: The non-primitive data types include String, Arrays etc
VARIABLES: Variables are the data containers that save the data values during Java program
execution. Every Variable in Java is assigned a data type that designates the type and quantity of value
it can hold.
Example: int t = 10;
Types of Variables:
1. Local Variables These variables are declared in methods, constructors, or blocks and are
used only inside that particular method or block. You cannot access a local variable
outside the method. In Java, methods are described under curly brackets. The area ({….})
between the brackets is called a block or a method.
// Local Variables
class TestLocal {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
3. Static variables are also known as class variables. These variables are declared similarly
to instance variables. The difference is that static variables are declared using the static
keyword within a class outside of any method, constructor, or block.
class TestStatic {
public static String name = "Pankaj kumar";
public static void main(String[] args)
{
System.out.println("Name is : " + TestStatic.name);
}}
OPERATORS: 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:
3. shift Operator: shift operators are the special type of operators that work on the bits of the
data. These operators are used to shift the bits of the numbers from left to right or right to left
depending on the type of shift operator used.
• Left Shift Operator (<<) : left shift operator is a special type of operator used
to move the bits of the expression to the left according to the number
specified after the operator.
• Right Shift Operator (>>) : right shift operator is a special type of operator
used to move the bits of the expression to the right according to the number
specified after the operator.
• Unsigned Right Shift Operator (>>>): unsigned right shift operator is a
special type of right shift operator that does not use the signal bit to fill in the
sequence. The unsigned Right shift operator on the right always fills the
sequence by 0.
Example: x => 40 => 0000 0000 0000 0000 0000 0000 0010 1000
Y => -40 => 1111 1111 1111 1111 1111 1111 1101 1000
Thus x >>> 2 = 0000 0000 0000 0000 0000 0000 0000 1010
AND y >>> 2 = 0011 1111 1111 1111 1111 1111 1111 0110
4. Relational Operator: Java Relational Operators are a bunch of binary operators used to
check for relations between two operands, including equality, greater than, less than, etc. They
return a boolean result after the comparison and are extensively used in looping statements as
well as conditional if-else statements and so on.
variable1 relation_operator variable2
5. Bitwise Operator:
These operators are used to perform the 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 the Binary indexed trees.
• &, 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
complement representation of the input value, i.e., with all bits inverted.
Example:
6. Logical Operator: You can also test for true or false values with logical operators.
• && is Logical and Returns true if both statements are true.
• || is Logical or Returns true if one of the statements is true.
• ! is Logical not Reverse the result, returns false if the result is true.
7. Ternary Operator: The ternary operator is a shorthand version of the if-else statement. It
has three operands and hence the name Ternary.
The general format is:
condition? if true: if false
The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.
do while loop
Java do-while loop is used to iterate a part of the program several times.If the number of iteration is
not fixed and you must have to execute the loopat least once, it is recommended to use do-while
loop.The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax: do{ /code to be executed
}while(condition);
While Loop
while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop.
while(condition){
//looping statements
}
for loop
for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
for(datatype var: array name/collection name){
//statements }
3. Jump statements: Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution control to the other
part of the program. There are two types of jump statements in Java, i.e., break and continue.
• break statement
• continue statement
break Statement
the break statement is used to break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement. However, it breaks only the inner loop in the case
of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i); } } }
Output: 0
1
2
3
Continue statement :Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
if (i == 2) {
continue;
}
System.out.println(i);
} }}
Output : 0
1
3
Arrays: Array is an object which contains elements of a similar data type. The elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on i.e. Arrays in Java are 0 base indexed.
Output : 4
7
8
9
1
Advantages
● Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
● Random access: We can get any data located at an index position.
Disadvantages
● Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.
Types of Array in java
There are two types of array.
1) Single Dimensional Array
2) Two Dimensional Array
3) Multidimensional Array
Single dimensional array − A single dimensional array of Java is a normal array where, the array
contains sequential elements (of same type) −
int[] myArray = {10, 20, 30, 40}
Two dimensional Array In Two dimensional Array You can store items that have both rows and
columns. A row has horizontal elements. A column has vertical elements.
Datatype arrayname[][] ;
arrayname = new datatype[2][3];
datatype arrayname[][] = new datatype[R][C];
R is size of row and C is size of column
Example : a[][] = new int[2][3];
Multi-dimensional arrays contain more than one dimension, such as rows, columns, etc. These
arrays can be visualized as tables with rows and columns where each element is accessed through its
position.
Example
public class TestArray {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; i++) {
for(int j = 0; j < myNumbers[i].length; j++) {
System.out.print(myNumbers[i][j]+ “ ”);
}
System.out.println(" "); } } }
Output: 1 2 3 4
5 6 7
Strings : A String is a sequence of characters. Which may contain alpha numeric values enclosed in
double quotes (e.g. "Hello World").
A String is immutable. this means that once an Object is created it, cannot be changed.
It contains methods that can perform certain operation on Strings
eg: concat(), equals(), length() etc.
There are two ways to create String object.
1. String Literal :
e.g. String greeting = "Hello world!"; Here, "Hello world!" is a string literal.
Java keep only one copy of a string literal object and reuses them. This process is called String
interning.
In this approach, string objects are not created again and again, but reused.
Example :
Using String literal
public class TestString{
public static void main(String[] args){
String a = "Hello"; //literal
System.out.println(a); //Hello
String b = "Hello"; //literal
System.out.println(b); // Hello
System.out.println (a==b);
}}
// output: True
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
} }
Output: Hello java
StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is
same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model organized around
objects rather than actions and data. An object-oriented program can be characterized as data
controlling access to code. Concepts of OOPS
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state and
behavior is known as an object. Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can communicate without
knowing details of each other's data or code, the only necessary thing is that the type of
message accepted and type of response returned by the objects.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
• identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But it is used internally by the JVM to identify
each object uniquely.
CLASS: Collection of objects is called class. It is a logical entity. A class can also be defined
as a blueprint from which you can create an individual object. A class consists of Data
members and methods. The primary purpose of a class is to hold data/information. The
member functions determine the behavior of the class, i.e. provide a definition for supporting
various operations on data held in the form of an object.Class doesn’t store any space.
INHERITANCE: Inheritance can be defined as the procedure or mechanism of acquiring all
the properties and behavior of one class to another, i.e., acquiring the properties and behavior
of child class from the parent class. When one object acquires all the properties and behaviors
of another object, it is known as inheritance. It provides code reusability and establishes
relationships between different classes. A class which inherits the properties is known as
Child Class (sub-class or derived class) whereas a class whose properties are inherited is
known as Parent class(super-class or base class). Types of inheritance in java: single,
multilevel and hierarchical inheritance. Multiple and hybrid inheritance is supported through
interface only.
1. Single Inheritance
This is the simplest form of inheritance, where one class inherits another class.
In below Diagram A is Superclass (parent class) , B is subclass (child class)
this Keyword : this keyword is used to to refer to the object that invoked it. this can be used
inside any method to refer to the current object. That is, this is always a reference to the
object on which the method was invoked. this() can be used to invoke current class
constructor.
Example:
public class Student{
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name; }
void display(){
System.out.println(id+" "+name); }
public static void main(String args[]){
Student stud1 = new Student(1,"Tarun");
stud1.display(); }}
Output:
1 Tarun
Super Keyword: super is the reserved keyword in Java that is used to invoke constructors
and methods of the parent class. This is possible only when one class inherits another class
(child class extends parent class).
public class Parent {
int a = 50;
String s = "Hello World!"; }
class Child extends Parent {
int a = 100;
String s = "Happy Coding!";
void print() {
// referencing to the instance variable of parent class
System.out.println("Number from parent class is : " + super.a);
System.out.println("String from parent class is : " + super.s);
// printing a and s of the current/child class
System.out.println("Number from child class is : " + a);
System.out.println("String from child class is : " + s); }}
public class Main {
public static void main(String[] args) {
// creating instance of child class
Child obj = new Child();
obj.print(); }}
Output:
Number from parent class is : 50
String from parent class is : Hello World!
Number from child class is : 100
String from child class is : Happy Coding!
POLYMORPHISM: When one task is performed by different ways i.e. known as
polymorphism. For example: to convince the customer differently, to draw something e.g.
shape or rectangle etc.
Polymorphism is classified into two ways:
Method Overloading(Compile time Polymorphism): Method Overloading is a feature that
allows a class to have two or more methods having the same name but the arguments passed
to the methods are different. Compile time polymorphism refers to a process in which a call
to an overloaded method is resolved at compile time rather than at run time.
public class TestMethodOverLoading{
public int addition(int x, int y) {
return x + y; }
public int addition(int x, int y, int z) {
return x + y + z; }
public static void main(String[] args) {
TestMethodOverLoading number = new TestMethodOverLoading();
int res1 = number.addition(444, 555);
System.out.println("Addition of two integers: " + res1);
int res2 = number.addition(333, 444, 555);
System.out.println("Addition of three integers: " + res2); }}
Output: Addition of two integers: 999
Addition of three integers: 1332
Method Overriding(Run time Polymorphism): If subclass (child class) has the same
method as declared in the parent class, it is known as method overriding in java.In other
words, If subclass provides the specific implementation of the method that has been provided
by one of its parent class, it is known as method overriding.
class Vehicle {
public void displayInfo() {
System.out.println("Some vehicles are there."); } }
class Car extends Vehicle {
public void displayInfo() {
System.out.println("I have a Car."); }}
class Bike extends Vehicle {
public void displayInfo() {
System.out.println("I have a Bike."); } }
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();
v1.displayInfo();
v2.displayInfo(); } }
OUTPUT: I have a Car.
I have a Bike.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality
to the user. For example: phone call, we don't know the internal processing. In java, we use
abstract class and interface to achieve abstraction.
Abstraction in Java can be achieved using the following tools it provides:
• Abstract classes
• Interfaces
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzzz"); }}
public class Cat extends Animal {
public void animalSound() {
System.out.println("The Cat says: meow"); }}
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep(); }}
OUTPUT: The Cat says: meow
Zzzz
Interfaces
Another way to achieve abstraction in Java, is with interfaces. An interface is a completely
"abstract class" that is used to group related methods with empty bodies.
interface Animal {
public void animalSound();
public void sleep();
}
------------------------------------
class Cat implements Animal {
public void animalSound() {
System.out.println("The Cat says: meow");
}
public void sleep() {
System.out.println("sleeping"); }}
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep(); }}}
OUTPUT: The Cat says: meow
sleeping
Multiple Interfaces :To implement multiple interfaces, separate them with a comma.
interface Animal {
public void animalSound();
public void sleep(); }
interface Animal2 {
public void eat(); }
------------------------------------
class Cat implements Animal , Animal2{
public void animalSound() {
System.out.println("The Cat says: meow"); }
public void sleep() {
System.out.println("sleeping"); }
public void eat() {
System.out.println("cat eat food"); } }
class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.animalSound();
cat.sleep();
cat.eat(); }}
Output: The Cat says: meow
sleeping
cat eat food
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. A java class is the example of
encapsulation. Achieving Encapsulation in Java:
• Declare the variables of a class as private.
• Provide public setter and getter methods to modify and view the variables values.
Example:
class Employee{
private String name;// concept of Data hiding
public void setName(String name){
this.name=name; }
public String getName(){
return name; } }
class Test{
public static void main(String[] args){
Employee e = new Employee();
e. setName("Rahul");
System.out.println(e.getName()); }}
Output : Rahul
In Java, getter and setter methods are used to access and update private fields of a class.
This is a core concept of encapsulation, where fields (variables) are made private to protect
data, and public methods (getters and setters) are used to access and modify them.
public class Student {
private String name;
// getter method
public String getName() {
return name; }
// setter method
public void setName(String newName) {
name = newName; }}
• getName() is a getter — it returns the value of name.
• setName(String newName) is a setter — it sets the value of name.
Packages: A packages is a collection of related classes, Interface and sub packages.
Example: package P1;
public class First {
public void display () {
System.out.println("I am first"); }}
The above source code is stored in First.java file in ‘P1’ folder. It is then compiled, which
produces First.class file in p directory.
The package can be used as follows:
package p2;
import P1 First;
public class Test{
public static void main(String[] args) {
First f = new First();
f.display (); }}
Package plays an important role in preventing naming conflicts, Controlling access, and
making searching and usage of classes , interfaces and annotation easier.
Naming Conventions : For avoiding unwanted package names we have some following
naming conventions which we use in creating a package.
The name should always be in the lower case.
Static import in Java
In Java, static import concept is introduced in 1.5 version. With the help of static import, we
can access the static members of a class directly without class name or any object. For
Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but
by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.
But according to the programming experts, it will lead to confusion and not good for
programming. If there is no specific requirement then we should not go for static import.
Advantage of static import:
If user wants to access any static member of class then less coding is required.
Disadvantage of static import: Static import makes the program unreadable and
unmaintainable if you are reusing this feature.
Using import Using static import
class TestImportJava { import static java.lang.Math.*;
public static void main(String[] args){ class Test2 {
System.out.println(Math.sqrt(4)); public static void main(String[] args){
System.out.println(Math.pow(2, 2)); System.out.println(sqrt(4));
System.out.println(Math.abs(6.3)); }} System.out.println(pow(2, 2));
System.out.println(abs(6.3)); }}
Classpath
CLASSPATH describes the location where all the required files are available which are used
in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to
locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find
the required files and hence will throw the following error.
Error: Could not find or load main class <class name>
Set the CLASSPATH in JAVA in Windows
Command Prompt: set PATH=.;C:\Program Files\Java\JDK1.6.20\bin
Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in the
above command.
Select Start -> Control Panel -> System -> Advanced -> Environment Variables -> System
Variables -> CLASSPATH.
If the Classpath variable exists, prepend .;C:\introcs (C:\Program Files\Java\JDK1.6.20\bin)
to the beginning of the CLASSPATH varible.
If the CLASSPATH variable does not exist, select New. Type CLASSPATH for the variable
name and .;C:\introcs for the variable value.
Click OK
Jar Files
A JAR (Java Archive) is a package file format typically used to aggregate many Java class
files and associated metadata and resources (text, images, etc.) into one file to distribute
application software or libraries on the Java platform.
In simple words, a JAR file is a file that contains a compressed version of .class files, audio
files, image files, or directories. We can imagine a .jar file as a zipped file(.zip) that is created
by using WinZip software. Even, WinZip software can be used to extract the contents of a .jar
So you can use them for tasks such as lossless data compression, archiving, decompression,
and archive unpacking.