0% found this document useful (0 votes)
85 views

Introduction To Java Programming

The document provides an introduction to the Java programming language. It discusses that Java was developed by Sun Microsystems in 1991 and later acquired by Oracle. It describes Java as a simple, object-oriented, cross-platform language. It also lists some popular Java editors like Notepad, Netbeans, and Eclipse that can be used to write Java programs. Additionally, it discusses the differences between the PATH and CLASSPATH environment variables and their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Introduction To Java Programming

The document provides an introduction to the Java programming language. It discusses that Java was developed by Sun Microsystems in 1991 and later acquired by Oracle. It describes Java as a simple, object-oriented, cross-platform language. It also lists some popular Java editors like Notepad, Netbeans, and Eclipse that can be used to write Java programs. Additionally, it discusses the differences between the PATH and CLASSPATH environment variables and their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to Java programming

AVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle


Corporation. It was developed by James Gosling and Patrick Naughton. It is a
simple programming language.  Writing, compiling and debugging a program is
easy in java.  It helps to create reusable code.

Java is an object-oriented, cross platform, multi-purpose programming language


produced by Sun Microsystems. First released in 1995, it was developed to be a
machine independent web technology. It was based on C and C++ syntax to make it
easy for programmers from those communities to learn.

Java has many characteristics that have contributed to its popularity:

 Platform independence - Many languages are compatible with only one platform. Java was
specifically designed so that it would run on any computer, regardless if it was running Windows,
Linux, Mac, Unix or any of the other operating systems.
 Simple and easy to use - Java's creators tried to design it so code could be written
efficiently and easily.
 Multi-functional - Java can produce many applications from command-line programs to
applets to Swing windows (basically, sophisticated graphical user interfaces).
Java does have some drawbacks. Since it has automated garbage collection, it can tend to use
more memory than other similar languages. There are often implementation differences on different
platforms, which have led to Java being described as a "write once, test everywhere" system

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more
sophisticated IDEs available in the market. But for now, you can consider one of the
following −
 Notepad − On Windows machine, you can use any simple text editor like
Notepad , TextPad.
 Netbeans − A Java IDE that is open-source and free
 Eclipse − A Java IDE developed by the eclipse open-source community

Major Differences between Path and Classpath is: 

1).Path is an environment variable which is used by the operating system to find the
executables.

Classpath is an environment variable which is used by the Java compiler to find the
path, of classes.ie in J2EE we give the path of jar files.
2).PATH is nothing but setting up an environment for operating system. Operating
System will look in this PATH for executables.

Classpath is nothing but setting up the environment for Java. Java will use to find
compiled classes

3).Path refers to the system while classpath refers to the Developing Envornment.

In path we set the path of executables while in


classpath we set path of jars for compiling classes.

SET PATH=C:\Program Files\Java\jdk_version\bin

PATH

Once you installed Java on your machine, it is required to Set the PATH environment
variable to conveniently run the executable (javac.exe, java.exe, javadoc.exe, and so
on) from any directory without having to type the full path of the command, such as:
C:\javac TestClass.java

Otherwise, you need to specify the full path every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac TestClass.java

CLASSPATH
Classpath is system environment variable used by the Java compiler and JVM.
Java compiler and JVM is used Classpath to determine the location of required class
files.
C:\Program Files\Java\jdk1.6.0\bin

Main Features of JAVA


Java is a platform independent language
Compiler(javac) converts source code (.java file) to the byte code(.class file). As
mentioned above, JVM executes the bytecode produced by compiler. This byte
code can run on any platform such as Windows, Linux, Mac OS etc. Which
means a program that is compiled on windows can run on Linux and vice-versa.
Each operating system has different JVM, however the output they produce after
execution of bytecode is same across all operating systems. That is why we call
java as platform independent language.

Java is an Object Oriented language


Object oriented programming is a way of organizing programs as collection of
objects, each of which represents an instance of a class.

4 main concepts of Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Simple
Java is considered as one of simple language because it does not have complex
features like Operator overloading, Multiple inheritance, pointers and Explicit
memory allocation.

