SlideShare a Scribd company logo
History of Java
 Java was developed by James Gosling, who is known
as the father of Java, in 1995.
 The history of Java starts with the Green Team.
Java team members (James Gosling, Mike
Sheridan, and Patrick Naughton), initiated the
java language project in June 1991. The small
team of sun engineers called Green Team.
 Initially it was designed for small, embedded
systems in electronic appliances like set-top
boxes, televisions etc. However, it was best
suited for internet programming.
History of Java ……
The principles for creating Java programming
were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
Currently, Java is used in internet
programming, mobile devices, games, e-business
solutions, etc. Following are given significant
points that describe the history of Java.
Firstly, it was called "Greentalk" by James
Gosling, and the file extension was .gt .
History of Java ……
After that, it was called Oak and was developed
as a part of the Green project.
Why Java was named as "Oak"?
 Oak is a symbol of strength and chosen as its a
national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.
 In 1995, Oak was renamed as "Java" because it
was already a trademark by Oak Technologies.
 Java is an island in Indonesia where the first
coffee was produced (called Java coffee). It is
a kind of espresso bean. Java name was chosen
by James Gosling while having a cup of coffee
nearby his office.
History of Java ……
Notice that Java is just a name, not an
acronym.
Finally JAVA was developed by James Gosling
and his team at Sun Microsystems (which is
now a subsidiary of Oracle Corporation) and
released in 1995.
In 1995, Time magazine called Java one of
the Ten Best Products of 1995.
JDK 1.0 was released on January 23, 1996.
After the first release of Java, there have
been many additional features added to the
language. Now Java is being used in Windows
applications, Web applications, enterprise
applications, mobile applications, cards, etc.
Difference Between C, C++, and Java
C is a general-purpose, structured, procedural,
and high-level programming language
developed by Dennis MacAlistair Ritchie in
1972 at Bell Laboratories.
It is mainly used for system programming such
as to develop the operating system, drivers,
compilers, etc.
The best-known example of the operating
system that was developed using C language is
Unix and Linux.
Features of C Language
Machine independent and portable
Modern Control Flow and Structure
Rich set of operators
Simple, Fast, and efficient
Case-sensitive
Low memory use
Easily extendable
Statically-typed (variable types are known at
compile time)
C++
C++ is an object-oriented, general-purpose,
programming language developed by Bjarne
Stroustrup at Bell Labs in 1979. It is based on
C language or we can say that it is an
extension of C language. It is used to develop
high-performance applications.
Features of C++ Language
 Case-sensitive
 Compiler based
 Platform-independent
 Portability
 Dynamic memory allocation
Java
Java is also an object-oriented, class-based,
static, strong, robust, safe, and high-level
programming language. It was developed
by James Gosling in 1995.
Its code is compiled and interpreted. It is
used to develop enterprise, mobile, and web-
based applications.
Java programming Evolution-OverviewOfJava.pdf
Features of Java
 Simple
Java is very easy to learn, and its syntax is simple,
clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming
language because:
 Java syntax is based on C++ (so easier for
programmers to learn it after C++).
 Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
 There is no need to remove unreferenced objects
because there is an Automatic Garbage Collection in
Java.
Features of Java
 Architecture-neutral
Java is architecture neutral because there are no
implementation dependent features, for example, the
size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of
memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies
4 bytes of memory for both 32 and 64-bit
architectures in Java.
Java has a "binary code format" that's independent
of hardware architectures, operating system
interfaces, and window systems. The format of this
system-independent binary code is architecture
neutral.
Features of Java
 Object-oriented
Java is an object-oriented language and it incorporates the
various characteristics of an object-oriented language,
such as Class, Object, inheritance and polymorphism,
abstraction, encapsulation.
Object-oriented programming (OOPs) is a methodology
that simplifies software development and maintenance by
providing some rules.
In Java, the entire program code must be encapsulated
inside a class. Even the most basic program in Java must
be written within a class.
 Platform independent
In Java, when you compile an error-free code, the compiler
converts the program to a platform independent code,
known as the bytecode. Thereafter, the Java Virtual
Machine (JVM) interprets this bytecode into the machine
code that can be run on that machine.
Features of Java …….
Converting a Java program into bytecode makes a Java
program platform independent because any computer
installed with the JVM can interpret and run the
bytecode.
 Portable
Portability refers to the ability of a program to run on
any platform without changing the source code of the
program. The programs developed on one computer can
run on another computer, which might have a different
operating system. Java enables the creation of cross-
platform programs by converting the programs into
Java bytecode.
Features of Java …….
 Distributed
Java can be used for the development of those
applications that can be distributed on multiple machines
in a network, such as the Internet. These applications can
be used by multiple users from multiple machines in a
network. For this purpose, Java supports the various
Internet protocols, such as Transmission Control Protocol
and Internet Protocol (TCP/IP) and Hyper Text Transfer
Protocol (HTTP).
 Secure:
Java is best known for its built-in security features. With
Java, we can develop virus-free systems. Java is secured
because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox
Java program gains access to only those resources of a
computer that are essential for its execution. This
ensures that a Java program executing on a particular
machine does not harm it
Secured
 Classloader: Classloader in Java is a part of the Java
Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the
classes of the local file system from those that are
imported from network sources.
 Bytecode Verifier: It checks the code fragments for
illegal code that can violate access rights to objects.
 Security Manager: It determines what resources a
class can access such as reading and writing to the local
disk.
 Java language provides these securities by default.
Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography,
etc.
Features of Java …….
Robust:
The English meaning of Robust is strong.
Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security
problems.
 Java provides automatic garbage collection which runs
on the Java Virtual Machine to get rid of objects
which are not being used by a Java application
anymore.
 There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
Multithreaded:
Java provides the concept of multithreading that allows a
program to simultaneously execute multiple tasks by
using threads. A thread is the smallest unit of execution
in a Java program.
The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media,
Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic
loading of classes. It means classes are loaded on
demand. It also supports functions from its native
languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory
management (garbage collection).
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
Java programming Evolution-OverviewOfJava.pdf
Java and Internet
Java is strongly associated with the Internet. Internet
users can use Java to create applet programs and run
them locally using a "Java-enabled browser" such as
HotJava.
They can also use a Java-enabled browser to download
an applet located on a computer anywhere in the
Internet and run it on his local computer.
In fact, Java applets have made the Internet a true
extension of the storage system of the local computer.
Internet users can also setup their websites containing
java applets that could be used by other remote users
of Internet. This feature made Java most popular
programming language for Internet.
Java and World Wide Web
World Wide Web (WWW) is an open-ended
information retrieval system designed to be used in
the Internet's distributed environment. This system
contains Web pages that provide both information and
controls. Web system is open-ended and we can
navigate to a new document in any direction. This is
made possible with the help of a language
called Hypertext Markup Language (HTML). Web pages
contain HTML tags that enable us to find, retrieve,
manipulate and display documents worldwide.
Java was meant to be used in distributed environments
such as Internet. Java could be easily incorporated
into the Web system. Before Java, the World Wide
Web was limited to the display of still images and
texts. However, the incorporation of Java into Web
pages has made it capable of supporting animation,
graphics, games, and a wide range of special effects.
Java Architecture
The Java architecture defines the components that
are essential to carry out the creation and execution
of code written in the Java programming language. The
various components of the Java architecture are:
 Source file
 Class file
 JVM
 Application Programming Interface (API)
The various components in the Java architecture are shown in the following figure.
Source File
Java is a robust programming language that enables
developers to build a wide variety of applications for
varying purposes. In order to write a Java program or
an application, you need to write certain code. A Java
application contains the source code that enables an
application to provide its desired functionalities. This
source code is saved in a source file with the
extension, .java.
Class File
Once created, a .java file is compiled to generate the
.class file. A class file contains the bytecode that is
generated by the compiler. Further, this class file can
be executed by any machine that supports the Java
Runtime Environment (JRE).
Java Development Kit (JDK)
JDK is a software development environment
used for developing Java applications and
applets. It includes :
 Java Runtime Environment (JRE),
 an interpreter/loader (Java),
 a compiler (javac), an archiver (jar),
 a documentation generator (Javadoc), and
