0% found this document useful (0 votes)
12 views30 pages

Java Material-2

Uploaded by

akbarnptel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views30 pages

Java Material-2

Uploaded by

akbarnptel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

Topic:1---------------------------------------

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.

9) Notice that Java is just a name, not an acronym.


10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.

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

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

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

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o 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.
o There are exception handling and the type checking mechanism in Java. All these points
make Java 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:

Java is an object-oriented, platform-independent, and secure programming language, which


contributes to its widespread popularity. With Java, we can develop a diverse range of
applications, from web and mobile to enterprise and embedded systems. Before exploring Java
in depth, it is essential to understand the basic structure of a Java program. This section will
cover the fundamental components of a Java program.

A typical structure of a Java program contains the following elements:

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.

o Single-line Comment: It starts with a pair of forwarding slash (//).

For example:

//First Java Program

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:

/**

* The BasicStructure class demonstrates the basic structure of a Java program.

* It includes a package declaration, import statements, a class declaration,

* a main method, and an additional method.

*/

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:

1. package javatpoint; //where javatpoint is the package name


2. package com.javatpoint; //where com is the root directory and javatpoint is the subdi
rectory

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:

1. import java.util.Scanner; //it imports the Scanner class only


2. import java.util.*; //it imports all the class of the java.util package

Interface Section

It is an optional section. We can create an interface in this section if required. We use


the interface keyword to create an interface. An interface is a slightly different from the class.
It contains only constants and method declarations. Another difference is that it cannot be
instantiated. We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword.

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:

1. class Student //class definition


2. {
3. }

Main Method Declaration

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:

1. public class Student //class definition


2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }

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.

Some valid identifiers are:

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

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

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 = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

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:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */.

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.

Java statements can be broadly classified into the following categories:

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.

There are three types of expressions in Java:

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.

1. int quantity, batch_number, lot_number;


2. boolean flag = false, isContains = true;
3. String message = "Hello", “how are you”;

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. }

Command Line Arguments in Java


Java command-line argument is an argument i.e. passed at the time of running the Java
program. In Java, the command line arguments passed from the console can be received in
the Java program and they can be used as input. The users can pass the arguments during the
execution bypassing the command-line arguments inside the main() method.

Working command-line arguments

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:

// Illustration of a user's input from keyboard into program


import java.util.Scanner;

public class UserInputForSum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt user for first number


System.out.print("Enter the first number: ");
int firstNumber = scanner.nextInt();

// Prompt user for second number


System.out.print("Enter the second number: ");
int secondNumber = scanner.nextInt();

// Calculate and display the sum


int sum = firstNumber + secondNumber;
System.out.println("The sum of the two numbers is: " + sum);

scanner.close(); // Close the Scanner object (good practice)


}
}
Data Types
Data types are a fundamental concept that define the kind of data that can be stored and
manipulated within a program. Java, a statically-typed programming language, every variable
must be declared with a specific data type, ensuring that the variable only holds data of that
type. This strong type-checking mechanism helps catch errors at compile-time, leading to more
robust and reliable code.

There are two types of data types in Java:

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:

Boolean one = false


Byte Data Type

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:

byte a = 10, byte b = -20


Short Data Type

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:

short s = 10000, short r = -5000


Int Data Type

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:

int a = 100000, int b = -200000


Long Data Type

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:

long a = 100000L, long b = -200000L


Float Data Type

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'

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range
of Unicode system.

Declaration of Variables:

 In Java, variables act as your data storage containers.


 Declaring a variable involves specifying its data type, giving it a clear name, and
optionally assigning an initial value.
 This sets the stage for how your program uses information. Where you declare the
variable determines its accessibility (local, instance, or class-wide), similar to different
storage areas in a building project.

Syntax:
Data_type variable_name;
Example:
1) //Java Variable Declaration Example: With Initialization

2) public class CreateVariable {


3) public static void main(String[] args)
4) {
5) //variable declaration
6) int student_id = 10;
7) String student_name = "Java coder";
8) double numbers = 3.21;
9) Boolean shows = true;
10) }
// Java Variable Declaration Example: Without Initialization

1. public class DeclareVariable {


2. int student_id;
3. String student_name;
4. double numbers;
5. Boolean shows;
6. }

// Java Variable Declaration Example: Parameterize Method


Create variable in default and parameterize method. Here, you can declare a variable as an
argument in the method. Assign value in the method and display it as an output.

1. public class CreatediffVariable {


2. public void methodData(int student_id, String student_name){
3. System.out.println("Age:" +student_id);
4. System.out.println("Name:" +student_name);
5. }
6. public static void main(String[] args)
7. {
8. CreatediffVariable hw = new CreatediffVariable();
9. hw.methoData(21, "Java variable");
10. }
11. }

Scope of Variables:

 Every variable used in a programming language holds a scope.


 The scope tells the compiler about the segment within a program where the variable is
accessible or used.
 Programmers can scope the variables lexically or statically in the case of Java variables.
 The static scope variable means the programmers have to determine the scope of a
variable in Java at compile-time rather than at run-time.

Scopes for variables in Java


1. Local Variables: These variables are declared within a code block, such as a method,
constructor, or loop. They are only accessible within that block and its nested blocks. Before
utilizing local variables, it is necessary to initialize them. The memory assigned to these local
variables is released upon exiting the code block. This promotes memory efficiency.
Example:

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. public class Circle {


2. double radius; // instance variable
3. public double calculateArea() {
4. return Math.PI * radius * radius;
5. }
6. }
3. Class Variables (Static Variables): These Variables are declared within a class but possess
a static designation. These variables are shared among all class instances, effectively
transforming into attributes of the entire class instead of individual objects. Upon the class
being loaded, these variables get initialized and endure in memory throughout the program's
runtime."
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 {

// Static method to calculate the square of a number


public static int square(int number) {
return number * number;
}

public static void main(String[] args) {


// Calling the static method without creating an instance of Demo
int result = Demo.square(5);
System.out.println("The square of 5 is: " + result);
}
}
Type Casting in Java

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.

Types of Type Casting

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting

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:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

Example:

1. public class WideningExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. }
11. }

Narrowing Type Casting

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:

1. public class NarrowingExample


2. {
3. public static void main(String args[])
4. {
5. double d = 166.66;
6. //converting double data type into long data type
7. long l = (long)d;
8. //converting long data type into int data type
9. int i = (int)l;
10. }
11. }

Note:

1. Converting a String to an int in Java is not considered casting. Instead, it is called


parsing.
2. In Java, type casting between char and String directly is not possible because they are
fundamentally different types.

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

For char data types, we can specify literals in 4 ways:


Single quote: We can specify literal to a char data type as a single character within the single
quote.
char ch = 'a';
Char literal as Integral literal: we can specify char literal as integral literal, which
represents the Unicode value of the character, and that integral literal can be specified either
in Decimal, Octal, and Hexadecimal forms. But the allowed range is 0 to 65535.
char ch = 062;
Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’.
Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';

4.String literals

Any sequence of characters within double quotes is treated as String literals.


String s = "Hello";

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

You might also like