Welcome to Java world!
Introduction of Java
Java technology is
both a programming language and a platform. The Java programming language is a
high-level language. In the Java programming language, all source code is first
written in plain text files ending with the .java extension.
Those source files are then compiled into .class files by the javac compiler.
A .class file does not contain code that is native to your processor; it instead contains byte codes the machine language of the Java Virtual Machine (Java VM).The java launcher tool then runs your application with an instance of the Java Virtual Machine.
Those source files are then compiled into .class files by the javac compiler.
A .class file does not contain code that is native to your processor; it instead contains byte codes the machine language of the Java Virtual Machine (Java VM).The java launcher tool then runs your application with an instance of the Java Virtual Machine.
History of Java
James Gosling -
founder of java.
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995.Java team members (also known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java.
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995.Java team members (also known as Green Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are given the major points that describes the history of java.
Java Version History
There are many java versions that has been released.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java IDE Tools
i) Forte by Sun MicroSystems
ii) Borland Jbuilder
iii) Microsoft Visual J++
iv) WebGain Café
v) IBM Visual Age for Java
vi) Eclipes
There are many java versions that has been released.
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java IDE Tools
i) Forte by Sun MicroSystems
ii) Borland Jbuilder
iii) Microsoft Visual J++
iv) WebGain Café
v) IBM Visual Age for Java
vi) Eclipes
Java Applications
There are mainly 4 type of applications
that can be created using java:-
1) Standalone Application/Desktop Application
2) Web Application
3) Enterprise Application
4) Mobile Application
1) Standalone Application/Desktop Application
2) Web Application
3) Enterprise Application
4) Mobile Application
1) Standalone Application/Desktop Application:-
It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.
It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.
2) Web Application :-
An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application :-
An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application:-
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications.
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications.
Features of Java
There is given many
features of java. They are also known as java buzzwords.
1. Object-Oriented
2. Platform independent
3. Simple
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Object Oriented:-
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:-
i) Object
ii) Class
iii) Inheritance
iv) Polymorphism
v) Abstraction
vi) Encapsulation
2. Platform independent:-
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
3. Simple:-
Java was designed to be easy for the professional programmer to learn and use effectively. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier.
Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.
4. Secured:-
Java is secured because:
i) No explicit pointer
ii) Programs run inside virtual machine sandbox.
5. Robust:-
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
6. Architectural- neutral:-
There is no implementation dependent features e.g. size of primitive types is set.
7. Portable:-
We may carry the java bytecode to any platform.
8. Dyanamic:-
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. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of bytecode may be dynamically updated on a running system.
9. Interpreted:-
As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. Most previous attempts at cross-platform solutions have done so at the expense of performance.
10. High Performance:-
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
11. Multi-threaded:-
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multi-media, Web applications etc.
12. Distributed:-
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
1. Object-Oriented
2. Platform independent
3. Simple
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Object Oriented:-
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:-
i) Object
ii) Class
iii) Inheritance
iv) Polymorphism
v) Abstraction
vi) Encapsulation
2. Platform independent:-
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
3. Simple:-
Java was designed to be easy for the professional programmer to learn and use effectively. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier.
Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.
4. Secured:-
Java is secured because:
i) No explicit pointer
ii) Programs run inside virtual machine sandbox.
5. Robust:-
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
6. Architectural- neutral:-
There is no implementation dependent features e.g. size of primitive types is set.
7. Portable:-
We may carry the java bytecode to any platform.
8. Dyanamic:-
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. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the Java environment, in which small fragments of bytecode may be dynamically updated on a running system.
9. Interpreted:-
As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. Most previous attempts at cross-platform solutions have done so at the expense of performance.
10. High Performance:-
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
11. Multi-threaded:-
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multi-media, Web applications etc.
12. Distributed:-
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.
Java Keywords/ Reserved Words
The following
keywords are reserved in Java:- Reserved words or Keywords are words that have
a specific meaning to the compiler and can not be used for other purposes in
the program.
Java Variables
The Java programming
language defines the following kinds of variables:
i) Instance Variables (Non-Static Fields)
ii) Class Variables (Static Fields)
iii) Local Variables
i) Instance Variables (Non-Static Fields):- Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword.
Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the current Speed of one bicycle is independent from the current Speed of another.
ii) Class Variables (Static Fields):- A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int num Gears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
iii) Local Variables:- Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field
i) Instance Variables (Non-Static Fields)
ii) Class Variables (Static Fields)
iii) Local Variables
i) Instance Variables (Non-Static Fields):- Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword.
Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the current Speed of one bicycle is independent from the current Speed of another.
ii) Class Variables (Static Fields):- A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int num Gears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
iii) Local Variables:- Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field
(for example, int count = 0;).
There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method.
As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method.
As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Java Data Types
The main purpose of
Data Types in java is to determine what kind of value we can stored in to the
variable.
Ex: int x;
like, int=12;
Ex: int x;
like, int=12;
Data Types
|
Memory Size
|
Minimum and Maximum Values
|
Byte
|
1 byte
|
-128 to +127
|
Short
|
2 bytes
|
-32768 to + 32767
|
Int
|
4 bytes
|
-2147483648 to +
2147483647
|
Long
|
8 bytes
|
-9223372036854775808
to +9223372036854775807
|
Float
|
4 bytes
|
-3.4e38 to -.4e-45
for negative values and 1.4e-45 to 3.4e+038 for positive values.
|
Double
|
8 bytes
|
-1.8e08 to
-4.9e-324 for negative values and 4.9e-324 to 1.8e+308 for positive values.
|
Char
|
2 bytes
|
0 to 65535
|
boolean
|
true or false
|
Java JDK Directory Structure
Assuming the JDK software is installed
at /jdk1.5.0, here are some of the most important directories:
Directory
|
Description
|
/jdk1.5.0
|
The root directory
of the JDK software installation. Contains copyright, license, and Readme
files. Also contains src.jar, the archive of source code for the java 2
platform.
|
/jdk1.5.0/bin
|
The executable for
all the development tools contained in the Java 2 JDK. The PATH environment
variable should contain an entry for this directory. For more information on
the tools.
|
/jdk1.5.0/lib
|
Files used by the
development tools. Includes tools.jar, which contains non-core classes for
support of the tools and utilities in the JDK.
|
/jdk1.5.0/jre
|
The root directory
of the Java runtime environment used by the JDK development tools. The
runtime environment is an implementation of Java 2 platform. This is the directory
referred to by the java. Home system property.
|
/jdk1.5.0/jre/bin
|
Executable files
for tools and libraries used by the Java platform. The executable files are
identical to files in /jdk1.5.0/bin. The java launcher tool serves as an
application launcher, in place of the old jre tool that shipped with 1.1
versions of the JDK software. This directory does not need to be in the PATH
environment variable.
|
/jdk1.5.0/jre/lib
|
Code libraries,
property settings, and resource files used by the Java runtime environment.
|
/jdk1.5.0/jre/lib/ext
|
Default
installation directory for Extensions to the Java platform. This is where the
JavaHelp jar file goes when it is installed.
|
/jdk1.5.0/jre/lib/security
|
Contains files used
for security management.These include the security policy (java.policy) and
security properties (java.security) files.
|
/jdk1.5.0/jre/lib/i386/client
|
Contains the .so
file used by the Java HotSpot Client Virtual Machine, which is implemented
with Java HotSpot technology. This is the default VM.
|
/jdk1.5.0/jre/lib/i386/server
|
Contains the .so
file used by the Java HotSpot Server Virtual Machine.
|
/jdk1.5.0/jre/lib/applet
|
Jar files
containing support classes for applets can be placed in the lib/applet/
directory.
|
/jdk1.5.0/jre/lib/fonts
|
Font files for use
by platform
|
Java Basic Tools
Tool Name
|
Brief Description
|
javac
|
The compiler for
the Java programming language.
|
java
|
The launcher for
Java applications.
|
javadoc
|
API documentation
generator.
|
appletviewer
|
Run and debug
applets without a web browser.
|
jar
|
Create and manage
Java Archive (JAR) files.
|
jdb
|
The Java Debugger.
|
javah
|
C header and stub
generator. Used to write native methods.
|
javap
|
Class file
disassembler
|
extcheck
|
Utility to detect
Jar conflicts.
|
Java Class Path
Java Class Path is
required for using tools such as javac, java etc. If you are saving the java
file in jdk/bin folder, path is not required.But If you are having your java
file outside the jdk/bin folder, it is necessary to set path of JDK.
There are two ways to set java class path of JDK:
1. Temporary
2. Permanent
1. Temporary:- Temporary java class path set of JDK in windows :-
You need to follow the some steps are:-
i) Open Command Prompt
ii) Copy the path of bin folder
iii) Write in command prompt: set path=copiedpath
Ex:- set path=C:\Program Files\Java\jdk1.6.0_23\bin
2. Permanent:- Permanent java class path set of JDK in windows :-
You need to follow the some steps are:-
i) Go to My Computer Properties
ii) Advanced System Settings
iii) Advanced Tab
iv) Environment Variables
v) New Tab of User Variable
vi) Write path in variable name
vii) Write path of bin folder in variable value
viii) Ok
ix) Ok
x) Ok
There are two ways to set java class path of JDK:
1. Temporary
2. Permanent
1. Temporary:- Temporary java class path set of JDK in windows :-
You need to follow the some steps are:-
i) Open Command Prompt
ii) Copy the path of bin folder
iii) Write in command prompt: set path=copiedpath
Ex:- set path=C:\Program Files\Java\jdk1.6.0_23\bin
2. Permanent:- Permanent java class path set of JDK in windows :-
You need to follow the some steps are:-
i) Go to My Computer Properties
ii) Advanced System Settings
iii) Advanced Tab
iv) Environment Variables
v) New Tab of User Variable
vi) Write path in variable name
vii) Write path of bin folder in variable value
viii) Ok
ix) Ok
x) Ok
Java Simple Program
//Start of public DemoProgram
class
public class DemoProgram
{
//Start of Main
Method
public static void main(string
args[])
{
System.out.println(" Simple demo
program");
} //End of Main Method
} //End of DemoProgram Class
How to Compile and Run the java program:-
i) Save java program with extension .java
ii) Compile java program
javac DemoProgram.java
iii) Run java program
java DemoProgram
i) Save java program with extension .java
ii) Compile java program
javac DemoProgram.java
iii) Run java program
java DemoProgram
Comments in Java
Comments are simply
notes for the programmer to remind themselves and other programmers what a
program is meant to do.
There are three types of comments in java are:-
i) Single line comment
ii) Multiline comment
iii) Documentation comment
i) Single line comment
Ex: -
// This is a single line comment
ii) Multiline comment
Ex:-
/* This is multiline comment....
this comment can extend over several lines ...........*/
iii) Documentation comment
Ex:-
/** This comment is document comment. This is use to incorporate yours line with java help file...... **/
There are three types of comments in java are:-
i) Single line comment
ii) Multiline comment
iii) Documentation comment
i) Single line comment
Ex: -
// This is a single line comment
ii) Multiline comment
Ex:-
/* This is multiline comment....
this comment can extend over several lines ...........*/
iii) Documentation comment
Ex:-
/** This comment is document comment. This is use to incorporate yours line with java help file...... **/
Operators in Java
An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators
are used in programs to manipulate data and variables. Java supports a rich set
of operators.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators:- Different arithmetic operators supported by java language are listed below:-
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators:- Different arithmetic operators supported by java language are listed below:-
Symbol Used
|
Operation Performed
|
+
|
Addition
|
-
|
Subtraction
|
*
|
Multiplication
|
/
|
Division
|
%
|
Modulus
|
2. Relational
Operators:- These operators are used to compare the values of the operands that
must be compatible, in order to facilitate decision-making.
Java supports 6 relational operators are:-
Java supports 6 relational operators are:-
Symbol Used
|
Operation Performed
|
<
|
Less than
|
<=
|
Less than or equal to
|
>
|
Greater than
|
>=
|
Greater than or equal to
|
==
|
Equal to
|
!=
|
Not Equal to
|
3. Logical Operators:- Java has the following three logical operators.
Symbol Used
|
Operation Performed
|
!
|
Logical NOT
|
&&
|
Logical AND
|
||
|
Logical OR
|
The logical operators && and || are used when we want to test more than one condition and make decisions.
Ex:-
i) if(a>b && x==10)
ii) if(age>55 && salary<2000)
4. Assignment Operator: - Assignment operators are used to assign the result of an expression to a variable.
Assignment Operator:- '='
Ex:-
c = a+b.
5. Increment /
Decrement Operator:- Java supports two very useful operators increment (++) and decrement
operator (--), these are not generally found in other languages. The increment
operator adds 1 from the operand, while decrement operator subtracts 1 from the
operand. Both are unary operators and takes the following form:-
++m (pre incrementation) or m++ (post incrementation)
--m (pre decrementation) or m-- (post decrementation)
++m (pre incrementation) or m++ (post incrementation)
--m (pre decrementation) or m-- (post decrementation)
6. Conditional
Operator (?:) :- A ternary operator pair "?:" is available in the java to
construct conditional expression of the form
Exp1 ? Exp2 : Exp3
This the only operator that take 3 operands
Result = Testing Expression : Exp1 : Exp2
If Testing Expression is True perform expression 1 and assign to result. If Testing Expression is False perform expression 2 and assign to resut
Exp1 ? Exp2 : Exp3
This the only operator that take 3 operands
Result = Testing Expression : Exp1 : Exp2
If Testing Expression is True perform expression 1 and assign to result. If Testing Expression is False perform expression 2 and assign to resut
7. Bitwise Operator:-These operator are
used for testing the bits or for shifting them right or left. Bitwise operators
may not be appiled to float or double.
Different bitwise operators supported by Java Language are listed below are:-
Different bitwise operators supported by Java Language are listed below are:-
Symbol Used
|
Operation Performed
|
>>
|
Shift-right
|
<<
|
Shift-left
|
>>>
|
Shift-right with zero fill
|
-
|
One's complement
|
&
|
Bitwise AND
|
!
|
Bitwise OR
|
^
|
Bitwise Exclusive OR
|
8. Special Operator:- Java supports some
special operators such as instanceof operator, Dot operator.
Instance of: This operator is used only for the object reference variables. The operator checks whether the object is of a particular type (class type or interface type). Instance of operator is written as:
(Object reference variable) instance of (class/ interface type)
Instance of: This operator is used only for the object reference variables. The operator checks whether the object is of a particular type (class type or interface type). Instance of operator is written as:
(Object reference variable) instance of (class/ interface type)
Control Flow Statement
The statements inside
your source files are generally executed from top to bottom, in the order that
they appear.
Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
This section
describes the decision-making statements (if, if...else, switch), the looping
statements (for, while, do-while), and the branching statements (break,
continue, return) supported by the Java programming language.
1) Decision-making statements:-
i) if statement
ii) if....else statement
iii) Nested if....else statement
iv) else if ladder
i) if statement:- The general form of a simple "if" statement is
Syntax:-
if (text expression)
{
statement block;
}
ii) if....else statement:- The "if....else" statement is an extention of simple "if" statement. The general form is
Syntax:-
if (text expression)
{
True-statement block;
}
else
{
False-statement block;
}
iii) Nested if....else statement:- Series of decisions are involved, we may have to use more than one "if....else" statement in nested if else as follows:-
Syntax:-
if (text condition1)
{
if (text condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
iv) else if ladder statement:- Series of multiple decisions are involved.
Syntax:-
if (text condition 1)
Statement block-1
{
else if (text condition 2)
{
Statement block-2;
}
else if(condition 3)
{
Statement block-3;
..............................
}
}
else if(condition n)
{
Statement block n;
}
else
Default Statement block
1) Decision-making statements:-
i) if statement
ii) if....else statement
iii) Nested if....else statement
iv) else if ladder
i) if statement:- The general form of a simple "if" statement is
Syntax:-
if (text expression)
{
statement block;
}
ii) if....else statement:- The "if....else" statement is an extention of simple "if" statement. The general form is
Syntax:-
if (text expression)
{
True-statement block;
}
else
{
False-statement block;
}
iii) Nested if....else statement:- Series of decisions are involved, we may have to use more than one "if....else" statement in nested if else as follows:-
Syntax:-
if (text condition1)
{
if (text condition2)
{
Statement block1;
}
else
{
Statement block2;
}
}
else
{
Statement block3;
}
iv) else if ladder statement:- Series of multiple decisions are involved.
Syntax:-
if (text condition 1)
Statement block-1
{
else if (text condition 2)
{
Statement block-2;
}
else if(condition 3)
{
Statement block-3;
..............................
}
}
else if(condition n)
{
Statement block n;
}
else
Default Statement block
Control Flow Statement
2. Looping Statements:-
i) for loop
ii) while loop
iii) do .. while loop
i) for loop or statement:- The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
Syntax:-
for (initialization; termination; increment/decrement)
{
statements block;
}
i) for loop
ii) while loop
iii) do .. while loop
i) for loop or statement:- The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
Syntax:-
for (initialization; termination; increment/decrement)
{
statements block;
}
ii) while loop:- The while statement
continually executes a block of statements while a particular condition is
true. Its syntax can be expressed as:
Syntax:-
while (expression)
{
statement block;
}
Syntax:-
while (expression)
{
statement block;
}
iii) do.. while loop:-The Java programming
language also provides a do-while statement, which can be expressed as follows:
Syntax:-
do {
statement block;
}
while (expression);
Syntax:-
do {
statement block;
}
while (expression);
Object-Oriented Programming Concepts
Object means a real
word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some
concepts:-
i) Object
ii) Class
iii) Inheritance
iv) Interface
v) Polymorphism
vi) Abstraction
vii) Encapsulation
i) Object:- An object is a software bundle of related state and behaviour.
Any entity that has state and behaviour is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
ii) Class:- Collection of objects is called class. It is a logical entity.
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
iii) Inheritance:- Different kinds of objects often have a certain amount in common with each other.
Object-oriented programming allows classes to inherit commonly used state and behaviour from other classes.
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
iv) Interface:- The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java. Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
v) Polymorphism:- When one task is performed by different ways i.e. known as polymorphism. For example: to convenes the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
vi) Abstraction:- Abstraction refers to the act of representing essential features without including background details or exceptions. Abstraction refers to the ability to make a class abstract in Object oriented programming.
vii) Encapsulation:- The wrapping up of data and methods into a single unit (called class) is known as Encapsulation. Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
i) Object
ii) Class
iii) Inheritance
iv) Interface
v) Polymorphism
vi) Abstraction
vii) Encapsulation
i) Object:- An object is a software bundle of related state and behaviour.
Any entity that has state and behaviour is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
ii) Class:- Collection of objects is called class. It is a logical entity.
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
iii) Inheritance:- Different kinds of objects often have a certain amount in common with each other.
Object-oriented programming allows classes to inherit commonly used state and behaviour from other classes.
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
iv) Interface:- The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java. Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.
v) Polymorphism:- When one task is performed by different ways i.e. known as polymorphism. For example: to convenes the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
vi) Abstraction:- Abstraction refers to the act of representing essential features without including background details or exceptions. Abstraction refers to the ability to make a class abstract in Object oriented programming.
vii) Encapsulation:- The wrapping up of data and methods into a single unit (called class) is known as Encapsulation. Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Java Classes and Objects
Java is a true
object-oriented language and therefore the underlying structure of all java
programs is classes. Anything we wise to represent in a java program must be
encapsulated in a class that defines the state and behaviour of the basic
program components known as objects.
An object is anything that really exists in the world and can be distinguished from others. Everything that we see physically will come into this definition, for example:- human being, a book, tree, a table, a pen, and so on.
Collection of objects is called class. It is a logical entity.
Syntax for class:-
[Access Specifier/Modifier-List] class < class name> [extends SuperClass] [implements Interface-List]
Or
< class modifiers> class < class name>< formal type parameter list> < extends clause>< implements clause> // Class header
{ // class body
< field declarations>
< method declarations>
< nested class declarations>
< nested interface declarations>
< nested enum declarations>
< constructor declarations>
< initializer blocks>
}// End of class body
Syntax for object:-
classname reference_variable = new classname([parameter-list]);
Ex:-
An object is anything that really exists in the world and can be distinguished from others. Everything that we see physically will come into this definition, for example:- human being, a book, tree, a table, a pen, and so on.
Collection of objects is called class. It is a logical entity.
Syntax for class:-
[Access Specifier/Modifier-List] class < class name> [extends SuperClass] [implements Interface-List]
Or
< class modifiers> class < class name>< formal type parameter list> < extends clause>< implements clause> // Class header
{ // class body
< field declarations>
< method declarations>
< nested class declarations>
< nested interface declarations>
< nested enum declarations>
< constructor declarations>
< initializer blocks>
}// End of class body
Syntax for object:-
classname reference_variable = new classname([parameter-list]);
Ex:-
//start of class Person
Class Person
{
//Start
of Main Method
public static void
main(String args[])
{
Person p = new
Person();
} //End of Main Method
} //End of Person Class
Java Access Specifier:
Access specifier
defines the boundary and scope to access the method, variable, and class etc.
Java has defines four type of access specifiers such as:-
1. public
2. private
3. protected
4. default / friendly
These access specifiers are defines the scope for variables/methods. If you are not defining any access specifier so it will be as 'default' access specifier for variables/methods.
1. public
2. private
3. protected
4. default / friendly
These access specifiers are defines the scope for variables/methods. If you are not defining any access specifier so it will be as 'default' access specifier for variables/methods.
1. public access
specifier:- If you declare any variable/ function as public access specifier so you
can used it from anywhere of the program.
Syntax:-
< Access Specifier > data type variable /function ;
Ex:-
public int number;
2. private access specifier:- If you declare any variable/ function as private access specifier so you can used within the java class itself, not from outside the class, package and others.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
private int number=10;
3. protected access specifier:- If you want to access the private variable of parent class within your child class so you can declare those variable as protected. If your variable/method is declared aas protected so that variables/methods can be access same Class name, Package name, and sub class.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
protected int number=10;
4. default access specifier:- Actually, there is no default access modifier; the absence of a modifier is treated as default. A method or variable, declared default ( that is, no access modifier specified at all ), can be accessed by any class belonging to the same package.
Classes belonging to other packages cannot access. That is why default access modifier is known as package level access.
A class can be either default or public.
Note: default is keyword and is used with switch statements.
Syntax:-
< Access Specifier > data type variable /function ;
Ex:-
public int number;
2. private access specifier:- If you declare any variable/ function as private access specifier so you can used within the java class itself, not from outside the class, package and others.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
private int number=10;
3. protected access specifier:- If you want to access the private variable of parent class within your child class so you can declare those variable as protected. If your variable/method is declared aas protected so that variables/methods can be access same Class name, Package name, and sub class.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
protected int number=10;
4. default access specifier:- Actually, there is no default access modifier; the absence of a modifier is treated as default. A method or variable, declared default ( that is, no access modifier specified at all ), can be accessed by any class belonging to the same package.
Classes belonging to other packages cannot access. That is why default access modifier is known as package level access.
A class can be either default or public.
Note: default is keyword and is used with switch statements.
Java Method Overloading
An overloaded method
is more than one method: it is two or more separate methods using the same
method name (of course, with different parameters).Methods are defined in
classes. Methods are distinguished by
the compiler by their
method signatures. A method signature includes method name, number of
parameters and their type. But in procedural languages like in C, method
overloading is not permitted.
Method overloading allows to group methods of same functionality under one name. Always the name of the method should reflect its functionality ( that is, what is it going to give us). In method overloading, compiler does not consider return type in differentiating the methods.
Example:-
Method overloading allows to group methods of same functionality under one name. Always the name of the method should reflect its functionality ( that is, what is it going to give us). In method overloading, compiler does not consider return type in differentiating the methods.
Example:-
//Start Of MethodOverLoading Class
public class MethodOverLoading
{
//Start of add(int i, int j)
interger method
public void add(int i, int j)
{
int k = i+j;
System.out.println("Addition
is :" +k);
}//End of add() interger Method
//Start of add(String s, String t) String Method
public void add(String s, String
t)
{
int k = Integer.parseInt(s)
+ Integer.parseInt(t);
System.out.println("Addition is :" +k);
}//End of add() string Method
}//End of MethodOverLoading class
//Start of Main Class
class Main
{
//Start
Of Main Method
public static void main(String
args[])
{
//Create MethodOverLoading object
MethodOverLoading obj = new
MethodOverLoading();
//call add() and pass two values integer type
obj.add(10,30);
//call add() and pass two values string types
obj.add("20", "40");
}//End of Main Method
}//End of Main class
Save this file as
Main.java
To compile: javac Main.java
To execute: java Main
Output:-
Addition is : 40
Addition is : 60
Java Method Overriding
If the method
signatures of a method in superclass and subclass are same, we say superclass
method is overridden in subclass. In method overriding the return type also
must be same of that of superclass.
The subclass method must have the same name, parameter list and return type as the superclass method. That is, by using the same method name of the superclass, the subclass gives different output.
When you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding.
Example:-
The subclass method must have the same name, parameter list and return type as the superclass method. That is, by using the same method name of the superclass, the subclass gives different output.
When you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding.
Example:-
//Start Of BaseClass
public class BaseClass
{
//Start of MethodOverriding()
public void
MethodOveriding()
{
System.out.println("Base
Class Method");
} //End of MethodOverriding()
} //End of BaseClass
//Start of DerivedClass
public class DerivedClass extends BaseClass
{
//Start of MethodOverriding()
public void
MethodOverriding()
{
System.out.println("Derived
Class Method");
}//End of
MethodOverriding()
}//End of Derived Class
//Start of Main Class
class Main
{
//Start of Main
Method
public static void
main(String args[])
{
//Create
DerivedClass object
DerivedClass
obj = new DerivedClass();
obj.MethodOverriding();
}//End of Main
Method
}//End of Main Class
Save this file as
Main.java
To compile: javac Main.java
To execute: java Main
Output:-
Derived Class Method
Java Constructors
A constructor is a
special member method which will be called by the JVM implicitly (automatically)
for placing user/programmer defined values instead of placing default values.
Constructors are meant for initializing the object. Constructor is a special type of method that is used to initialize the state of an object.
Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Advantages of Constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/CHARACTERISTICS of a Constructor:
1. Constructor name must be same as its class name.
2. Constructor should not return any value even void also.
3. Constructors should not be static .
4. Constructors should not be private.
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
1. Default constructor (no-argument constructor):- A constructor is one which will not take any parameter.
A constructor that have no parameter is known as default constructor.
Syntax:-
Constructors are meant for initializing the object. Constructor is a special type of method that is used to initialize the state of an object.
Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Advantages of Constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/CHARACTERISTICS of a Constructor:
1. Constructor name must be same as its class name.
2. Constructor should not return any value even void also.
3. Constructors should not be static .
4. Constructors should not be private.
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
1. Default constructor (no-argument constructor):- A constructor is one which will not take any parameter.
A constructor that have no parameter is known as default constructor.
Syntax:-
class < class name >
{
classname()
//default constructor
{
Block
of statements;
...................;
...................;
}
..................;
..................;
};
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor()
{
System.out.println("
Default Constructor !!!");
a =
10;
b =
20;
System.out.println("Value
of a = " +a);
System.out.println("Value
of b = " +b);
}
};
class MainConstructor
{
public static void
main(String args[])
{
TestConstructor
obj = new TestConstructor();
}
};
2. Parameterized Constructor:- A constructor is one which takes some parameters.
Syntax:-
class < class name >
{
classname(list of
parameters) //paramiterized constructor
{
Block
of statements;
...................;
...................;
}
..................;
..................;
};
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor(int
x, int y)
{
System.out.println("
Parameterized Constructor !!!");
a =
x;
b =
y;
System.out.println("Value
of a = " +a);
System.out.println("Value
of b = " +b);
}
};
class MainConstructor
{
public static void
main(String args[])
{
TestConstructor
obj = new TestConstructor(10,20);
}
};
Static Keyword
Static is java
keyword it is utilized for static variables, static methods, static blocks, and
static inner classes but not for the outer class.
Static Variables:
static variable could be recognized & executed at the time of loading the byte code of respective class. The value of a variable is nnot varied for object then we should declare that variable as static.
In java application static variables will be accessed by either by using class name directly or by using respective class object reference variable.
Example:-
Static Variables:
static variable could be recognized & executed at the time of loading the byte code of respective class. The value of a variable is nnot varied for object then we should declare that variable as static.
In java application static variables will be accessed by either by using class name directly or by using respective class object reference variable.
Example:-
class A
{
int x = 10;
static int y = 20;
public static void main(String
args[])
{
//System.out.println(A.x); //CompileTimeError
System.out.println(A.y); //20
A obj = new A();
System.out.println(obj.y);
//20
System.out.println(obj.x);
//10
}
}
Static Methods:
Static Methods:
Static method is a
java method, which will be recognized at the time of loading respective class
byte code & whose execution is completely depending on the movement when we
access the method.
Static method will allow directly static variables of the same name class and which will not allow non static variables directly.
Static methods not allow to 'this' keyword, but it is possible to access static methods with 'this' keyword.
Example:-
Static method will allow directly static variables of the same name class and which will not allow non static variables directly.
Static methods not allow to 'this' keyword, but it is possible to access static methods with 'this' keyword.
Example:-
class StaticEx
{
int x = 10;
static int y = 20;
public static void Method1()
{
//System.out.println(x); //CompileTimeError
StaticEx obj = new
StaticEx();
System.out.println(obj.y);
//20
System.out.println(obj.x);
//10
}
public void Method2()
{
this.Method1();
}
}
class StaticMain
{
public static void main(String
args[])
{
StaticEx
obj = new StaticEx();
obj.Method1();
obj.Method2();
StaticEx.Method1();
}
}
Save this file as
StaticMain.java
To compile: javac
StaticMain.java
To execute: java StaticMain
Output:-
10
20
10
20
10
20
Super Keyword
super keyword gives
explicit access to the constructors, methods and variables of its super class.
The super keyword works with inheritance. Inheritance gives implicit access to subclass to call its superclass members. But implicit access is blocked by method overriding or by declaring the same instance variables in subclass what superclass is having.
Here, super keyword is used. That is super keyword gives explicit access to immediate superclass parts, even if access is blocked.
Usage of super with variables:
In the following program, the instance variable x is blocked by the subclass variable. Here super is used to print the superclass variable. Example:-
The super keyword works with inheritance. Inheritance gives implicit access to subclass to call its superclass members. But implicit access is blocked by method overriding or by declaring the same instance variables in subclass what superclass is having.
Here, super keyword is used. That is super keyword gives explicit access to immediate superclass parts, even if access is blocked.
Usage of super with variables:
In the following program, the instance variable x is blocked by the subclass variable. Here super is used to print the superclass variable. Example:-
class A
{
int x = 10 ;
}
public class B extends A
{
in x
= 20 ;
public void display(
)
{
System.out.println(
x ) ; // prints 20
System.out.println(
super.x ) ; // prints 10
System.out.println(
x + super.x) ; // prints 30
}
public static void
main(String args[ ] )
{
B b
new B( ) ;
b.display(
) ;
}
}
Usage of super with methods:
In the following program, the display method is blocked by the subclass overridden method. Here super is used to call the superclass method.
class A
{
public void display( )
{
System.out.println(
"Hello1" ) ;
}
}
public class B extends A
{
public void display( )
{
System.out.println( "Hello2 " ) ;
}
public void show(
)
{
display( ) ; //
Hello2 is printed
super.display( ) ; // Hello1 is printed
}
public static void
main(String args[ ] )
{
B b
new B( ) ;
b.show(
);
}
}
Usage of super with constructors - super( ) :
super keyword should be called in a different way with constructors, because constructors are not inherited but accessed. To access the superclass constructor from a subclass constructor we use super( ). JVM distinguishes which superclass consturctor is to be called by matching the parameters we pass with super( ).
class A
{
A( )
{
System.out.println( " Default A" )
;
A( int x )
{
System.out.println( x ) ;
}
class B extends A
{
B( )
{
System.out.println( "Default B" )
;
B( int x )
{
super( 10 ) ; // calls superclass A( int x ) constructor
System.out.println( x ) ;
}
public static void main(String args[ ] )
{
B b = new B( 5 ) ;
}
} // output is 10 and 5
final Keyword
final is a keyword in
Java which generically means, cannot be changed once created. Any final keyword
when declared with variables, methods and classes specifically means:
a final variable cannot be reassigned once initialized.
a final method cannot be overridden.
a final class cannot be subclassed.
Classes are usually declared final for either performance or security reasons. final methods work like inline code of C++.
final with variables:
final variables work like const of C-language that can't be altered in the whole program. That is, final variables once created can't be changed and they must be used as it is by all the program.
Example:-
a final variable cannot be reassigned once initialized.
a final method cannot be overridden.
a final class cannot be subclassed.
Classes are usually declared final for either performance or security reasons. final methods work like inline code of C++.
final with variables:
final variables work like const of C-language that can't be altered in the whole program. That is, final variables once created can't be changed and they must be used as it is by all the program.
Example:-
public static void main( String args[ ] )
{
int x = 10;
final int y = 20 ;
x = 100 ; // not an error
as x is not final
y = 200 ; // error
because y is final
}
final with methods:
Generally, a superclass method can be overriden by the subclass if it wants a different functionality. Or, it can use the same method if it wants the same functionality( output ).
If the superclass desires that the subclass shoud not override its method by the subclass, it declares the method as final. That is mehods declared final can not be overridden( else it is a compilation error ).
Example:-
Generally, a superclass method can be overriden by the subclass if it wants a different functionality. Or, it can use the same method if it wants the same functionality( output ).
If the superclass desires that the subclass shoud not override its method by the subclass, it declares the method as final. That is mehods declared final can not be overridden( else it is a compilation error ).
Example:-
class A
{
final void display( )
{
System.out.println(
"Barik" ) ;
}
}
class B extends A
{
void display( )
{
System.out.println( "
Tarun" ) ;
} //
raises an error
} // as display( ) is declared as final in the
superclass
final with classes:
If you want the class not be subclassed by any other class, declare it final. Classes declared final can not be extended. That is, any class can use the methods of a final class by creating an object of final class and call the methods with its object.
Example:-
If you want the class not be subclassed by any other class, declare it final. Classes declared final can not be extended. That is, any class can use the methods of a final class by creating an object of final class and call the methods with its object.
Example:-
final class A
{
}
class B extends A
{
} // error because class A is declared final
this Keyword
'this' is a keyword that
refers to the object of the class where it is used.
In other words, 'this' refers to the object of the present class.
Generally, we write instance variables, constructors and methods in a class. All these members are referenced by 'this'. When an object is created to a class, a default reference is also created internally to the object. This default reference
In other words, 'this' refers to the object of the present class.
Generally, we write instance variables, constructors and methods in a class. All these members are referenced by 'this'. When an object is created to a class, a default reference is also created internally to the object. This default reference
is nothing but
'this'. So 'this' can refer to all the things of the present object. <br<
p=""> </br<>
Interface
Interfaces are
syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
Using the keyword interface, you can fully abstract a class, interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
Once interface is defined, any number of classes can implement it. Also, one class can implement any number of interfaces.
Using the keyword interface, you can fully abstract a class, interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
Once interface is defined, any number of classes can implement it. Also, one class can implement any number of interfaces.
Interfaces
are designed to support dynamic method resolution at run time.
Example of interface:-
Example of interface:-
interface displayinterface
{
void
display();
}
class A implements displayinterface
{
public void
display()
{
System.out.println("Hello
Interface!!!");
}
public static void main(String args[])
{
A
obj = new A();
obj.display();
}
}
Output:-
Hello
Interface!!!
Java Package
A
package is a collection of classes and interfaces( generally, having a common
functionality ). Packages provide access restrictions to other classes.
A package groups together a set of classes and interfaces that are needed to work as a whole. The java.io package contains classes and interfaces for managing various kinds input and output operations.
Package defines boundary lines to govern how classes and interfaces may interact (access) with each other.
Packages also reduce the potential name clashes between classes. A single package cannot have classes with the same name more than one. But the classes with the same name can exist in different packages.
That is, we can make a Button class of our own and keep in our own package. The Button in our own package does not clash with the Button of java.io package.
Each class and interface belongs to some package( like a file cannot exist without a directory) . When we compile a class without mentioning the package name, it is placed in the default( unnamed ) package created by the JVM.
Packages can be nested, if needed. That is we can create sub-packages to packages. For example, in java.awt.event event is the sub-package to awt package.
In declaring a class, the order of statements is very important as given below, else compilation error. Always package name must be the first, if one exists.
Example:-
A package groups together a set of classes and interfaces that are needed to work as a whole. The java.io package contains classes and interfaces for managing various kinds input and output operations.
Package defines boundary lines to govern how classes and interfaces may interact (access) with each other.
Packages also reduce the potential name clashes between classes. A single package cannot have classes with the same name more than one. But the classes with the same name can exist in different packages.
That is, we can make a Button class of our own and keep in our own package. The Button in our own package does not clash with the Button of java.io package.
Each class and interface belongs to some package( like a file cannot exist without a directory) . When we compile a class without mentioning the package name, it is placed in the default( unnamed ) package created by the JVM.
Packages can be nested, if needed. That is we can create sub-packages to packages. For example, in java.awt.event event is the sub-package to awt package.
In declaring a class, the order of statements is very important as given below, else compilation error. Always package name must be the first, if one exists.
Example:-
package student ;
import java.io.* ;
public class Tarun
{
public
static void main(String args[])
{
System.out.println("Welcome
to package");
}
}
Save this file as Tarun.java
To Compile: javac -d. Tarun.java
To Run: java student.Tarun
To Compile: javac -d. Tarun.java
To Run: java student.Tarun
Output:-
Welcome
to package
Java Enums
Java Enums can be thought of as classes which have a fixed set of constants .
class SeasonExample{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}}
it is nice
ReplyDelete