other tools needed in Java development.
JRE (Java Runtime Environment)
Java Runtime Environment (JRE) is an open-
access software distribution that has a Java
class library, specific tools, and a separate
JVM.
JRE is one of the interrelated components in
the Java Development Kit (JDK). It is the most
common environment available on devices for
running Java programs. Java source code is
compiled and converted to Java bytecode.
If we want to run this bytecode on any
platform, you need JRE in turn JVM. The JRE
loads classes, check memory access and get
system resources. JRE acts as a software layer
on top of the operating system.
JVM
The JVM is an application that is responsible for
executing Java programs on a computer. It resides in
the Random Access Memory (RAM) and is specific for
every platform, such as Sun and Macintosh. The
bytecode generated during the compilation of a
program is the machine language of the JVM. JVM is
responsible for executing the bytecode and generating
the machine specific code for the machine on which
the Java program needs to be executed.
The major components of JVM are:
 Class loader
 Execution engine and Just-In-Time (JIT) compiler
 Bytecode verifier
Class Loader
The class loader loads the class files required by a
program that needs to be executed. The classes are
loaded dynamically when required by the running
program.
Execution Engine and JIT Compiler
The Java execution engine acts as an interpreter that
interprets the bytecode one line after another and
executes it. The line-by-line interpretation is a time-
consuming task and reduces the performance of a
program. To enhance the performance, the JIT
compiler has been introduced in the JVM. The JIT
compiler compiles the bytecode into machine
executable code, as and when needed, which optimizes
the performance of a Java program.
Bytecode Verifier
Before being executed by the JVM, the bytecode is
verified by using the bytecode verifier. The bytecode
verifier ensures that the bytecode is executed safely
and does not pose any security threat to the machine.
API
The Java API is a collection of software components,
such as classes, interfaces, and methods, which
provides various capabilities, such as GUI, Date and
Time, and Calendar. The related classes and interfaces
of the Java API are grouped into packages.
Simple Java Program Structure
Documentation (Comment) Section
Package Statement
Import Statement
Class Definition
Main Method Class
Documentation (Comment) Section
It is used to improve the readability of the program.
The compiler ignores these comments during the time
of execution and is solely meant for improving the
readability of the Java program.
There are three types of comments that Java supports
 Single line Comment
 Multi-line Comment
 Documentation Comment
Documentation (Comment) Section
/ a single line comment is declared like this
/* a multi-line comment is declared like this
and can have multiple lines as a comment */
/** a documentation comment starts with a
delimiter and ends with */
Package Statement
There is a provision in Java that allows you to
declare your classes in a collection called package.
There can be only one package statement in a
Java program and it has to be at the beginning of
the code before any class or interface declaration.
This statement is optional. Example:
package student;
Import Statement
Many predefined classes are stored in packages
in Java, an import statement is used to refer to
the classes stored in other packages. An import
statement is always written after the package
statement but it has to be before any class
declaration.
We can import a specific class or classes in an
import statement. Take a look at the example to
understand how import statement works in Java.
Ex:-
import java.util.Date; //imports the date class
import java.applet.*;
//imports all the classes from the java applet package
Class Definition
A Java program may contain
Several class definitions, classes are an essential
part of any Java program. It defines the
information about the user-defined classes in a
program.
A class is a collection
of variables and methods that operate on the
fields. Every program in Java will have at least one
class with the main method.
Main Method
The main method is from where the execution
actually starts and follows the order specified
for the following statements. Let’s take a look at
a sample program to understand how it is
structured.
public class Example{
//main method declaration
public static void main(String[] args){
System.out.println("hello world");
}
}
public class Example
This creates a class called Example. You should make
sure that the class name starts with a capital letter,
and the public word means it is accessible from any
other classes.
Comments
To improve the readability, we can use
comments to define a specific note or
functionality of methods, etc for the
programmer.
Curly Braces
The curly brackets are used to group all the
commands together. To make sure that the
commands belong to a class or a method.
public static void main
 When the main method is declared public, it
means that it can be used outside of this class
as well.
 The word static means that we want to access
a method without making its objects. As we
call the main method without creating any
objects.
 The word void indicates that it does not
return any value. The main is declared as void
because it does not return any value.
 Main is the method, which is an essential part
of any Java program.
String[] args
It is an array where each element is a string,
which is named as args. If you run the Java
code through a console, you can pass the input
parameter. The main() takes it as an input.
System.out.println();
The statement is used to print the output on
the screen where the system is a predefined
class, out is an object of the PrintWriter class.
The method println prints the text on the
screen with a new line. All Java statements end
with a semicolon.
Example :
Java Application having two classes in one file.
package comp
public class Computer
{
Computer()
{
System.out.println("Constructor of Computer class.");
}
void computer_method()
{
System.out.println("Power gone! Shut down your PC soon...");
}
public static void main(String[] args)
{
Computer c = new Computer();
Laptop l = new Laptop();
c.computer_method();
l.laptop_method();
}
}
class Laptop
{
Laptop()
{
System.out.println("Constructor of Laptop class.");
}
void laptop_method()
{
System.out.println("99% Battery available.");
}
}
What is token in Java?
In Java, the program contains classes and
methods. Further, the methods contain the
expressions and statements required to perform a
specific operation.
These statements and expressions are made up
of tokens. In other words, we can say that the
expression and statement is a set of tokens. The
tokens are the small building blocks of a Java
program that are meaningful to the Java compiler.
The Java compiler breaks the line of code into
text (words) is called Java tokens. These are the
smallest element of the Java program. The Java
compiler identified these words as tokens. These
tokens are separated by the delimiters. It is
useful for compilers to detect errors.
Java programming Evolution-OverviewOfJava.pdf
Defining a Class
A class defines the characteristics and behavior of an
object.
For example, if you create a gaming application, each game
that a user can play from the application can be
considered as an object of the Games class. Each game
has common characteristics, such as the number of
players, game category, and score. These characteristics
are known as the member variables, and the behavior is
specified by methods.
Any concept that you need to implement in a Java program
is encapsulated within a class. A class defines the member
variables and methods of objects that share common
characteristics.
Further, all the games have common methods, such as
calculating score, starting the game, and displaying game
instructions.
The following code snippet shows how to declare a class:
class <ClassName>
{
//Declaration of member variables
//Declaration of methods
}
In the preceding code snippet, the word, class, is a
keyword in Java that is used to declare a class and
<ClassName> is the name given to the class.
We can use the following code snippet to create the
ClassicJumble class to develop the Classic Jumble Word
game:
class ClassicJumble {
//Declaration of member variables
//Declaration of methods
}
There are certain rules that should be followed to name
Java classes. A program will raise error if these rules are
not followed. Some of these rules are:
 The name of a class should not contain any embedded
space or symbol, such as ?, !, #, @, %, &, {}, [], :, “, and /.
 A class name must be unique.
 A class name must begin with a letter, an underscore
(_), or the dollar symbol ($). Or, it must begin with an
alphabet that can be followed by a sequence of letters
or digits (0 to 9), ‘$’, or ‘_’.
 A class name should not consist of a keyword.
While naming a class, you should adhere to the following
class naming conventions that improve the readability of a
program:
 The class name should be a noun.
 The first letter of the class name should be capitalized.
 If the class name consists of several words, the first
letter of each word should be capitalized.
After defining a class, you need to save the file
before it can be executed. The following naming
conventions should be followed for naming a Java file:
 A file name must be unique.
 A file name cannot be a keyword.
 If a class is specified as public, the file name and
class name should be the same.
 If a file contains multiple classes, only one class can
be declared as public. The file name should be the
same as the class name that is declared public in
the file.
 If a file contains multiple classes that are not
declared public, any file name can be specified for
the file.
Identifying Data Types
While working with an application, you need to store
and manipulate varying data.
For example, in the Classic Jumble Word game, the
game score is a numeric value and the player name is a
string.
To handle such varying data in an application, Java
supports various data types.
There are eight primitive data types in Java, which
are further grouped into the following categories:
 Integer type: Can store integer values. The
four integer data types are:
 byte
 short
 int
 Long
