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

Java Unit I 2022

JAVA NOTES

Uploaded by

pradeep gawas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Unit I 2022

JAVA NOTES

Uploaded by

pradeep gawas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT – I Introduction to Java

History of Java :–

The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital cable television
industry at the time. The history of Java starts with the Green Team. Java team members
(also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team members
started the project in the early '90s. 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
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.

Why Java was named as "Oak"?


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.

Why Java Programming named "Java"?


7) Why had they chose the name Java for Java language? 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.
Features of Java Programming
Following are the notable features of Java:
Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.

Platform Independent
Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform-
independent byte code. This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.

Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP
Java, it would be easy to master.

Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.

Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes
the compiled code executable on many processors, with the presence of Java runtime
system.

Portable
Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. The compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.

Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile time error checking and runtime checking.

Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform
many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.

Interpreted
Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking
is an incremental and light-weight process.
High Performance

With the use of Just-In-Time compilers, Java enables high performance.

Distributed
Java is designed for the distributed environment of the internet.

Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry an extensive amount of run-time
information that can be used to verify and resolve accesses to objects at run-time

Differences Between C++ Vs Java


#1) Platform Independence
C++ Java
C++ is a platform dependent language. Java is platform-independent.
The source code written in C++ needs to Once compiled into byte code, it can be
be compiled on every platform. executed on any platform.

#2) Compiler and Interpreter


C++ Java
C++ is a compiled language. Java is a compiled as well as an interpreted
The source program writtenin C++ is language.The compiled output of a Java source
Compiled into an object code which can code is a byte code which is platform-
then be executed to produce an output. independent.

#3) Portability
C++ Java
C++ code is not portable. Java, however, translates the code into byte
It must be compiled for each platform. code.This byte code is portable and can be
executed on any platform.

#4) Memory Management


C++ Java
Memory management in C++ is manual. In Java the memory management is system-
We need to allocate/deallocate memory controlled.
manually using the new/delete operators.

#5) Multiple Inheritance


C++ Java
C++ supports various types of inheritances Java, supports only single inheritance.
including single and multiple inheritances. Effects of multiple inheritance can be
Although there are problems arising from achieved using the interfaces in Java.
multiple inheritances, C++ uses the virtual
keyword to resolve the problems.

#6) Overloading
C++ Java
In C++, methods and operators can be In Java, only method overloading is
overloaded. This is static polymorphism. allowed.
It does not allow operator overloading.

#7) Virtual Keyword


C++ Java
As a part of dynamic polymorphism, in C++, the In Java, the virtual keyword is absent.
virtual keyword is used with a function to However, in Java, all non-static methods
indicate the function that can be overridden in by default can be overridden.
the derived class. This way we can achieve Or in simple terms, all non-static methods
polymorphism. in Java are virtual by default.

#8) Pointers
C++ Java
C++ is all about pointers.As seen in tutorials Java has limited support for pointers.
earlier, C++ has strong support for pointers and Initially, Java was completely without
we can do a lot of useful programming using pointers but later versions started
pointers. providing limited support for pointers.
We cannot use pointers in Java as leisurely
as we can use in C++.

#9) Documentation Comment


C++ Java
C++ has no support for documentation Java has a built-in support for
comments. documentation comments (/**…*/). This
way Java source files can have their own
documentation.

#10) Thread Support

C++ Java
C++ doesn’t have in-built thread support. It Java is in-built thread support with a class
mostly relies on third-party threading libraries. ―thread‖. We can inherit the thread class
and then override the run method.
Java Virtual Machine :-

Java Virtual Machine (JVM) is a specification that provides runtime


environment in which java byte code can be executed. As the name implies the JVM acts
as a ―virtual‖ machine or processor. Java's platform independence consists mostly of
its Java Virtual Machine (JVM) . JVM makes this possible because it is aware of the specific
instruction lengths and other particularities of the platform. The JVM performs following
operation:

 Loads code
 Verifies code
 Executes code

In most cases, other programming languages, the compiler produce


