Java Material-2
Java Material-2
History of JAVA:
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.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence
of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) 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.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) 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. Each
new version adds new features in Java.
Topic:2--------------------
Principles/Buzzwords/Features:
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Multithreaded
9. Distributed
10. Dynamic
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:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o 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.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
o 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.
Robust
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.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it 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++.
Program Structure in Java:
o Documentation Section
o Package Declaration
o Import Statements
o Class Definition/ Interface Section/ enum
o Main Method declaration
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To write
the statements in the documentation section, we use comments. The comments may be single-
line, multi-line, and documentation comments.
For example:
o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols.
For example:
/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */.
For example:
/**
*/
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can be only
one package statement in a Java program. It must be defined before any class and interface
declaration. It is necessary because a Java class can be placed in different packages and
directories based on the module they are used. For all these classes package belongs to a single
parent directory. We use the keyword package to declare the package name.
For example:
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class
of a particular package, we need to import that class. The import statement represents the class
stored in the other package. We use the import keyword to import the class. It is written before
the class declaration and after the package statement. We use the import statement in two ways,
either import a specific class or import all classes of a particular package. In a Java program,
we can use multiple import statements. For example:
Interface Section
For example:
1. interface car
2. {
3. void start();
4. void stop();
5. }
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. A Java program may conation more than one class definition.
We use the class keyword to define the class. The class is a blueprint of a Java program. It
contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:
In this section, we define the main() method. It is essential for all Java programs. Because the
execution of all Java programs starts from the main() method. In other words, it is an entry
point of the class. It must be inside the class. Inside the main method, we create objects and
call the methods. We use the following statement to define the main() method:
For example:
Sample Program:
// Package Declaration
package com.example.basic;
// import Statement
import java.lang
/**
* The HelloWorld class contains the main method which is the entry point of the program.
*/
public class HelloWorld {
/**
* The main method is the entry point of the program.
* It prints "Hello, World!" to the console.
*
* @param args Command line arguments (not used in this example).
*/
public static void main (String [] args) {
// Print "Hello, World!" to the console
System.out.println("Hello, World!");
}
}
Elements or Tokens 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.
Types of Tokens:
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
Literal Type
23 int
9.86 double
"javatpoint" String
Operators: In programming, operators are the special symbol that tells the compiler to perform
a special operation. Java provides different types of operators that can be classified according
to the functionality they provide. There are eight types of operators in Java, are as follows:
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Separators: The separators in Java is also known as punctuators. The separators in Java, are
as follows:
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the two-
dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:
Types of Statements:
In Java, a statement is an executable instruction that tells the compiler what to perform. It
forms a complete command to be executed and can include one or more expressions. A sentence
forms a complete idea that can include one or more clauses.
o Expression Statements
o Declaration Statements
o Control Statements
Expression Statements
Expression is an essential building block of any Java program. Generally, it is used to generate
a new value. Sometimes, we can also assign a value to a variable. In Java, expression is the
combination of values, variables, operators, and method calls.
o Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note
that the expression enclosed in the parentheses will be evaluate first, after that rest of
the expression.
o Expressions that assign a value. For example, number = 90, pi = 3.14.
o Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement operator
respectively, method invocation, etc.
Declaration Statements
In declaration statements, we declare variables and constants by specifying their data type and
name. A variable holds a value that is going to use in the Java program. For example:
1. int quantity;
2. boolean flag;
3. String message;
Java also allows us to declare multiple variables in a single declaration statement. Note that all
the variables must be of the same data type.
Control Statement
Control statements decide the flow (order or sequence of execution of statements) of a Java
program. In Java, statements are parsed from top to bottom. Therefore, using the control flow
statements can interrupt a particular section of a program based on a certain condition.
Example of Statement
1. //declaration statement
2. int number;
3. //expression statement
4. number = 412;
5. //control flow statement
6. if (number > 10 )
7. {
8. //expression statement
9. System.out.println(number + " is greater than 100");
10. }
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. These
arguments convert into a string array and are provided to the main() function as a string array
argument.
When command-line arguments are supplied to JVM, JVM wraps these and supplies them to
args[]. It can be confirmed that they are wrapped up in an args array by checking the length
of args using args.length.
Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass
into the main() function. We can check these arguments using args.length method. JVM
stores the first command-line argument at args[0], the second at args[1], the third at args[2],
and so on.
Example:
class CommandLineDemo2{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
User Input to Programs:
In Java, user input can be obtained from various sources, such as the keyboard, files, or
network connections. One of the most common ways to get user input is through the
console using the Scanner class, which is part of the java.util package. Understanding how
to handle user input is essential for creating interactive programs that respond to user
actions.
Using the Scanner Class
The Scanner class provides methods to read different types of input, including strings,
integers, and floating-point numbers. It simplifies the process of parsing primitive types
and strings using regular expressions. Here’s a brief overview of how to use the Scanner
class to read user input from the console.
Example of Reading User Input
Below is an example program that demonstrates how to read different types of user input
using the Scanner class:
1) Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2) Non-primitive or User_defined : The non-primitive data types
include Classes, Interfaces, and Arrays.
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
Example:
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is
0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive). The char data type is used to store characters.
Example:
char letterA = 'A'
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range
of Unicode system.
Declaration of Variables:
Syntax:
Data_type variable_name;
Example:
1) //Java Variable Declaration Example: With Initialization
Scope of Variables:
1. public SumExample
2. {
3. public void calculateSum() {
4. int a = 5; // local variable
5. int b = 10; // local variable
6. int sum = a + b;
7. System.out.println("The sum is: " + sum);
8. } // a, b, and sum go out of scope here
9. }
2.Instance Variables (Non-Static Variables): These variables are declared within a class
but outside any method, constructor, or block. They belong to an instance of the class and
can have different values for different instances. Instance variables are created when an
object of the class is instantiated and are accessible as long as the object exists.
Example:
1. class MyClass {
2. // Static variable
3. static int rollno = 42;
4. public static void main(String[] args)
5. {
6. // Accessing the static variable using the class name
7. System.out.println(MyClass.rollno);
8. // Modifying the static variable using the class name
9. MyClass.rollno = 99;
10. System.out.println(MyClass.rollno);
11. }
12. }
Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
o Static methods cannot directly access instance variables or instance methods of the
class. They can only access static variables and other static methods.
o Static methods cannot use the “this” keyword, as there is no instance associated with
static methods.
o You can invoke a static method using the class name, like
“ClassName.methodName()”, or directly from within other static methods of the same
class.
Example:
public class Demo {
In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler and
manual conversion performed by the programmer.
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:
Example:
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting then the compiler reports a compile-time error.
Example:
Note:
Literals in Java
Literal: Any constant value which can be assigned to the variable is called literal/constant.
In simple words, Literals in Java is a synthetic representation of boolean, numeric, character,
or string data.
Types of Literals in Java
1. Integral literals
For Integral data types (byte, short, int, long), we can specify literals in 4 ways:-
Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9, and characters are
a-f. We can use both uppercase and lowercase characters as we know that java is a case-
sensitive programming language, but here java is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
Binary literals: From JAVA 1.7 onward, we can specify literal value even in binary form
also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;
2.Floating-Point literal
For Floating-point data types, we can specify literals in only decimal form, and we cant
specify in octal and Hexadecimal forms.
Decimal literals (Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
3.Char literals
4.String literals
5.Boolean literals
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
Symbolic constants
In Java, a symbolic constant is a named constant value defined once and used throughout a
program. Symbolic constants are declared using the final keyword.
Which indicates that the value cannot be changed once it is initialized.
The naming convention for symbolic constants is to use all capital letters with
underscores separating words.
Syntax of Symbolic Constants
final data_type CONSTANT_NAME = value;
Example:
final double PI = 3.14159;
Final Keyword
The `final` keyword in Java is a non-access modifier that can be applied to variables, methods,
and classes. It is used to impose restrictions on these elements, ensuring that their behavior
cannot be altered.
The following are different contexts where the final is used:
1. Variable
2. Method
3. Class