Robust Language
Robust means reliable. Java programming language is developed in a way that
puts a lot of emphasis on early checking for possible errors, that’s why java
compiler is able to detect errors that are not easy to detect in other programming
languages. The main features of java that makes it robust are garbage collection,
Exception Handling and memory allocation.

Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in
Java.
Java is distributed
Using java programming language we can create distributed applications.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for
creating distributed applications in java. In simple words: The java programs can
be distributed on more than one systems that are connected to each other using
internet connection. Objects on one JVM (java virtual machine) can execute
procedures on a remote JVM.

Multithreading
Java supports multithreading. Multithreading is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization
of CPU.

Portable
As discussed above, java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any platform for
execution that makes java code portable.

Differences between C++ and Java


Metrics C++ Java

Programming Object-Oriented Pure Object


Paradigm Programming (OOP) Oriented Oriented
Based on C and C+
Origin Based on C language
+
Bjarne Stroustrup in James Gosling in
Developer
1979 1991
Interpreted
Translator Compiler only language (Compiler
+ interpreter)
Platform Platform
Platform Dependent
Dependency Independent
Executed by JVM
Code execution Direct (Java Virtual
Machine)
File generation .exe files .class files
Datatypes (union,
Supported Not supported
structure)
Supported except
Inheritance Supported
Multiple inheritance
Support Function Operator
Overloading overloading overloading is not
(Polymorphism) supported
Pointers Supported Not supported
Allocation Use new, delete Garbage collector
Exception Handling Supported Supported
Destructors Supported Not supported
Multithreading/
Not supported Supported
Interfaces
Database
Not supported Supported
connectivity
Supported ( auto,
Storage Classes Not supported
extern )

What is Java Bytecode?


Java bytecode is the instruction set for the Java Virtual Machine. As soon as a java program
is compiled, java bytecode is generated. In more apt terms, java bytecode is the machine
code in the form of a .class file. With the help of java bytecode we achieve platform
independence in java.

How does it works?

When we write a program in Java, firstly, the compiler compiles that program and a
bytecode is generated for that piece of code. When we wish to run this .class file on
any other platform, we can do so. After the first compilation, the byte code
generated is now run by the Java Virtual Machine and not the processor in
consideration. This essentially means that we only need to have basic java
installation on any platforms that we want to run our code on. Resources required
to run the bytecode are made available by theJava Virtual Machine, which calls the
processor to allocate the required resources. JVM's are stack-based so they stack
implementation to read the codes.
Advantage of Java Bytecode

Platform independence is one of the soul reasons for which James Gosling started
the formation of java and it is this implementation of bytecode which helps us to
achieve this. Hence bytecode is a very important component of any java
program.The set of instructions for the JVM may differ from system to system but
all can interpret the bytecode. A point to keep in mind is that bytecodes are non-
runnable codes and rely on the availability of an interpreter to execute and thus the
JVM comes into play.
JVM Architecture

how JVM works:


Class Loader: The class loader reads the .class file and save the byte code in the method area.

Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class
level information of each .class file.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each .class file.

Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.

PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed.
Since instructions are executed by threads, each thread has a separate PC register.

Native Method stack: A native method can access the runtime data areas of the virtual machine.

Native Method interface: It enables java code to call or be called by native applications. Native applications are
programs that are specific to the hardware and OS of a system.

Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed
by garbage collection for memory management.
JVM Vs JRE Vs JDK
JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine(JVM), class libraries, and other files excluding
development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the
code in JRE.

JVM: As we discussed above, JVM runs the program by using class, libraries
and files provided by JRE.

JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler,
debugger etc.
JDK vs JRE vs JVM

Let’s look at some of the important difference between JDK, JRE, and JVM.

1. JDK is for development purpose whereas JRE is for running the java
programs.
2. JDK and JRE both contains JVM so that we can run our java program.
3. JVM is the heart of java programming language and provides platform
independence.

Java applications list:

 Desktop GUI Applications


 Mobile Applications
 Enterprise Applications
 Scientific Applications
 Web-based Applications
 Embedded Systems
 Big Data Technologies
 Distributed Applications
 Cloud-based Applications
 Web servers and Application servers
 Software Tools
 Gaming Applications