The following table lists the integer primitive
data type, its data types, size, range, and
default values.
Group Data Type Size Range Default
Value
Integer byte 1 byte -27 to 27-1 0
short 2 bytes -215 to 215 -1 0
int 4 bytes -231 to 231-1 0
long 8 bytes -263 to 263-1 0
The Details of the Integer Primitive Data Type
 Floating point type: Can store decimal
numbers. The two floating point types are:
 float
 Double
The following table lists the floating point
primitive data type, its data types, size, range,
and default values.
Group Data
Type
Size Range Defau
lt
Value
Floating
point
float 4 bytes 3.4e-038 to
3.4e+038
0.0
double 8 bytes 1.7e-308 to
1.7e+308
0.0
Boolean type: Can store only the values, true and
false.
Character type: Can store a single character,
such as a symbol, letter, and number. In the
character type, there is one data type, char. To
a character data type, 2 bytes of memory is
allocated.
Note :- To store string values, you need to
use built-in classes, such as, String,
StringBuilder, and StringBuffer.
Wrapper Classes
Variables that are declared by using the primitive data
types are not objects. The primitive data types, such
as int and char, are not a part of the object hierarchy.
Therefore, in order to use the primitive data types as
objects, Java provides wrapper classes. A wrapper
class acts like an object wrapper and encapsulates the
primitive data types within the class so it can be
treated like an object.
The various wrapper classes, such as Boolean, Byte,
Character, Integer, Short, Long, Double, and Float,
are provided by the java.lang package. These classes
are useful when you need to manipulate primitive data
types as objects.
Autoboxing and Unboxing
The automatic conversion of primitive data types into
its equivalent Wrapper type is known as boxing and
opposite operation is known as unboxing.
Advantages of Autoboxing and Unboxing
No need of conversion between primitives and
Wrappers manually so less coding is required.
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
//Integer a3=Integer.valueOf(5)
System.out.println(a2+" "+a3);
}
}
Example of Unboxing in java
The automatic conversion of wrapper class type into
corresponding primitive type, is known as Unboxing.
Let's see the example of unboxing:
class UnboxingExample1{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
//int a=i.intValue();
System.out.println(a);
}
}
Identifying Class Members
In Java, a class can contain the following members:
 Variables
 Methods
 Objects
 Inner classes
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.
There are two types of data types in Java:
primitive and non-primitive.
Variable
A variable is the name of a reserved area
allocated in memory. In other words, it is a
name of the memory location. It is a
combination of "vary + able" which means its
value can be changed.
There are three types of variables in java:
local, instance and static.
Variable
A variable needs to be declared before it is accessed.
The declaration of a variable informs the compiler
about the variable name and the type of value stored
in it. The following code snippet shows how to declare
a variable:
<type> <variablename>; // Single variable of given type.
<type> <variable1name,variable2name.....variable_n_name>;
// Multiple variables of given type.
int choice;
int num1, num2;
The following code snippet shows how to assign values
to a variable:
<type> <variablename>=<value>; // During declaration.
<variablename>=<value> // After declaration.
For example, you can use the following code snippet to
assign values to the variables, num1 and num2:
int num1, num2; // Declaration of variables.
num1 = 5; // Assigning values to the variables.
num2 =10;
The following code snippet can be used to assign a
value to a variable at the time of its declaration.
int num1=5;
You can also assign the same value to more than one
variable in a single statement. The following code
snippet shows the assignment of the same value to
more than one variable:
a=b=c=3;
In the preceding code snippet, the integer value, 3, is
first assigned to c, then to b, and finally to a.
Literal in a JAVA Program
To understand the type of values that a variable can
contain, you need to understand the concept of
literals. A literal is a value that is assigned to a
variable or constants in a Java program. A literal
contains a sequence of characters, such as digits,
alphabets, or any other symbol, which represents the
value to be stored. The various types of literals in
Java are:
 Integer literals: Are non-fractional numeric
values. The numerical values can be represented in
the decimal, octal, and hexadecimal notation. In
order to represent an octal number, it is preceded
by zero. In order to represent hexadecimal
numbers, they are prefixed by 0x.
For example, n=0567 is integer literal represented in
the octal notation whereas n=0x124 represents an
integer literal in hexadecimal notation.
Floating point literals: Are numeric values that
contain a fractional part. The floating point literals
contain a decimal and an integer part. For example, z=2.2
represents a floating point literal.
Character literals: Are represented inside a pair of
single quotation marks. For example, x='k' is a character
literal.
String literals: Are enclosed in a pair of double
quotation marks. For example, x="James" is a string
literal.
Boolean literals: Are the literals that can contain the
values, true or false. For example, x= false is a boolean
literal.
Binary literals: Are the literals that can be used to
express the primitive integer data types into binary form.
In order to specify these literals, you need to prefix the
binary number with 0b or 0B. For example, 0b101.
Java programming Evolution-OverviewOfJava.pdf
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.
// Java Program to Illustrate Working Of Function Calling
// Class
class LocalVar {
public static int findSum(int a, int b)
{
int sum = a + b; //Local Variable
return sum;
}
public static void main(String[] args)
{
int a = 10, b = 20; //Local Variable
int c = findSum(a, b);
System.out.print(c);
}
}
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.
It is called an instance variable because its value is
instance-specific and is not shared among instances.
Features of an instance variable
The life of an instance variable depends on the life of
an Object, i.e., when the object is created, an
instance variable also gets created.
public class Student
{
String name;
int marks;
Student (String stuName) {
name = stuName;
}
public void setMarks(int stuMar) {
marks = stuMar;
}
// This method prints the student details.
public void printStudent() {
System.out.println("Name: " + name );
System.out.println("Marks:" + marks);
}
public static void main(String args[]) {
Student StudentOne = new Student("Ankit");
Student StudentTwo = new Student("Akshat");
Student StudentThree = new Student("Vikram");
StudentOne.setMarks(98);
StudentTwo.setMarks(89);
StudentThree.setMarks(90);
StudentOne.printStudent();
StudentTwo.printStudent();
StudentThree.printStudent();
}
}
Java Scanner Class
The Scanner class of the java.util package is used to
read input data from different sources like input
streams, users, files, etc.
The Scanner class provides various methods that allow
us to read inputs of different types.
Method Description
nextInt() reads an int value from the user
nextFloat()
reads a float value form
the user
nextBoolean()
reads a boolean value from
the user
nextLine()
reads a line of text from
the user
next() reads a word from the user
nextByte()
reads a byte value from
the user
nextDouble()
reads a double value from
the user
nextShort()
reads a short value from
the user
nextLong()
reads a long value from the
user
import java.util.Scanner;
class Scanner1 {
String name,gender;
Byte age;
Integer qty;
Double rate;
Boolean status;
public void input()
{
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// takes input from the keyboard
name = input.nextLine();
System.out.print("Enter your Gender: ");
gender=input.next();
System.out.print("Enter your Age: ");
age=input.nextByte();
System.out.print("Enter Item Quantity :");
qty=input.nextInt();
System.out.print("Enter Rate of Item (Double) :");
rate=input.nextDouble();
System.out.print("Are you above 18?- :(True/False)");
status = input.nextBoolean();
}
public void display()
{
// prints the name
System.out.println("nnnnnMy name is :" + name);
System.out.println("My Gender is :" + gender);
System.out.println("My Age is :" + age);
System.out.println("Rate of Item :" + rate);
System.out.println("Item Quantity : " + qty);
if (status == true)
{
System.out.println("You are over 18");
}
else if (status == false)
{
System.out.println("You are under 18");
}
}
public static void main(String[] args)
{
Scanner1 obj=new Scanner1();
obj.input();
obj.display();
}
}
Static Members
Variables and methods declared using
keyword static are called static members of a
class. We know that non-static variables and
methods belong to instance.
But static members (variables, methods) belong to
class. Static members are not part of any instance
of the class.
Static members can be accessed using class name
directly, in other words, there is no need to create
instance of the class specifically to use them.
Static members can be of two types:
Static Variables
Static Methods
Static Variable
 A static variable is associated with a class
rather than an instance. A static field is
declared using the static keyword.
 Static variables are shared across all
instances of a class.
 There is only one copy of a static variable per
class.
 Non-static variables cannot be called
inside static methods.
 If any instance of a class modifies the value