code for a particular Operating System but the Java compiler produce Bytecode only for
a Java Virtual Machine . When you run a Java program, it runs as a thread within the JVM
process. It is the JVM's responsibility to load your class files, verify code, interpret them
and execute them. When you issue a command like java , the JVM loads the class
definition for that particular class and calls the main method of that class.
It is the JVMs responsibility that makes it possible for the same class
file to run on any other Operating Systems . The JVM takes your compiled platform-
neutral byte code and interprets it to run platform-specific machine code. It can also
compile it into native code with a JIT (a just-in-time compiler that compiles and caches
your code, usually one method at a time). Thus, it is in the JVM where your code results, if
needed, in native Operating System calls. Therefore, in the JVM , your platform-neutral
threading code gets turned into platform-specific threading code.
Java allocates threads as needed for your application. The JVM
manages the memory of your Java program. So, when you create an Object, or an Audio
Clip, or a plain old float, Java allocates memory for both objects and primitives. Java
determines when these items are no longer referenced, and, therefore, can have their
memories reclaimed. The JVM, without any prompting from the user, runs the Garbage
Collector thread (when possible or required) to reclaim used, unreferenced memory. In
addition to interpreting bytecodes, the JVM must supply interfaces to the various
subsystems managed by the Operating System for display, mouse, keyboard, file system
and I/O ports etc.

Java Tokens
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. Further, these two
components contain variables, constants, and operators. In this section, we will
discuss what is tokens in Java.
What is token in Java
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. Remember that the delimiters are not part of the Java tokens.

1. token <= identifier | keyword | separator | operator | literal | comment

For example, consider the following code.

public class Demo


{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}

In the above code snippet, public, class, Demo, {, static, void, main,
(, String, args, [, ], ), System, ., out, println, javatpoint, etc. are the Java tokens.The Java
compiler translates these tokens into Java bytecode. Further, these bytecodes are
executed inside the interpreted Java environment.
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. 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 data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These
are the most basic data types available in Java language.

There are 8 types of primitive data types:

o Boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Primitive data types


Java Non-Primitive Data Types
o Non-primitive data types are called reference types because they refer to objects.

o The main difference between primitive and non-primitive data types are:

o Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and are not defined by Java (except for String).

o Non-primitive types can be used to call methods to perform certain operations,


while primitive types cannot.

o A primitive type has always a value, while non-primitive types can be null.

o A primitive type starts with a lowercase letter, while non-primitive types start with
an uppercase letter.

o The size of a primitive type depends on the data type, while non-primitive types
have all the same size.

o Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc

Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence

Operator Type Category Precedence

postfix expr++ expr--


Unary
prefix ++expr --expr +expr -expr ~ !

multiplicative */%
Arithmetic
additive +-

Shift shift << >> >>>

comparison < > <= >= instanceof


Relational
equality == !=

bitwise AND &

Bitwise bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&


Logical
logical OR ||

Ternary ternary ?:

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

Decision Making Statements in Java


1) If statement
2) If-else statement
3) Else-if statement
4) Switch statement

1) If statement
If statements in Java is used to control the program flow based on
some condition, it's used to execute some statement code block if the expression
evaluated to true; otherwise, it will get skipped. This statement is the simplest way to
modify the control flow of the program.

If (test expression)
{
Statement 1;
Statement 2;
...
}

Example-

public class Sample


{
public static void main(String args[])
{
int a=20, b=30;

if(b>a)
{
System.out.println("b is greater");
}
}

If else statements

If else statements in Java is also used to control the program flow based on
some condition, only the difference is: it's used to execute some statement code block if
the expression is evaluated to true, otherwise executes else statement code block.

Syntax

If (test expression)
{
//execute your code
}
else
{
//execute your code
}

Example

public class Sample


{
public static void main(String args[])
{
int a = 80, b = 30;
if (b > a)
{
System.out.println("b is greater");
}
else
{
System.out.println("a is greater");
}
}}

Else if statements

else if statements in Java is like another if condition, it's used in the program
when if statement having multiple decisions.

Syntax
If (test expression)
{
//execute your code
}
else if (test expression n)
{
//execute your code
}
else
{
//execute your code
}
Example
public class Sample
{
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a)
{
System.out.println("b is greater");
}
else if(a > b)
{
System.out.println("a is greater");
}
else
{
System.out.println("Both are equal");
}
}
}