Disadvantages

1- Performance
Java programs take much longer time to run compared to C/C++.
2- Memory
Since Java Programs run on top of Java Virtual Machine, it consumes more
memory.
3- Cost
Since memory and processing requirements higher, hardware cost increases.
4. Low level programming
There is no support for low level programming in Java, like pointers are missing.
5- Garbage collection
There is no control over garbage collection in Java. That is programmer does not
have any right to control the garbage collection. Java does not provide functions like
delete(), free().

Java Variables and Data Types


What is a Variable?
A variable can be thought of as a container which holds value for you, during the life of a Java program. Every
variable is assigned a data type which designates the type and quantity of value it can hold.

In order to use a variable in a program you to need to perform 2 steps

1. Variable Declaration
2. Variable Initialization

Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are

int a,b,c;

float pi;

double d;

char a;

Variable Initialization:
To initialize a variable, you must assign it a valid value.
Types of variables
In Java, there are three types of variables:

1. Local Variables
2. Instance Variables
3. Static Variables

1) Local Variables

Local Variables are a variable that are declared inside the body of a method.

2) Instance Variables

Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They
are Object specific and are known as instance variables.

3) Static Variables

Static variables are initialized only once, at the start of the program execution. These variables should be initialized
first, before the initialization of any instance variables.

Example: Types of Variables in Java


class jnucs5sem {
static int a = 1; //static variable
int data = 99; //instance variable
void method() {
int b = 90; //local variable
}
}

Data Types in Java (Data type defines the values that a variable can take)
Data types classify the different values to be stored in the variable. In java, there are two types of data types:

1. Primitive Data Types


2. Non-primitive Data Types
Primitive Data Types

Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with
other primitive values.

There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data types
Java Data Types

Data Type Default Value Default size

Byte 0 1 byte

Short 0 2 bytes

Int 0 4 bytes

Long 0L 8 bytes

Float 0.0f 4 bytes

Double 0.0d 8 bytes

Boolean False 1 bit

Char '\u0000' 2 bytes

har data type in Java is 2 bytes because it uses UNICODE character set. UNICODE is a character set which covers
all known scripts and language in the world

class JavaExample {
public static void main(String[] args) {

byte num;

num = 113;
System.out.println(num);
}
}
Output:

113

short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767.
Default size of this data type: 2 byte

short num = 45678;

Try the same program by assigning value assigning 150 value to variable num, you would get type mismatch error because
the value 150 is out of the range of byte data type. The range of byte as I mentioned above is -128 to 127.

class JavaExample {
public static void main(String[] args) {

short num;

num = 150;
System.out.println(num);
}
}
Output:

150

long:
Used when int is not large enough to hold the value, it has wider range than int data type, ranging from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

class JavaExample {
public static void main(String[] args) {

long num = -12332252626L;


System.out.println(num);
}
}
Output:

-12332252626

char: holds characters.


size: 2 bytes

class JavaExample {
public static void main(String[] args) {

char ch = 'Z';
System.out.println(ch);
}
}
Output:

Z
boolean: holds either true of false.

class JavaExample {
public static void main(String[] args) {

boolean b = false;
System.out.println(b);
}
}
Output:

false

float: Sufficient for holding 6 to 7 decimal digits


size: 4 bytes

class JavaExample {
public static void main(String[] args) {

float num = 19.98f;


System.out.println(num);
}
}
Output:

19.98

Strings: String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.

Arrays: Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store one or more values of a
specific data type and provide indexed access to store the same. A specific element in an array is accessed by its index.

Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and variables are called Identifier. Identifier must
follow some rules. Here are the rules:

 All identifiers must start with either a letter( a to z or A to Z ) or currency character($) or an underscore.
 After the first character, an identifier can have any combination of characters.
 Java keywords cannot be used as an identifier.
 Identifiers in Java are case sensitive, foo and Foo are two different identifiers.

Some valid identifiers are: int a, class Car, float amount etc. ////////////int char; invalid identifier

Or

int score;
Here,  score  is a variable (an identifier). You cannot use keywords as variable names. It's because keywords have
predefined meanings. For example,