of a static variable, the change is reflected
across all instances of the class.
 Static variables are memory-efficient as they
are not duplicated for each instance.
Static Variables
Static variables are also called class
variables because they can be accessed
using class name, whereas, non static
variables are called instance variables and
can be accessed using instance reference
only.
Static variables occupy single location in the
memory. These can also be accessed using
instance reference.
These are accessible in both static and non-
static methods, even non-static methods can
change their values.
While declaration, there is no need to initialize
the static variables explicitly because they
take default values like other non-static
variables (instance variables).
Now, the question is, why to use static
variables?
Let us look at a reason for using one. Suppose
you want to keep record about the number of
running instances of a class. In this situation, it
would be better to declare a static variable.
Static Methods/Class Methods
Static methods are also called class methods. A
static method belongs to class, it can be used
with class name directly. It is also accessible
using instance references.
Static methods can use static variables only,
whereas non-static methods can use both
instance variables and static variables.
Implementation:
The following program uses a static counter
variable and static method showCount() method
to track the number of running instances of the
class student in the memory.
class Student
{ private static int count=0; //static variable
Student()
{
count++; //increment static variable
}
static void showCount() //static method
{
System.out.println(“Number Of students : “+count);
}
}
public class StaticDemo
{
public static void main(String[] args)
{
Student s1=new Student();
Student s2=new Student();
Student.showCount(); //calling static method
Student s3=new Student();
Student s4=new Student();
s4.showCount(); //calling static method
}
}
class Country {
// Static variable
static int countryCounter;
String name;
int counter;
Country() //Constructor function
{
countryCounter++;
}
public static void main(String[] args)
{
Country ob1 = new Country(); // Creating first instance
// Assigning values to object's data variables.
ob1.name = "India";
ob1.counter = 1;
Country ob2 = new Country(); // Creating second instance
ob2.name = “South Africa";
ob2.counter = 1;
System.out.println("ob1.countryCounter = " + ob1.countryCounter);
System.out.println("ob2.countryCounter = " + ob2.countryCounter);
System.out.println("Country.countryCounter = " + Country.countryCounter);
}
}
Java Command Line Arguments
The command-line arguments in Java allow the
programmers to pass the arguments during the
execution of a program. The users can pass the
arguments during the execution by passing the
command-line arguments inside the main() method.
We need to pass the arguments as space-separated
values. We can pass both strings and primitive data
types(int, double, float, char, etc) as command-line
arguments to JVM. These arguments get stored as
Strings in a String array that is passed to the main()
function.
We can use these command-line arguments as input in
our Java program.
// Java Program to Check for Command Line Arguments
class CommandLine {
// Main driver method
public static void main(String[] args)
{
// Checking if length of args array is greater than 0
if (args.length > 0) {
// Print statements
System.out.println("The command line arguments are:");
// Iterating the args array
// using for each loop
for (String val : args)
// Printing command line arguments
System.out.println(val);
}
else
// Print statements
System.out.println("No command line "+ "arguments found.");
}
}
package mypack;
public class CommandLine
{
public static void main(String []args)
{
System.out.println("Welcome to java Class");
System.out.println("Command Line Arguments are:");
for (String s : args)
System.out.println("Command Line Arguments are :->"+s);
}
}
public class Arguments
{
public static void main(String args[])
{ int sum=0;
System.out.println("Sum of all numbers are");
for(int i=0;i<args.length;i++)
{
sum=sum+Integer.parseInt(args[i]);
}
System.out.println("Sum of numbers is "+sum);
}
}
public class Tables
{
public static void main(String args[])
{ int n=0;
System.out.println("Table of "+args[0]);
for(int i=1;i<=10;i++)
{
n=Integer.parseInt(args[0]);
System.out.println(n+" * "+i+" = "+n*i);
}
}
}
Java Constant
 Constant is a value that cannot be changed after
assigning it. Java does not directly support the
constants. There is an alternative way to define the
constants in Java by using the non-access modifiers
static and final.
 In Java, to declare any variable as constant, we
use static and final modifiers. It is also known
as non-access modifiers. According to the Java
naming convention the identifier name must be
in capital letters.
Static and Final Modifiers
 The purpose to use the static modifier is to
manage the memory.
 It also allows the variable to be available
without loading any instance of the class in
which it is defined.
 The final modifier represents that the value
of the variable cannot be changed. It also
makes the primitive data type immutable or
unchangeable.
import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
PRICE=900;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is:
"+total_bill);
}
}
Method or Function
A method is a set of statements that is intended to
perform a specific task.
For example,
a compute() method can be used for computing the score.
Moreover, methods provide encapsulation and are also
essential to refer to the data members and access them. A
method consists of two parts, method declaration and
method body.
The syntax for defining a method is:
<Access specifier> <Return type> <Method name>(Parameter list)
//method declaration
{
<Method body> // body of the method
}
In the preceding syntax, the first line depicts the
method declaration and the contents within the
curly braces depict the method body. According to
the preceding syntax, the various elements of a
method are:
 Access specifier: Determines the extent to which
a method can be accessed from another class.
 Return type: A method can also return a value.
The return type specifies the data type of the
value returned by a method. Some methods do not
return any value. Such methods should use the
void return type. The value to be returned by the
method is specified with the keyword, return.
 Method name: Is a unique identifier and is case-
sensitive.
Parameter list: A method may or may not contain
a parameter list depending upon its functionality. The
parameter list consists of a list of parameters
separated by commas. Parameters are used to pass
data to a method. The parameter list is written
between parentheses after the method name. The
parentheses are included even if there are no
parameters.
Method body: This contains the set of
instructions that perform a specific task. The
variables declared inside the method body are known
as local variables.
While adding a method to a class, you should adhere to
the following method naming conventions:
The method names should be verb-noun pairs.
The first letter of the method should be in
lowercase.
If the method name consists of several words, the
first letter of each word, except the first word,
should be capitalized.
Example :
public int startGame()
Rules for creating a Java Constructor
1) It has the same name as the class
2)It should not return a value not even void
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
Constructor Overloading in Java
Constructor is a special method that is used to
initialize a newly created object and is called
just after the memory is allocated for the
object. It can be used to initialize the objects
to desired values or default values at the time
of object creation. It is not mandatory for the
coder to write a constructor for a class.
If no user-defined constructor is provided for
a class, compiler initializes member variables to
its default values.
 numeric data types are set to 0
 char data types are set to null character(‘0’)
 reference variables are set to null