O/P - Both are equal

Java switch statement

Java switch statement is used when you have multiple possibilities for the if statement.

Syntax

switch (variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;

default:
//execute your code
break;
}
Example

public class Sample


{
public static void main(String args[])
{
int a = 5;
switch (a)
{
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
case 4:
System.out.println("You chose Four");
break;
case 5:
System.out.println("You chose Five");
break;
default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
}

O/P

You chose Five


Java supports following types of loops:

 while loops
 do while loops
 for loops

1) while loop
Java while loops statement allows to repeatedly run the same block of
code until a condition is met.while loop is the most basic loop in Java. It has one control
condition and executes as long the condition is true. The condition of the loop is tested
before the body of the loop is executed; hence it is called an entry-controlled loop.

Syntax

While (condition)
{
statement(s);
Incrementation;
}

Example :-

public class Sample


{
public static void main(String args[])
{
int n = 1, times = 5;

/* while loops execution */


while (n <= times)
{
System.out.println("Java while loops:" + n);
n++;
}
}
}
2) Do-while loop
Java do-while loops are very similar to the while loops, but it always
executes the code block at least once and furthermore as long as the condition remains
true. This loop is an exit-controlled loop.
Syntax—
--------
do
{
statement(s);
}
while( condition );

Example -
public class Sample
{

public static void main(String args[])


{
int n = 1, times = 0;

/* do-while loops execution */


do
{
System.out.println("Java do while loops:" + n);
n++;
}
while (n <= times);
}
}
3)For loop
Java for loops is very similar to Java while loops in that it continues to
process a block of code until a statement becomes false, and everything is defined in a
single line.

Syntax

for ( init; condition; increment )


{
statement(s);
}

Example –

public class Sample


{
public static void main(String args[])
{
/* local variable Initialization */
int n = 1, times = 5;
/* for loops execution */
for (n = 1; n <= times; n = n + 1)
{
System.out.println("Java for loops:" + n);
}
}
}
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. In this
section, we will discuss type casting and its types with proper examples.

Type casting

Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are two types of type casting:

o Widening / Implicit /Automatic Type Casting


o Narrowing / Explicit / Manual 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.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.
WideningTypeCastingExample.java

public class Widening


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}

Output

Before conversion, the value is: 7

After conversion, the long value is: 7

After conversion, the float value is: 7.0

In the above example, we have taken a variable x and converted it into a long type. After
that, the long type is converted into the float type.

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.

double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.

In the following example, we have performed the narrowing type casting two times. First,
we have converted the double type into long data type after that long data type is
converted into int type.
NarrowingTypeCastingExample.java

public class Narrowing


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}

Output

Before conversion: 166.66

After conversion into long type: 166

After conversion into int type: 166


What is Command Line Argument in Java?

Command Line Argument in Java is the information that is passed to the program when
it is executed. The information passed is stored in the string array passed to the main() method

and it is stored as a string. It is the information that directly follows the program’s name on the

command line when it is running.

Command Line Arguments in Java: Important Points

Command Line Arguments can be used to specify configuration information while launching your
application.

There is no restriction on the number of java command line arguments. You can specify any

number of arguments

Information is passed as Strings.


They are captured into the String args of your main method

Simple example of command-line argument in java

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

{
System.out.println("Your first argument is: "+args[0]);
}
}

-----------------------------------------------------------------------------------------------------
compile by > javac CommandLineExample.java

run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.class A{
public static void main(String args[])

{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc

Simple Program of Java


In this page, we will learn how to write the simple program of java. We
can write a simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains main
method. Let's understand the requirement first.

Requirement for Hello Java Example

For executing any java program, you need to

 install the JDK if you don't have installed it, download the JDK and install it.

 set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-


path-in-java

 create the java program

 compile and run the java program


Creating hello java example

Let's create the hello java program:

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

save this file as Simple.java

To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

HOW TO COMPILE A J AVA FILE USING JAVAC COMMAND

To compile a program, execute the Java compiler by


specifying the name of the file. For this, you have to type this command at the
command prompt.
javac compiler creates a class file. This file holds the bytecode
of the program which contains the instructions to be executed by the Java
interpreter.

You might also like