int float;

The above code is wrong. It's because  float  is a keyword and cannot be used as a variable name.

Here are some valid identifiers:

 score

 level

 highestScore

 number1

 convertToString

Here are some invalid identifiers:

 class

 float

 1number

 Highest Score

 @pple

Other Rules
Whitespaces are not allowed------Similarly, you cannot use symbols such as  @ ,  # , and
so on------It can have a sequence of letters and digits. However, it must begin
with a letter,  $  or  _ . The first letter of an identifier cannot be a digit.
Constants in java
A constant is a variable whose value cannot change once it has been assigned. Java doesn't
have built-in support for constants.
A constant can make our program more easily read and understood by others. In addition, a
constant is cached by the JVM as well as our application, so using a constant can improve
performance.
A constant variable is the one whose value is fixed and only one copy of it exists in the program.
Once you declare a constant variable and assign value to it, you cannot change its value again
throughout the program.
You can create a constant in c language using the constant keyword (one way to create it) as
const int a=100;

const float b=100.10;

Unlike in C language constants are not supported in Java(directly). But, you can still create a constant by
declaring a variable static and final.
Static − Once you declare a variable static they will be loaded in to the memory at the compile time i.e.
only one copy of them is available and The static modifier causes the variable to be available without an
instance of it’s defining class being loaded.
The static modifier is mainly used for memory management

It also allows the variable to be available without loading any instance of the class in which it is defined.
Final − once you declare a variable final you cannot modify its value again. The final modifier means that
the value of a variable cannot change. Once the value is assigned to a variable, a different value cannot
be reassigned to the same variable.
Therefore, you can create a constant in Java by declaring the instance variable static and final.
To make any variable a constant, we must use ‘static’ and ‘final’ modifiers.

Why constants?
Constants make your program more easy to read and understand when read by others.
Using a constant also improves performance, as constants are cached by both the JVM and your
application.
Operator and Expression
An operator is a character that represents an action, for example + is an arithmetic operator that
represents addition,

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups −

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then –
Few examples:

Operator Description Example

Adds values on either side of the A+B


+ (Addition) operator. will give
30
Subtracts right-hand operand from left- A - B will
- (Subtraction)
hand operand. give -10

* Multiplies values on either side of the A * B will


(Multiplication) operator. give 200

Divides left-hand operand by right- B / A will


/ (Division)
hand operand. give 2

Divides left-hand operand by right- B%A


% (Modulus) hand operand and returns remainder. will give
0

Increases the value of operand by 1. B++


++ (Increment)
gives 21

Decreases the value of operand by 1. B-- gives


-- (Decrement)
19

The Relational Operators


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −
Few examples: =, ==

Operator Description Example

Checks if the values of two


== (equal operands are equal or not, if (A == B) is
to) yes then condition becomes not true.
true.

Checks if the values of two


!= (not equal operands are equal or not, if (A != B) is
to) values are not equal then true.
condition becomes true.

Checks if the value of left


> (greater operand is greater than the (A > B) is
than) value of right operand, if yes not true.
then condition becomes true.

Checks if the value of left


operand is less than the value (A < B) is
< (less than)
of right operand, if yes then true.
condition becomes true.

>= (greater Checks if the value of left (A >= B) is


than or operand is greater than or not true.
equal to the value of right
equal to) operand, if yes then condition
becomes true.

Checks if the value of left


<= (less operand is less than or equal
(A <= B) is
than or to the value of right operand, if
true.
equal to) yes then condition becomes
true.

The Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then

Operator Description Example

Binary AND Operator


& (bitwise copies a bit to the (A & B) will give 12
and) result if it exists in both which is 0000 1100
operands.

Binary OR Operator
(A | B) will give 61
| (bitwise or) copies a bit if it exists in
which is 0011 1101
either operand.

Binary XOR Operator


^ (bitwise copies the bit if it is set (A ^ B) will give 49
XOR) in one operand but not which is 0011 0001
both.

(~A ) will give -61