Constructor Overloading in Java
Java Constructor overloading is a technique
in which a class can have any number of
constructors that differ in parameter list.
The compiler differentiates these
constructors by taking into account the
number of parameters in the list and their
type.
Examples of valid constructors for class
Account are
Account(int a);
Account (int a,int b);
Account (String a,int b);
class Demo{
int value1;
int value2;
Demo(){ //Default Constructor
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a){ //One Argument Constructor
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){ //One Argument Constructor
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display()
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Java Type Casting
Type casting is when you assign a value of one
primitive data type to another type.
In Java, there are two types of casting:
 Widening Casting (automatically) - converting a
smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger
type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a
smaller size type to a larger size type:
public class Main
{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt;
// Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the
type in parentheses in front of the value:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble;
// Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
Exercise 1
Predict the output of the following code:
class JumbledGame {
final int choice;
public static void main(String[] args) {
JumbledGame obj1 = new JumbledGame ();
System.out.println(obj1.choice);
}
}
Exercise 2
Write a program to create a class named SampleClass. The
SampleClass class should contain a variable named counter and
assign it the value, 1. Declare the counter variable as public. Create a
method named Display() in the class. The Display() method should
print the value of the counter variable. Create an object and access
the Display() method using the object.
Exercise 3
Create a Reservation class with a member variable, TicketID, and a
method, ShowTicket(). A constructor should initialize the TicketID
variable, and the ShowTicket() method should display its value. In
addition, create an object of the Reservation class to call these
methods.
Exercise 4
ServeYourMoney bank offers various services to its customers. The
bank has branches all over the country, and therefore, each branch
has a unique id. The bank stores the details of its customers, such as
customer name, account number, address, phone number, and email
address. In addition, the bank stores the various details of its
employees, such as employee name, employee id, address, phone
number, and email id. The bank offers its customers a choice of
accounts, such as savings account and current account. Ask the
students to identify the various classes, their member variables, and
data types.
Exercise 5
Create a Grocery class with a member variable, weight, and two
methods, weightNow() and checkWeight(). The weightNow() method
should initialize the weight variable and the checkWeight() method
should display its value. In addition, create an object of the Grocery
class to call the preceding methods.

More Related Content

Similar to Java programming Evolution-OverviewOfJava.pdf (20)

Java Concepts and Features-Programming in Java
Java Concepts and Features-Programming in JavaJava Concepts and Features-Programming in Java
Java Concepts and Features-Programming in Java
jasminebeulahg
 
Java
JavaJava
Java
seenak
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
DeepakChaudhriAmbali
 
Java programming Introduction | Java basic architecture
Java programming Introduction | Java basic architectureJava programming Introduction | Java basic architecture
Java programming Introduction | Java basic architecture
shaswinayyan
 
itft-Java evolution
itft-Java evolutionitft-Java evolution
itft-Java evolution
Atul Sehdev
 
Chapter 1 java
Chapter 1 java Chapter 1 java
Chapter 1 java
Ahmad sohail Kakar
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Elizabeth alexander
 
Java Basic.pdf
Java Basic.pdfJava Basic.pdf
Java Basic.pdf
TechSearchWeb
 
Ch2
Ch2Ch2
Ch2
Uğurcan Uzer
 
Java Notes .pdf
Java Notes .pdfJava Notes .pdf
Java Notes .pdf
gokulprasanna4
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
Qualys
 
Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
Peter Jose
 
1 .java basic
1 .java basic1 .java basic
1 .java basic
Indu Sharma Bhardwaj
 
Java
JavaJava
Java
Mariappans13
 
Java1
Java1Java1
Java1
computertuitions
 
Java
Java Java
Java
computertuitions
 
Introduction to java and it's opportunities
Introduction to java and it's opportunities Introduction to java and it's opportunities
Introduction to java and it's opportunities
VigneshManikandan11
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
ILOVE you11111111111111111111111111.pptx
ILOVE you11111111111111111111111111.pptxILOVE you11111111111111111111111111.pptx
ILOVE you11111111111111111111111111.pptx
RobertCarreonBula
 

Recently uploaded (20)

How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Ad

Java programming Evolution-OverviewOfJava.pdf

  • 1. History of Java  Java was developed by James Gosling, who is known as the father of Java, in 1995.  The history of Java starts with the Green Team. Java team members (James Gosling, Mike Sheridan, and Patrick Naughton), initiated the java language project in June 1991. The small team of sun engineers called Green Team.  Initially it was designed for small, embedded systems in electronic appliances like set-top boxes, televisions etc. However, it was best suited for internet programming.
  • 2. History of Java …… The principles for creating Java programming were "Simple, Robust, Portable, Platform- independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object- Oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given significant points that describe the history of Java. Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt .
  • 3. History of Java …… After that, it was called Oak and was developed as a part of the Green project. Why Java was named as "Oak"?  Oak is a symbol of strength and chosen as its a national tree of many countries like the U.S.A., France, Germany, Romania, etc.  In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.  Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
  • 4. History of Java …… Notice that Java is just a name, not an acronym. Finally JAVA was developed by James Gosling and his team at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995. In 1995, Time magazine called Java one of the Ten Best Products of 1995. JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications, cards, etc.
  • 5. Difference Between C, C++, and Java C is a general-purpose, structured, procedural, and high-level programming language developed by Dennis MacAlistair Ritchie in 1972 at Bell Laboratories. It is mainly used for system programming such as to develop the operating system, drivers, compilers, etc. The best-known example of the operating system that was developed using C language is Unix and Linux.
  • 6. Features of C Language Machine independent and portable Modern Control Flow and Structure Rich set of operators Simple, Fast, and efficient Case-sensitive Low memory use Easily extendable Statically-typed (variable types are known at compile time)
  • 7. C++ C++ is an object-oriented, general-purpose, programming language developed by Bjarne Stroustrup at Bell Labs in 1979. It is based on C language or we can say that it is an extension of C language. It is used to develop high-performance applications. Features of C++ Language  Case-sensitive  Compiler based  Platform-independent  Portability  Dynamic memory allocation
  • 8. Java Java is also an object-oriented, class-based, static, strong, robust, safe, and high-level programming language. It was developed by James Gosling in 1995. Its code is compiled and interpreted. It is used to develop enterprise, mobile, and web- based applications.
  • 10. Features of Java  Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because:  Java syntax is based on C++ (so easier for programmers to learn it after C++).  Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.  There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
  • 11. Features of Java  Architecture-neutral Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java. Java has a "binary code format" that's independent of hardware architectures, operating system interfaces, and window systems. The format of this system-independent binary code is architecture neutral.
  • 12. Features of Java  Object-oriented Java is an object-oriented language and it incorporates the various characteristics of an object-oriented language, such as Class, Object, inheritance and polymorphism, abstraction, encapsulation. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. In Java, the entire program code must be encapsulated inside a class. Even the most basic program in Java must be written within a class.  Platform independent In Java, when you compile an error-free code, the compiler converts the program to a platform independent code, known as the bytecode. Thereafter, the Java Virtual Machine (JVM) interprets this bytecode into the machine code that can be run on that machine.
  • 13. Features of Java ……. Converting a Java program into bytecode makes a Java program platform independent because any computer installed with the JVM can interpret and run the bytecode.  Portable Portability refers to the ability of a program to run on any platform without changing the source code of the program. The programs developed on one computer can run on another computer, which might have a different operating system. Java enables the creation of cross- platform programs by converting the programs into Java bytecode.
  • 14. Features of Java …….  Distributed Java can be used for the development of those applications that can be distributed on multiple machines in a network, such as the Internet. These applications can be used by multiple users from multiple machines in a network. For this purpose, Java supports the various Internet protocols, such as Transmission Control Protocol and Internet Protocol (TCP/IP) and Hyper Text Transfer Protocol (HTTP).  Secure: Java is best known for its built-in security features. With Java, we can develop virus-free systems. Java is secured because:  No explicit pointer  Java Programs run inside a virtual machine sandbox Java program gains access to only those resources of a computer that are essential for its execution. This ensures that a Java program executing on a particular machine does not harm it
  • 15. Secured  Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources.  Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.  Security Manager: It determines what resources a class can access such as reading and writing to the local disk.  Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
  • 16. Features of Java ……. Robust: The English meaning of Robust is strong. Java is robust because:  It uses strong memory management.  There is a lack of pointers that avoids security problems.  Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.  There are exception handling and the type checking mechanism in Java. All these points make Java robust.
  • 17. Multithreaded: Java provides the concept of multithreading that allows a program to simultaneously execute multiple tasks by using threads. A thread is the smallest unit of execution in a Java program. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. Dynamic Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and automatic memory management (garbage collection).
  • 23. Java and Internet Java is strongly associated with the Internet. Internet users can use Java to create applet programs and run them locally using a "Java-enabled browser" such as HotJava. They can also use a Java-enabled browser to download an applet located on a computer anywhere in the Internet and run it on his local computer. In fact, Java applets have made the Internet a true extension of the storage system of the local computer. Internet users can also setup their websites containing java applets that could be used by other remote users of Internet. This feature made Java most popular programming language for Internet.
  • 24. Java and World Wide Web World Wide Web (WWW) is an open-ended information retrieval system designed to be used in the Internet's distributed environment. This system contains Web pages that provide both information and controls. Web system is open-ended and we can navigate to a new document in any direction. This is made possible with the help of a language called Hypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide. Java was meant to be used in distributed environments such as Internet. Java could be easily incorporated into the Web system. Before Java, the World Wide Web was limited to the display of still images and texts. However, the incorporation of Java into Web pages has made it capable of supporting animation, graphics, games, and a wide range of special effects.
  • 25. Java Architecture The Java architecture defines the components that are essential to carry out the creation and execution of code written in the Java programming language. The various components of the Java architecture are:  Source file  Class file  JVM  Application Programming Interface (API)
  • 26. The various components in the Java architecture are shown in the following figure.
  • 27. Source File Java is a robust programming language that enables developers to build a wide variety of applications for varying purposes. In order to write a Java program or an application, you need to write certain code. A Java application contains the source code that enables an application to provide its desired functionalities. This source code is saved in a source file with the extension, .java. Class File Once created, a .java file is compiled to generate the .class file. A class file contains the bytecode that is generated by the compiler. Further, this class file can be executed by any machine that supports the Java Runtime Environment (JRE).
  • 28. Java Development Kit (JDK) JDK is a software development environment used for developing Java applications and applets. It includes :  Java Runtime Environment (JRE),  an interpreter/loader (Java),  a compiler (javac), an archiver (jar),  a documentation generator (Javadoc), and other tools needed in Java development.
  • 29. JRE (Java Runtime Environment) Java Runtime Environment (JRE) is an open- access software distribution that has a Java class library, specific tools, and a separate JVM. JRE is one of the interrelated components in the Java Development Kit (JDK). It is the most common environment available on devices for running Java programs. Java source code is compiled and converted to Java bytecode. If we want to run this bytecode on any platform, you need JRE in turn JVM. The JRE loads classes, check memory access and get system resources. JRE acts as a software layer on top of the operating system.
  • 30. JVM The JVM is an application that is responsible for executing Java programs on a computer. It resides in the Random Access Memory (RAM) and is specific for every platform, such as Sun and Macintosh. The bytecode generated during the compilation of a program is the machine language of the JVM. JVM is responsible for executing the bytecode and generating the machine specific code for the machine on which the Java program needs to be executed. The major components of JVM are:  Class loader  Execution engine and Just-In-Time (JIT) compiler  Bytecode verifier
  • 31. Class Loader The class loader loads the class files required by a program that needs to be executed. The classes are loaded dynamically when required by the running program. Execution Engine and JIT Compiler The Java execution engine acts as an interpreter that interprets the bytecode one line after another and executes it. The line-by-line interpretation is a time- consuming task and reduces the performance of a program. To enhance the performance, the JIT compiler has been introduced in the JVM. The JIT compiler compiles the bytecode into machine executable code, as and when needed, which optimizes the performance of a Java program.
  • 32. Bytecode Verifier Before being executed by the JVM, the bytecode is verified by using the bytecode verifier. The bytecode verifier ensures that the bytecode is executed safely and does not pose any security threat to the machine. API The Java API is a collection of software components, such as classes, interfaces, and methods, which provides various capabilities, such as GUI, Date and Time, and Calendar. The related classes and interfaces of the Java API are grouped into packages.
  • 33. Simple Java Program Structure Documentation (Comment) Section Package Statement Import Statement Class Definition Main Method Class Documentation (Comment) Section It is used to improve the readability of the program. The compiler ignores these comments during the time of execution and is solely meant for improving the readability of the Java program. There are three types of comments that Java supports  Single line Comment  Multi-line Comment  Documentation Comment
  • 34. Documentation (Comment) Section / a single line comment is declared like this /* a multi-line comment is declared like this and can have multiple lines as a comment */ /** a documentation comment starts with a delimiter and ends with */ Package Statement There is a provision in Java that allows you to declare your classes in a collection called package. There can be only one package statement in a Java program and it has to be at the beginning of the code before any class or interface declaration. This statement is optional. Example: package student;
  • 35. Import Statement Many predefined classes are stored in packages in Java, an import statement is used to refer to the classes stored in other packages. An import statement is always written after the package statement but it has to be before any class declaration. We can import a specific class or classes in an import statement. Take a look at the example to understand how import statement works in Java. Ex:- import java.util.Date; //imports the date class import java.applet.*; //imports all the classes from the java applet package
  • 36. Class Definition A Java program may contain Several class definitions, classes are an essential part of any Java program. It defines the information about the user-defined classes in a program. A class is a collection of variables and methods that operate on the fields. Every program in Java will have at least one class with the main method.
  • 37. Main Method The main method is from where the execution actually starts and follows the order specified for the following statements. Let’s take a look at a sample program to understand how it is structured. public class Example{ //main method declaration public static void main(String[] args){ System.out.println("hello world"); } } public class Example This creates a class called Example. You should make sure that the class name starts with a capital letter, and the public word means it is accessible from any other classes.
  • 38. Comments To improve the readability, we can use comments to define a specific note or functionality of methods, etc for the programmer. Curly Braces The curly brackets are used to group all the commands together. To make sure that the commands belong to a class or a method.
  • 39. public static void main  When the main method is declared public, it means that it can be used outside of this class as well.  The word static means that we want to access a method without making its objects. As we call the main method without creating any objects.  The word void indicates that it does not return any value. The main is declared as void because it does not return any value.  Main is the method, which is an essential part of any Java program.
  • 40. String[] args It is an array where each element is a string, which is named as args. If you run the Java code through a console, you can pass the input parameter. The main() takes it as an input. System.out.println(); The statement is used to print the output on the screen where the system is a predefined class, out is an object of the PrintWriter class. The method println prints the text on the screen with a new line. All Java statements end with a semicolon. Example : Java Application having two classes in one file.
  • 41. package comp public class Computer { Computer() { System.out.println("Constructor of Computer class."); } void computer_method() { System.out.println("Power gone! Shut down your PC soon..."); } public static void main(String[] args) { Computer c = new Computer(); Laptop l = new Laptop(); c.computer_method(); l.laptop_method(); } } class Laptop { Laptop() { System.out.println("Constructor of Laptop class."); } void laptop_method() { System.out.println("99% Battery available."); } }
  • 42. What is token in Java? In Java, the program contains classes and methods. Further, the methods contain the expressions and statements required to perform a specific operation. These statements and expressions are made up of tokens. In other words, we can say that the expression and statement is a set of tokens. The tokens are the small building blocks of a Java program that are meaningful to the Java compiler. The Java compiler breaks the line of code into text (words) is called Java tokens. These are the smallest element of the Java program. The Java compiler identified these words as tokens. These tokens are separated by the delimiters. It is useful for compilers to detect errors.
  • 44. Defining a Class A class defines the characteristics and behavior of an object. For example, if you create a gaming application, each game that a user can play from the application can be considered as an object of the Games class. Each game has common characteristics, such as the number of players, game category, and score. These characteristics are known as the member variables, and the behavior is specified by methods. Any concept that you need to implement in a Java program is encapsulated within a class. A class defines the member variables and methods of objects that share common characteristics. Further, all the games have common methods, such as calculating score, starting the game, and displaying game instructions.
  • 45. The following code snippet shows how to declare a class: class <ClassName> { //Declaration of member variables //Declaration of methods } In the preceding code snippet, the word, class, is a keyword in Java that is used to declare a class and <ClassName> is the name given to the class. We can use the following code snippet to create the ClassicJumble class to develop the Classic Jumble Word game: class ClassicJumble { //Declaration of member variables //Declaration of methods }
  • 46. There are certain rules that should be followed to name Java classes. A program will raise error if these rules are not followed. Some of these rules are:  The name of a class should not contain any embedded space or symbol, such as ?, !, #, @, %, &, {}, [], :, “, and /.  A class name must be unique.  A class name must begin with a letter, an underscore (_), or the dollar symbol ($). Or, it must begin with an alphabet that can be followed by a sequence of letters or digits (0 to 9), ‘$’, or ‘_’.  A class name should not consist of a keyword. While naming a class, you should adhere to the following class naming conventions that improve the readability of a program:  The class name should be a noun.  The first letter of the class name should be capitalized.  If the class name consists of several words, the first letter of each word should be capitalized.
  • 47. After defining a class, you need to save the file before it can be executed. The following naming conventions should be followed for naming a Java file:  A file name must be unique.  A file name cannot be a keyword.  If a class is specified as public, the file name and class name should be the same.  If a file contains multiple classes, only one class can be declared as public. The file name should be the same as the class name that is declared public in the file.  If a file contains multiple classes that are not declared public, any file name can be specified for the file.
  • 48. Identifying Data Types While working with an application, you need to store and manipulate varying data. For example, in the Classic Jumble Word game, the game score is a numeric value and the player name is a string. To handle such varying data in an application, Java supports various data types. There are eight primitive data types in Java, which are further grouped into the following categories:
  • 49.  Integer type: Can store integer values. The four integer data types are:  byte  short  int  Long The following table lists the integer primitive data type, its data types, size, range, and default values. Group Data Type Size Range Default Value Integer byte 1 byte -27 to 27-1 0 short 2 bytes -215 to 215 -1 0 int 4 bytes -231 to 231-1 0 long 8 bytes -263 to 263-1 0 The Details of the Integer Primitive Data Type
  • 50.  Floating point type: Can store decimal numbers. The two floating point types are:  float  Double The following table lists the floating point primitive data type, its data types, size, range, and default values. Group Data Type Size Range Defau lt Value Floating point float 4 bytes 3.4e-038 to 3.4e+038 0.0 double 8 bytes 1.7e-308 to 1.7e+308 0.0
  • 51. Boolean type: Can store only the values, true and false. Character type: Can store a single character, such as a symbol, letter, and number. In the character type, there is one data type, char. To a character data type, 2 bytes of memory is allocated. Note :- To store string values, you need to use built-in classes, such as, String, StringBuilder, and StringBuffer.
  • 52. Wrapper Classes Variables that are declared by using the primitive data types are not objects. The primitive data types, such as int and char, are not a part of the object hierarchy. Therefore, in order to use the primitive data types as objects, Java provides wrapper classes. A wrapper class acts like an object wrapper and encapsulates the primitive data types within the class so it can be treated like an object. The various wrapper classes, such as Boolean, Byte, Character, Integer, Short, Long, Double, and Float, are provided by the java.lang package. These classes are useful when you need to manipulate primitive data types as objects.
  • 53. Autoboxing and Unboxing The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. Advantages of Autoboxing and Unboxing No need of conversion between primitives and Wrappers manually so less coding is required. class BoxingExample1{ public static void main(String args[]){ int a=50; Integer a2=new Integer(a);//Boxing Integer a3=5;//Boxing //Integer a3=Integer.valueOf(5) System.out.println(a2+" "+a3); } }
  • 54. Example of Unboxing in java The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let's see the example of unboxing: class UnboxingExample1{ public static void main(String args[]) { Integer i=new Integer(50); int a=i; //int a=i.intValue(); System.out.println(a); } }
  • 55. Identifying Class Members In Java, a class can contain the following members:  Variables  Methods  Objects  Inner classes
  • 56. 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. There are two types of data types in Java: primitive and non-primitive. Variable A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed. There are three types of variables in java: local, instance and static.
  • 57. Variable A variable needs to be declared before it is accessed. The declaration of a variable informs the compiler about the variable name and the type of value stored in it. The following code snippet shows how to declare a variable: <type> <variablename>; // Single variable of given type. <type> <variable1name,variable2name.....variable_n_name>; // Multiple variables of given type. int choice; int num1, num2; The following code snippet shows how to assign values to a variable: <type> <variablename>=<value>; // During declaration. <variablename>=<value> // After declaration.
  • 58. For example, you can use the following code snippet to assign values to the variables, num1 and num2: int num1, num2; // Declaration of variables. num1 = 5; // Assigning values to the variables. num2 =10; The following code snippet can be used to assign a value to a variable at the time of its declaration. int num1=5; You can also assign the same value to more than one variable in a single statement. The following code snippet shows the assignment of the same value to more than one variable: a=b=c=3; In the preceding code snippet, the integer value, 3, is first assigned to c, then to b, and finally to a.
  • 59. Literal in a JAVA Program To understand the type of values that a variable can contain, you need to understand the concept of literals. A literal is a value that is assigned to a variable or constants in a Java program. A literal contains a sequence of characters, such as digits, alphabets, or any other symbol, which represents the value to be stored. The various types of literals in Java are:  Integer literals: Are non-fractional numeric values. The numerical values can be represented in the decimal, octal, and hexadecimal notation. In order to represent an octal number, it is preceded by zero. In order to represent hexadecimal numbers, they are prefixed by 0x. For example, n=0567 is integer literal represented in the octal notation whereas n=0x124 represents an integer literal in hexadecimal notation.
  • 60. Floating point literals: Are numeric values that contain a fractional part. The floating point literals contain a decimal and an integer part. For example, z=2.2 represents a floating point literal. Character literals: Are represented inside a pair of single quotation marks. For example, x='k' is a character literal. String literals: Are enclosed in a pair of double quotation marks. For example, x="James" is a string literal. Boolean literals: Are the literals that can contain the values, true or false. For example, x= false is a boolean literal. Binary literals: Are the literals that can be used to express the primitive integer data types into binary form. In order to specify these literals, you need to prefix the binary number with 0b or 0B. For example, 0b101.
  • 62. 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.
  • 63. // Java Program to Illustrate Working Of Function Calling // Class class LocalVar { public static int findSum(int a, int b) { int sum = a + b; //Local Variable return sum; } public static void main(String[] args) { int a = 10, b = 20; //Local Variable int c = findSum(a, b); System.out.print(c); } }
  • 64. 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. It is called an instance variable because its value is instance-specific and is not shared among instances. Features of an instance variable The life of an instance variable depends on the life of an Object, i.e., when the object is created, an instance variable also gets created.
  • 65. public class Student { String name; int marks; Student (String stuName) { name = stuName; } public void setMarks(int stuMar) { marks = stuMar; } // This method prints the student details. public void printStudent() { System.out.println("Name: " + name ); System.out.println("Marks:" + marks); } public static void main(String args[]) { Student StudentOne = new Student("Ankit"); Student StudentTwo = new Student("Akshat"); Student StudentThree = new Student("Vikram"); StudentOne.setMarks(98); StudentTwo.setMarks(89); StudentThree.setMarks(90); StudentOne.printStudent(); StudentTwo.printStudent(); StudentThree.printStudent(); } }
  • 66. Java Scanner Class The Scanner class of the java.util package is used to read input data from different sources like input streams, users, files, etc. The Scanner class provides various methods that allow us to read inputs of different types.
  • 67. Method Description nextInt() reads an int value from the user nextFloat() reads a float value form the user nextBoolean() reads a boolean value from the user nextLine() reads a line of text from the user next() reads a word from the user nextByte() reads a byte value from the user nextDouble() reads a double value from the user nextShort() reads a short value from the user nextLong() reads a long value from the user
  • 68. import java.util.Scanner; class Scanner1 { String name,gender; Byte age; Integer qty; Double rate; Boolean status; public void input() { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard name = input.nextLine(); System.out.print("Enter your Gender: "); gender=input.next(); System.out.print("Enter your Age: "); age=input.nextByte(); System.out.print("Enter Item Quantity :"); qty=input.nextInt(); System.out.print("Enter Rate of Item (Double) :"); rate=input.nextDouble(); System.out.print("Are you above 18?- :(True/False)"); status = input.nextBoolean(); }
  • 69. public void display() { // prints the name System.out.println("nnnnnMy name is :" + name); System.out.println("My Gender is :" + gender); System.out.println("My Age is :" + age); System.out.println("Rate of Item :" + rate); System.out.println("Item Quantity : " + qty); if (status == true) { System.out.println("You are over 18"); } else if (status == false) { System.out.println("You are under 18"); } } public static void main(String[] args) { Scanner1 obj=new Scanner1(); obj.input(); obj.display(); } }
  • 70. Static Members Variables and methods declared using keyword static are called static members of a class. We know that non-static variables and methods belong to instance. But static members (variables, methods) belong to class. Static members are not part of any instance of the class. Static members can be accessed using class name directly, in other words, there is no need to create instance of the class specifically to use them. Static members can be of two types: Static Variables Static Methods
  • 71. Static Variable  A static variable is associated with a class rather than an instance. A static field is declared using the static keyword.  Static variables are shared across all instances of a class.  There is only one copy of a static variable per class.  Non-static variables cannot be called inside static methods.  If any instance of a class modifies the value of a static variable, the change is reflected across all instances of the class.  Static variables are memory-efficient as they are not duplicated for each instance.
  • 72. Static Variables Static variables are also called class variables because they can be accessed using class name, whereas, non static variables are called instance variables and can be accessed using instance reference only. Static variables occupy single location in the memory. These can also be accessed using instance reference. These are accessible in both static and non- static methods, even non-static methods can change their values.
  • 73. While declaration, there is no need to initialize the static variables explicitly because they take default values like other non-static variables (instance variables). Now, the question is, why to use static variables? Let us look at a reason for using one. Suppose you want to keep record about the number of running instances of a class. In this situation, it would be better to declare a static variable.
  • 74. Static Methods/Class Methods Static methods are also called class methods. A static method belongs to class, it can be used with class name directly. It is also accessible using instance references. Static methods can use static variables only, whereas non-static methods can use both instance variables and static variables. Implementation: The following program uses a static counter variable and static method showCount() method to track the number of running instances of the class student in the memory.
  • 75. class Student { private static int count=0; //static variable Student() { count++; //increment static variable } static void showCount() //static method { System.out.println(“Number Of students : “+count); } } public class StaticDemo { public static void main(String[] args) { Student s1=new Student(); Student s2=new Student(); Student.showCount(); //calling static method Student s3=new Student(); Student s4=new Student(); s4.showCount(); //calling static method } }
  • 76. class Country { // Static variable static int countryCounter; String name; int counter; Country() //Constructor function { countryCounter++; } public static void main(String[] args) { Country ob1 = new Country(); // Creating first instance // Assigning values to object's data variables. ob1.name = "India"; ob1.counter = 1; Country ob2 = new Country(); // Creating second instance ob2.name = “South Africa"; ob2.counter = 1; System.out.println("ob1.countryCounter = " + ob1.countryCounter); System.out.println("ob2.countryCounter = " + ob2.countryCounter); System.out.println("Country.countryCounter = " + Country.countryCounter); } }
  • 77. Java Command Line Arguments The command-line arguments in Java allow the programmers to pass the arguments during the execution of a program. The users can pass the arguments during the execution by passing the command-line arguments inside the main() method. We need to pass the arguments as space-separated values. We can pass both strings and primitive data types(int, double, float, char, etc) as command-line arguments to JVM. These arguments get stored as Strings in a String array that is passed to the main() function. We can use these command-line arguments as input in our Java program.
  • 78. // Java Program to Check for Command Line Arguments class CommandLine { // Main driver method public static void main(String[] args) { // Checking if length of args array is greater than 0 if (args.length > 0) { // Print statements System.out.println("The command line arguments are:"); // Iterating the args array // using for each loop for (String val : args) // Printing command line arguments System.out.println(val); } else // Print statements System.out.println("No command line "+ "arguments found."); } }
  • 79. package mypack; public class CommandLine { public static void main(String []args) { System.out.println("Welcome to java Class"); System.out.println("Command Line Arguments are:"); for (String s : args) System.out.println("Command Line Arguments are :->"+s); } }
  • 80. public class Arguments { public static void main(String args[]) { int sum=0; System.out.println("Sum of all numbers are"); for(int i=0;i<args.length;i++) { sum=sum+Integer.parseInt(args[i]); } System.out.println("Sum of numbers is "+sum); } }
  • 81. public class Tables { public static void main(String args[]) { int n=0; System.out.println("Table of "+args[0]); for(int i=1;i<=10;i++) { n=Integer.parseInt(args[0]); System.out.println(n+" * "+i+" = "+n*i); } } }
  • 82. Java Constant  Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final.  In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.
  • 83. Static and Final Modifiers  The purpose to use the static modifier is to manage the memory.  It also allows the variable to be available without loading any instance of the class in which it is defined.  The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable.
  • 84. import java.util.Scanner; public class ConstantExample1 { //declaring constant private static final double PRICE=234.90; public static void main(String[] args) { int unit; double total_bill; PRICE=900; System.out.print("Enter the number of units you have used: "); Scanner sc=new Scanner(System.in); unit=sc.nextInt(); total_bill=PRICE*unit; System.out.println("The total amount you have to deposit is: "+total_bill); } }
  • 85. Method or Function A method is a set of statements that is intended to perform a specific task. For example, a compute() method can be used for computing the score. Moreover, methods provide encapsulation and are also essential to refer to the data members and access them. A method consists of two parts, method declaration and method body. The syntax for defining a method is: <Access specifier> <Return type> <Method name>(Parameter list) //method declaration { <Method body> // body of the method }
  • 86. In the preceding syntax, the first line depicts the method declaration and the contents within the curly braces depict the method body. According to the preceding syntax, the various elements of a method are:  Access specifier: Determines the extent to which a method can be accessed from another class.  Return type: A method can also return a value. The return type specifies the data type of the value returned by a method. Some methods do not return any value. Such methods should use the void return type. The value to be returned by the method is specified with the keyword, return.  Method name: Is a unique identifier and is case- sensitive.
  • 87. Parameter list: A method may or may not contain a parameter list depending upon its functionality. The parameter list consists of a list of parameters separated by commas. Parameters are used to pass data to a method. The parameter list is written between parentheses after the method name. The parentheses are included even if there are no parameters. Method body: This contains the set of instructions that perform a specific task. The variables declared inside the method body are known as local variables.
  • 88. While adding a method to a class, you should adhere to the following method naming conventions: The method names should be verb-noun pairs. The first letter of the method should be in lowercase. If the method name consists of several words, the first letter of each word, except the first word, should be capitalized. Example : public int startGame()
  • 89. Rules for creating a Java Constructor 1) It has the same name as the class 2)It should not return a value not even void class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); d1.display(); } }
  • 90. Constructor Overloading in Java Constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation. It is not mandatory for the coder to write a constructor for a class. If no user-defined constructor is provided for a class, compiler initializes member variables to its default values.  numeric data types are set to 0  char data types are set to null character(‘0’)  reference variables are set to null
  • 91. Constructor Overloading in Java Java Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter list. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. Examples of valid constructors for class Account are Account(int a); Account (int a,int b); Account (String a,int b);
  • 92. class Demo{ int value1; int value2; Demo(){ //Default Constructor value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); } Demo(int a){ //One Argument Constructor value1 = a; System.out.println("Inside 2nd Constructor"); } Demo(int a,int b){ //One Argument Constructor value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); }
  • 93. public void display() { System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); } }
  • 94. Java Type Casting Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting:  Widening Casting (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double  Narrowing Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char -> short -> byte
  • 95. Widening Casting Widening casting is done automatically when passing a smaller size type to a larger size type: public class Main { public static void main(String[] args) { int myInt = 9; double myDouble = myInt; // Automatic casting: int to double System.out.println(myInt); // Outputs 9 System.out.println(myDouble); // Outputs 9.0 } }
  • 96. Narrowing Casting Narrowing casting must be done manually by placing the type in parentheses in front of the value: public class Main { public static void main(String[] args) { double myDouble = 9.78d; int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // Outputs 9.78 System.out.println(myInt); // Outputs 9 } }
  • 97. Exercise 1 Predict the output of the following code: class JumbledGame { final int choice; public static void main(String[] args) { JumbledGame obj1 = new JumbledGame (); System.out.println(obj1.choice); } } Exercise 2 Write a program to create a class named SampleClass. The SampleClass class should contain a variable named counter and assign it the value, 1. Declare the counter variable as public. Create a method named Display() in the class. The Display() method should print the value of the counter variable. Create an object and access the Display() method using the object. Exercise 3 Create a Reservation class with a member variable, TicketID, and a method, ShowTicket(). A constructor should initialize the TicketID variable, and the ShowTicket() method should display its value. In addition, create an object of the Reservation class to call these methods.
  • 98. Exercise 4 ServeYourMoney bank offers various services to its customers. The bank has branches all over the country, and therefore, each branch has a unique id. The bank stores the details of its customers, such as customer name, account number, address, phone number, and email address. In addition, the bank stores the various details of its employees, such as employee name, employee id, address, phone number, and email id. The bank offers its customers a choice of accounts, such as savings account and current account. Ask the students to identify the various classes, their member variables, and data types. Exercise 5 Create a Grocery class with a member variable, weight, and two methods, weightNow() and checkWeight(). The weightNow() method should initialize the weight variable and the checkWeight() method should display its value. In addition, create an object of the Grocery class to call the preceding methods.