File 1743100200 4666 JavaUnit1-1
File 1743100200 4666 JavaUnit1-1
21
10. Java SE 8 (18th Mar 2014)
1. Simple : Java's syntax is clear, basic, and easy to understand, making it a very
easy language to learn. According to Sun Microsystem, Java language is a
simple programming language because its grammar is based on C++ (thus
easier for programmers to learn it after C++).Many complex and little used
features, such as operator overloading and explicit pointers, have been
eliminated in Java.
21
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Portable: Java allows you to take the Java byte code to any platform, which
makes it portable. No implementation is necessary.
C++ vs Java
Comparison C++ Java
Index
Platform- C++ is platform specific. Java is not platform specific.
21
independent
Mainly used for The primary use of C++ is in Java is mostly used for programming
system programming.. applications. It is extensively utilized in
workplace, mobile, web-based, and Windows-
based applications.
Goto C++ is compatible with the The goto statement is not supported in Java.
goto statement
Multiple Multiple inheritance is supported Multiple inheritance through classes is not
inheritance in C++. supported in Java. Java interfaces can be used
to do this.
Operator In C++, operator overloading is In Java, operator overloading is not supported.
Overloading supported.
Pointers Pointers are supported in C++. C+ Java has limited support for pointers.
+ allows you to write pointer
programs.
Compiler and Only the compiler is used in C++. Java makes use of both an interpreter and a
Interpreter C++ is platform dependent since compiler. During compilation, Java source code
it is compiled and executed using is transformed into bytecode. At runtime, the
a compiler that transforms interpreter runs this bytecode and generates
source code into machine code. output. Java is platform-independent since it is
interpreted.
Call by Value Both call by reference and call by Java only allows call by value. Java doesn't
and Call by value are supported in C++. have call by reference.
reference
Structure and Unions and structures are Java does not support unions or structures
Union supported in C++
Thread Support C++ does not come with built-in Java supports threads by default.
thread support. It is dependent
on external libraries for thread
support.
JVM (Java Virtual Machine): The specification known as JVM makes it easier to create the
runtime environment where Java bytecode is executed. An instance of the JVM is
created each time the command java is used. The JVM makes it easier to define the
class file format, register set, memory area, and fatal error reporting. Keep in mind that
the JVM depends on the platform.
Java Development Kit (JDK): It is the whole Java Development Kit, which includes the
compiler, Java documentation, debuggers, JRE (Java Runtime Environment), and more.
To create, compile, and run a Java application, the JDK needs to be installed on the
computer.
Java Runtime Environment (JRE): The JDK includes JRE. The user can only launch the
program if the machine only has JRE installed. To put it another way, only the Java
21
command functions. A Java program cannot be compiled (the javac command will not
function).
The program Creation
The Java program can be written using a Text Editor (Notepad++ or NotePad or other
editors will also do the job.) or IDE (Eclipse, NetBeans, etc.).
FileName: TestClass.java
1. public class ExamClass
2. {
3. // main method
4. public static void main(String args [])
5. {
6. // print statement
7. System.out.println (" First Java Program.");
8. }
9. }
Write the above code and save the file with the name ExamClass. The file should have
the .java extension.
Type javac into the command prompt. The command that triggers the Java compiler to
start compiling the Java application is ExamClass.java. javac. The name of the file that
has to be compiled must be entered after the command. It is ExamClass.java in our
instance. Once you have typed, hit the enter key. A file called ExamClass.class
containing the byte code will be created if all goes according to plan. The compiler will
identify any errors in the program and prevent the creation of ExamClass.class
containing the byte code.
After the .class file is created, type java ExamClass to execute the program. The output of
the program will be displayed on the screen, which is mentioned below.
21
is visible to all. Other access specifier keywords are, private, protected, and default.
import java.io.*: It means that all of the classes present in the package java.io is imported.
The java.io package facilitates the output and input streams for writing and reading
data to files. * means all. If one wants to import only a specific class, then replace the *
with the name of the class.
System.in: It is the input stream that is utilized for reading characters from the input-
giving device, which is usually a keyboard in our case.
static void main(): The static keyword tells that the method can be accessed without doing
the instantiation of the class.
System.out: As System.in is used for reading the characters, System.out is used to give
the result of the program on an output device such as the computer screen.
double, int: The different data types, int for the integers, double for double. Other data
types are char, boolean, float, etc.
println(): The method shows the texts on the console. The method prints the text to the
screen and then moves to the next line. For the next line, ln is used. If we do not want the
cursor to move to the next line, use the method print().
1. Class
A class is a user-defined data type. It represents the set of properties or methods that are
common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed
limits, mileage are their properties.
2. Object:
21
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated. An object has an
identity, state, and behavior. Each object contains data and code to manipulate the data.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.
3. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism.
4. Inheritance:
The capability of a class to derive properties and characteristics from another class is
21
called Inheritance. When we write a class, we inherit properties from other classes. So
when we create a class, we do not need to write all the properties and functions again
and again, as these can be inherited from another class that possesses it. Inheritance
allows the user to reuse the code whenever possible and reduce its redundancy.
5. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates, so it is also known
as data-hiding.
6. Data Abstraction:
Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will
21
stop the car, but he does not know about how on pressing the accelerator the
speed is increasing, he does not know about the inner mechanism of the car or
the implementation of the accelerator, brakes, etc in the car.
3. Class name: The name must begin with an initial letter (capitalized by
convention).
4. Superclass (if any): The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one parent.
Example 1:
Let's consider the following example to understand how to define a class in Java and
implement it with the object of class.
Calculate.java
// class definition
public class Calculate {
21
// instance variables
int a;
int b;
// constructor to instantiate
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}
// method to add numbers
public int add () {
int res = a + b;
return res;
}
// method to subtract numbers
public int subtract () {
int res = a - b;
return res;
}
// method to multiply numbers
public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);
21
// calling the methods of Calculate class
System.out.println("Addition is :" + c1.add());
System.out.println("Subtraction is :" + c1.subtract());
System.out.println("Multiplication is :" + c1.multiply());
System.out.println("Division is :" + c1.divide());
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
2. Parameterized constructor
21
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class.
21
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
21
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
Output
111 Karan 0
222 Aryan 25
21
Method
A method is a block of code or collection of statements or a set of code grouped together
to perform a certain task or operation
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
21
from within the class, outside the class, within the package and outside the package.
Return Type: Return type is a data type that the method returns
.
Method Name: It is a unique name that is used to define the name of a method name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in the
program at any point. Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already stored in the
library.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Public void show, public void display and so on.
Shared memory allocation: Static variables and methods are allocated memory space only
21
once during the execution of the program.
Accessible without object instantiation: Static members can be accessed without the need to
create an instance of the class
Associated with class, not objects: Static members are associated with the class, not with
individual objects.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
class Student
{
int rollno;
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
21
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we
are accessing static method m1() without creating any object of the Test class.
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating any object of class Test
m1();
}
}
Output:
From m1
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable,
a method, or a class. It is used to restrict a user in Java.
21
Characteristics of final keyword in Java:
Final variables: When a variable is declared as final, its value cannot be changed once it
has been initialized.
Final methods: When a method is declared as final, it cannot be overridden by a subclass.
Final classes: When a class is declared as final, it cannot be extended by a subclass.
Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class.
In Java, we cannot change the value of a final variable. For example,
class Main {
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
OUTPUT:
ERROR!
/tmp/yyyEAaOvI5/Main.java:8: error: cannot assign a value to final variable AGE
AGE = 45;
^
1 error
21
Single-line Comments
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World");
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
● datatype: Type of data that can be stored in this variable.
● variable_name: Name given to the variable.
● value: It is the initial value stored in the variable.
21
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
Static variable
A variable that is declared as static is called a static variable. It cannot be local.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.
21
Java Operator Precedence
Operator Type Category Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
21
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
If Statement:
In Java, the "if" statement is used to evaluate a condition.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
21
4. Nested if-statement
1. Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} } }
Output:
x + y is greater than 20
2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
21
}
3. if-else-if ladder:
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
} } }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.
21
}
}else {
System.out.println("You are not living in India");
} } }
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on
the variable which is being switched. The switch statement is easier to use instead of if-
else-if statements. It also enhances the readability of the program.
Syntax
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example
21
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
} } }
Output: 2
Loop Statements
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
21
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
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(data_type var : array_name/collection_name){
//statements
}
Example
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
21
while loop
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }
Example:
0
2
4
6
8
10
do-while loop
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
21
System.out.println(i);
i = i + 2;
}while(i<=10);
}}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Output:
0
1
2
3
4
21
5
6
continue statement
nlike 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.
Consider the following example to understand the functioning of the continue statement
in Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
} } } }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
object
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
21
intangible object is the banking system.
An object has three characteristics:
o State: represents the data (value) of an object.
o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM
to identify each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.
class
Fields
Methods
Constructors
Blocks
Nested class and interface
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
21
}
}
Output:
0
Null
21
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
21
class.
21
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...
21
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output
meowing...
eating...
21
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
onsider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
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
Java interfaces
21
A Java interface is a group of abstract methods that specify the behavior that
implementing classes must follow.
interface Character {
void attack();
}
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
System.out.println("Warrior attacks with a sword.");
}
public void use() {
System.out.println("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
System.out.println("Mage attacks with a wand.");
}
public void use() {
System.out.println("Mage uses a wand.");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
Warrior warrior = new Warrior();
Mage mage = new Mage();
21
mage.attack(); // Output: Mage attacks with a wand.
mage.use(); // Output: Mage uses a wand.
}
}
Output:
Warrior attacks with a sword.
Warrior uses a sword.
Mage attacks with a wand.
Mage uses a wand.
Explanation: The interfaces "Character" and "Weapon" in the example above specify the
behaviour that classes that implement them must have. As a result of the classes
"Warrior" and "Mage" implementing both interfaces, the necessary behaviors may be
inherited and shown. The main method shows how to instantiate these classes' objects
and call their corresponding behaviors.
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
2. The method must have the same parameter as in the parent class.
Example
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
21
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
super.run();
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
class Vehicle
{
void run()
{
21
System.out.println("Vehicle is running");
}
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single
unit, for example, a capsule which is 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.
The Java Bean class is the example of a fully encapsulated class.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
21
void run(){System.out.println("running safely with 60km");}
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have final methods which will force the subclass not to change the body
of the method.
21
an abstract method.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output: running safely
Java Package
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.
21
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
Using packagename.*
If you 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.
//save by B.java
21
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
How to run java package program
To Compile: javac -d . B.java
To Run: java mypack.B
There are two ways to ways to set CLASSPATH: through Command Prompt or by
setting Environment Variable.
Let's see how to set CLASSPATH of MySQL database:
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step2: System
Step3: Advanced System Setting
Step4: Environment Variable
Step5: If the CLASSPATH already exists in System Variables, click on the Edit button
then put a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and
21
type Variable name as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-Connector Java.jar;.;
Remember: Put ;.; at the end of the CLASSPATH.
How to make an executable jar file in Java
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file.
An executable jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.
Main-Class: First
As you can see, the mf file starts with Main-Class colon space class name. Here, class
name is First.
In mf file, new line is must after the class name.
21
Now it will create the executable jar file. If you double click on it, it will call the main
method of the First class.
We are assuming that you have created any window based application using AWT or
SWING. If you don't, you can use the code given below:
First.java
import javax.swing.*;
public class First{
First(){
JFrame f=new JFrame();
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new First();
}
21
}
21
2. From the open wizard, we select the Java JAR file and click on the Next The Next
button opens JAR Export for JAR File Specification.
21
3. Now, from the JAR File Specification page, we select the resources needed for
exporting in the Select the resources to export After that, we enter the JAR file name
and folder. By default, the Export generated class files and resources checkbox is
checked. We also check the Export Java source files and resources checkbox to
export the source code.
21
4. If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or
resource is checked in the window on the right.
5. On the same page, there are three more checkboxes, i.e., Compress the content
of the JAR file, Add directory entries, and Overwrite existing files without warning.
By default, the Compress content of the JAR file checkbox is checked.
6. Now, we have two options for proceeding next, i.e., Finish and Next. If we click
on the Next, it will immediately create a JAR file to that location which we defined
in the Select the export destination. If we click on the Next button, it will open the
Jar Packaging Option wizard for creating a JAR description, setting the advance
option, or changing the default manifest.
21
7. For now, we skip the Next and click on the Finish button.
8. Now, we go to the specified location, which we defined in the Select the export
destination, to ensure that the JAR file is created successfully or not.
System.out.println("num="+num);
System.out.println("Square root of 25 is "+value);
}
}
21
Output:
num=1000.0
21