Binary Ones
which is 1100 0011
~ (bitwise Complement Operator
in 2's complement
compliment) is unary and has the
form due to a signed
effect of 'flipping' bits.
binary number.
Binary Left Shift
Operator. The left
operands value is
A << 2 will give 240
<< (left shift) moved left by the
which is 1111 0000
number of bits
specified by the right
operand.

Binary Right Shift


Operator. The left
operands value is
>> (right A >> 2 will give 15
moved right by the
shift) which is 1111
number of bits
specified by the right
operand.

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Few examples;

Operator Description Example

Called Logical AND


operator. If both the
&& (logical
operands are non-zero, (A && B) is false
and)
then the condition
becomes true.

Called Logical OR
Operator. If any of the
|| (logical or) two operands are non- (A || B) is true
zero, then the condition
becomes true.

Called Logical NOT


Operator. Use to
reverses the logical state
! (logical not) of its operand. If a !(A && B) is true
condition is true then
Logical NOT operator will
make false.

The Assignment Operators


Following are the assignment operators supported by Java language −
Operato Description Example
r

Simple assignment operator. Assigns values C = A + B


from right side operands to left side will assign
=
operand. value of A
+ B into C

Add AND assignment operator. It adds right C += A is


operand to the left operand and assign the equivalent
+=
result to left operand. to C = C +
A

Subtract AND assignment operator. It C -= A is


subtracts right operand from the left operand equivalent
-=
and assign the result to left operand. to C = C –
A

Multiply AND assignment operator. It C *= A is


multiplies right operand with the left operand equivalent
*=
and assign the result to left operand. to C = C *
A

/= Divide AND assignment operator. It divides C /= A is


left operand with the right operand and equivalent
assign the result to left operand. to C = C /
A

Modulus AND assignment operator. It takes C %= A is


modulus using two operands and assign the equivalent
%=
result to left operand. to C = C
%A

C <<= 2
is same
<<= Left shift AND assignment operator.
as C = C
<< 2

C >>= 2
is same
>>= Right shift AND assignment operator.
as C = C
>> 2

C &= 2 is
&= Bitwise AND assignment operator. same as
C=C&2

bitwise exclusive OR and assignment C ^= 2 is


^= operator. same as
C=C^2

bitwise inclusive OR and assignment C |= 2 is


|= operator. same as
C=C|2
Miscellaneous Operators
There are few other operators supported by Java Language.

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should
be assigned to the variable. The operator is written as −
Variable x = (expression) ? value if true : value if false

public class Test {

public static void main(String args[]) {


int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This will produce the following result −


Output
Value of b is : 30
Value of b is : 20

Precedence of Java Operators


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator −
For example, x = (10 + (3 * 4)); here x is assigned 22, not 52 because operator * has higher precedence
than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator
Postfix expression++ expression--

Unary ++expression –-expression +expression –expression ~ !

Multiplicative */%

Additive +-

Shift << >> >>>

Relational < > <= >= instanceof

Equality == !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Conditional ?:

Assignment = += -= *= /= %= ^= |= <<= >>= >>>=


Java Expressions
A Java expression consists of variables, operators, literals, and method calls. To know
more about method calls, Java methods call. For example,

int score ; score= 10;

Here score=10 is expression

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three
types of expressions in Java:

 Those that produce a value, i.e., the result of

(1 + 1)

 Those that assign a variable, for example

(v = 10)

Java Statements
In Java, each statement is a complete unit of execution. For example,
int score =10*2;

Here, we have a statement. The complete execution of this statement involves


multiplying integers and then assigning the result to the variable.

In the above statement, we have an expression 10 * 2. In Java, expressions are part of


statements.

Means that you can construct statements using expression but not vice a versa.
Type Casting (Type conversion )
The process of converting the value of one data type( int, float, double etc. ) in to another data type
is known as typecasting. It has two types as follow

1. Widening Type Casting

2. Narrowing Type Casting

Widening Type Casting


In Widening Type Casting, Java automatically converts one data type to another data type. In the
case of Widening Type Casting, the lower data type (having smaller size value) is converted into
the higher data type (having larger sizevalue ). Hence there is no loss in data. This is why this type
of conversion happens automatically.
This is also known as Implicit Type Casting.

Example:

class tc {
public static void main(String[] args) {
int num = 10;
System.out.println("The integer data type value is: " + num);

// convert into double type


double data = num;
System.out.println("The double data type value, after automatic
conversion is: " + data);
}
}

Output

The integer data type value is: 10

The double data type value, after automatic conversion is: 10.0
In the above example, we are assigning the  int  type variable named  num  to a  double  type variable
named  data .
Here, the Java first converts the  int  type data into the  double  type. And then assign it to
the  double  variable.

Narrowing Type Casting


In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.
In the case of Narrowing Type Casting, the higher data types (having larger size) are converted
into lower data types (having smaller size). Hence there is the loss of data. This is why this type of
conversion does not happen automatically.
This is also known as Explicit Type Casting.

Example:

class tc2 {
public static void main(String[] args) {
double num = 10.99;
System.out.println("The double value: " + num);

// convert into int type


int data = (int)num;
System.out.println("Data will be lost and The integer value, after
conversion is: " + data);
}
}

Output

The double value is: 10.99

Data will be lost and the integer value, after conversion is: 10

In the above example, we are assigning the  double  type variable named  num  to an  int  type variable
named  data .
Notice the line

int data= (int)num;

Here, the  int  keyword inside the parenthesis indicates that that the  num  variable is converted into
the  int  type.

Control Flow
Packages
A package in Java is used to group related classes. Think of it as a folder in a file
directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

The library is divided into packages and classes. Meaning you can either


import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use
the import keyword:

Syntax

import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation. In our example, we will use the nextLine() method, which is used
to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}

Import a Package
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date and time
facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:

Example
import java.util.*;

java.lang -
It Provides classes that are fundamental to the design of the Java programming
language such as String, Math, and basic runtime support for processes.

java.util -
It Provides the collections framework, formatted printing and scanning, array
manipulation utilities, event model, date and time facilities, internationalization, and
miscellaneous utility classes.

Java.lang is the default Package for the Java Program All the Classes available in
java.lang package will be available without importing the package. Whereas java.util is
not the default Package in order the use the java.util package i.e (Collection Framework)
you must have to import it to the current Program i.e import java.util.*

Important Classes of Java.lang package:

1.java.lang.Object

2.java.lang.String

5.java.lang.Byte

6.java.lang.Short
7.java.lang.Integer

8.java.lang.Long

9.java.lang.Boolean

10.java.lang.Double

11.java.lang.Character

12.java.lang.Runtime

13.java.lang.System

15.java.lang.Math

16.java.lang.Exception

Classes and interface available in java.util package

1.java.util.Collection (interface)

2.java.util.List(Interface)

3.java.util.Set(interface)

4.java.util.ArrayList

5.java.util.Vector

6.java.util.LinkedList

Java.util.*;

Java Math class


Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(),
cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of
Math class can't define to return the bit-for-bit same results. This relaxation permits implementation
with better-performance where strict reproducibility is not required.

For other arithmetic operations like increment, decrement, divide, absolute value, and negation
overflow occur only with a specific minimum or maximum value. It should be checked against the
maximum and minimum value as appropriate.
Example
public class JavaMathExample1    
{    
    public static void main(String[] args)     
    {    
        double x = 28;    
        double y = 4;    
          
        // return the maximum of two numbers  
        System.out.println("Maximum number of x and y is: " +Math.max(x, y));   
          
        // return the square root of y   
        System.out.println("Square root of y is: " + Math.sqrt(y));   
          
        //returns 28 power of 4 i.e. 28*28*28*28    
        System.out.println("Power of x and y is: " + Math.pow(x, y));      
  
        // return the logarithm of given value       
        System.out.println("Logarithm of x is: " + Math.log(x));   
        System.out.println("Logarithm of y is: " + Math.log(y));  
          
        // return the logarithm of given value when base is 10      
        System.out.println("log10 of x is: " + Math.log10(x));   
        System.out.println("log10 of y is: " + Math.log10(y));    
          
        // return the log of x + 1  
        System.out.println("log1p of x is: " +Math.log1p(x));    
  
        // return a power of 2    
        System.out.println("exp of a is: " +Math.exp(x));    
          
        // return (a power of 2)-1  
        System.out.println("expm1 of a is: " +Math.expm1(x));  
    }    
}    

Output:

Maximum number of x and y is: 28.0


Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12

Java Math Methods


The java.lang.Math class contains various methods for performing basic numeric operations such as the logarithm, cube root, and trigonometric
functions etc. The various java math methods are as follows:
Basic Math methods
Method Description

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.sqrt() It is used to return the square root of a number.

Math.pow() It returns the value of first argument raised to the power to second argument.

Math.random() It returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Package java.text

Provides classes for handling text, dates, numbers, and messages in a manner independent of
natural languages.

Every locale has four default formats for formatting and parsing dates. They are called SHORT, MEDIUM, LONG,
and FULL. The SHORT format consists entirely of numbers while the FULL format contains most of the date
components. There is also a default format called DEFAULT and is the same as MEDIUM.
If the example is run in a different locale, the output will not be the same:

import static java.lang.System.out;

import java.text.DateFormat;

import java.util.*;

public class tpkg {

public static void main(String[] args) {

// Format
Date date = new Date();

String s = DateFormat.getDateInstance(DateFormat.SHORT).format(date);

out.println("DateFormat.SHORT : " + s);

s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);

out.println("DateFormat.MEDIUM : " + s);

s = DateFormat.getDateInstance(DateFormat.LONG).format(date);

out.println("DateFormat.LONG : " + s);

s = DateFormat.getDateInstance(DateFormat.FULL).format(date);

out.println("DateFormat.FULL : " + s);

s = DateFormat.getDateInstance().format(date);

out.println("default : " + s);

s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);

out.println("DateFormat.DEFAULT : " + s);

}
Java I/O(i.o package)
The package java.io contains the classes that handle fundamental input and output
operations in Java. The I/O classes can be grouped as follows:

 Classes for reading input from a stream of data.


 Classes for writing output to a stream of data.
 Classes that manipulate files on the local file system.

I/O in Java is based on streams. A stream represents a flow of data or a channel of


communication. The Input Stream class is the super class of all byte input streams,
while Output Stream is the super class of all the byte output streams.
Javac test.java

Java test

dir abc.txt

File f= new File(“jnucs”);

jnucs

Java file I/O concepts is implemented based on unix os.


Physical files or dirs are available or not

To create a new file

To create a directory

A pointer is pointing to file if yes, then return true otherwise false

A pointer is pointing to directory if yes, then return true otherwise false

Name of all files and dirs present in specified directory

No. of characters present in file

To delete specify file or directory

Program—to display all files and dir present in particular dir/folder


import java.io.*;

class testdd

public static void main(String[] args)throws Exception

int count=0;
File f= new File("F:\\COVID Notes\\PIJ");

String[] s = f.list();

for(String s1 : s)

count++;

System.out.println(s1);

System.out.println(“The Total Number :" +count);

To display only file names


import java.io.*;

class testdd

public static void main(String[] args)throws Exception

int count=0;

File f= new File("F:\\COVID Notes\\PIJ");

String[] s = f.list();

for(String s1 : s)

{ File f1 =new File(f,s1);


if(s1.isFile())

count++;

System.out.println(s1);

System.out.println(“The Total Number :" +count);

To display only Directory


import java.io.*;

class testdd

public static void main(String[] args)throws Exception

int count=0;

File f= new File("F:\\COVID Notes\\PIJ");

String[] s = f.list();

for(String s1 : s)

{ File f1 =new File(f,s1);

if(s1.isDirectory())
{

count++;

System.out.println(s1);

System.out.println(“The Total Number :" +count);

BufferReader is a class that helps to read text from a character-based


input stream. It reads characters using another Reader (faster)

Some methods in the BufferReader class are as follows.

int read() – This method reads a single character.


String readLine() – This reads a line of text.
void close() – This method closes the input stream and releases the
associated system resources.

FileReader is a class that helps to read data from a file.(Slower)

FileReader class has the following two methods.

int read () – This method returns a character in ASCII form. It returns -1


at the end of the file.
void close () – This helps to close the FileReader object.

You might also like