0% found this document useful (0 votes)
36 views18 pages

Intro of Java CHAPTER 1 PDF

The document provides an introduction to the Java programming language, describing its history, features, types of applications, environment, and role in internet development. Key points covered include Java being an object-oriented language that is simple, platform independent, secure, robust and suitable for a variety of applications including web, standalone, enterprise and mobile.

Uploaded by

Sufiyan Ali
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)
36 views18 pages

Intro of Java CHAPTER 1 PDF

The document provides an introduction to the Java programming language, describing its history, features, types of applications, environment, and role in internet development. Key points covered include Java being an object-oriented language that is simple, platform independent, secure, robust and suitable for a variety of applications including web, standalone, enterprise and mobile.

Uploaded by

Sufiyan Ali
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/ 18

CHAPTER 1

INTRODUCTION TO JAVA
Java is an object-oriented programming language with its runtime environment. It is a
combination of features of C and C++ with some essential additional concepts. Java is well suited
for both standalone and web application development and is designed to provide solutions to
most of the problems faced by users of the internet era.
❖ What is java?
• Java is an object-oriented programming language developed by Sun Microsystems, and it
was released in 1991.
• James Gosling initially developed Java in Sun Microsystems (which was later merged
with Oracle Corporation).
• Java is a set of features of C and C++. It has obtained its format from C, and OOP features from
C++.
• Java programs are platform independent which means they can be run on any operating
system with any processor as long as the Java interpreter is available on that system.
• Java code that runs on one platform does not need to be recompiled to run on another
platform; it's called write once, run anywhere(WORA).
• Java Virtual Machine (JVM) executes Java code, but it has been written in platform-specific
languages such as C/C++/ASM, etc. JVM is not written in Java and hence cannot be platform
independent, and Java interpreter is a part of JVM.

❖ Types of Java Applications


Web Application - Java is used to create server-side web applications. Currently, Servlet, JSP,
Struts, JSF, etc. technologies are used.
Standalone Application - It is also known as the desktop application or window-based
application. An application that we need to install on every machine or server such as media
player, antivirus, etc. AWT and Swing are used in java for creating standalone applications.
Enterprise Application - An application that is distributed in nature, such as banking
applications, etc. It has the advantage of the high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
Mobile Application - Java is used to create application software for mobile devices. Currently,
Java ME is used for building applications for small devices, and also Java is a programming
language for Google Android application development.

❖ Features of JAVA:
Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to
Sun, 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 confusing and rarely-used features e.g. explicit pointers, operator
overloading etc.
o There is no need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
Object-oriented
Java is 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 incorporates
both data and behaviour.
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 software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. 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 virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is
used to dynamically load Java classes into the Java Virtual Machine. 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 right
to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL, JAAS, Cryptography etc.
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There are lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get
rid of objects which are not being used by a Java application anymore.
o There is exception handling and type checking mechanism in java. All these points makes
java robust.
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. 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. But in java, it occupies 4 bytes of memory for both 32 and 64
bit architectures.
Portable
Java is portable because it facilitates you to carry the java byte code to any platform. It doesn't
require any type of implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g. C++). Java is
an interpreted language that is why it is slower than compiled languages e.g. C, C++ etc.
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 dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages i.e. C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

❖ Java Virtual Machine: (JVM)


All language compilers translate source code into machine code for a specific computer Java
compiler also does the same thing. Then, how does Java achieve architecture neutrality? The
answer is that the Java compiler, produces an intermediate code known as byte code for a
machine that does not exit. This machine is called the Java Virtual Machine and it exists only
inside the computer memory. It is a simulated computer within the computer and does all major
functions of a real computer. Following Figure illustrates the process of compiling a Java
program into byte code which is also referred to as virtual machine code.

Java program Java compiler Virtual machine

Source Code Byte Code


Process of Compilation
The virtual machine code is not machine specific. The Java interpreter generates the machine
specific code (known as machine code) by acting as an intermediate between the virtual machine
and the real machine as shown in following fig.
Remember that the interpreter is different for different machines.

Byte code Java interpreter Machine code

Virtual Machine Real Machine


Process of converting byte code into machine code

❖ Java And Internet:


Java is strongly associated with the Internet because of the fact that the first application program
written in Java was Hotjava, a Web browser to run applets on Internet.
Internet users can use Java to create applet programs and run them locally using a "Java-enabled
browser" such as HotJava. They can also use a Java-enabled browser to download an applet
located on a computer anywhere in the Internet and run it on his local computer. In fact, Java
applets have made the Internet a true extension of the storage system of the local computer.
Internet users can also set up their Web sites containing Java applets that could be used by other
remote users of Internet.
The ability of Java applets to hitch a ride on the Information Superhighway has made Java a
unique programming language for the Internet. In fact, due to this, Java is popularly known as
Internet language.
❖ Java Environment: (JDK)
Java environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development Kit (JDK)
and the classes and methods are part of the Java Standard Library, also known as the Application
Programming Interface (API).
Java Development Kit
The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs. They include
❖ appletviewer (for viewing Java applets)
❖ javac (Java compiler)
❖ java (Java Interpreter)
❖ javah (for C header files)
❖ javadoc (for creating HTML. documents)
❖ jdb ( Java debugger)
The way these tools are applied to build and run application program is illustrated in following
figure. To create a Java program, we need to create a source code file using a text editor. The
source code then compiled using the Java Compiler javac and executed using the Java Interpreter
java. The Java debugger jdb is used to find errors, if any, in the source code.

Text
Editor
Java source Javado HTML
code files

Javac

Java class Javah Header

Java Jdb

Java
progra
m
output
❖ Difference between Java and C++
• Java does not include the C unique statement keywords goto, sizeof, and typedef.
• Java does not contain the data types struct, union and enum.
• Java does not support an explicit pointer type.
• Java does not have a preprocessor and therefore we cannot use # define, #include, and # ifdef
statements.
• Java does not support operator overloading.
• Java does not have template classes as in C+ + .
• Java does not support multiple inheritance of classes. This is accomplished using a new
feature called "interface".
• Java does not support global variables. Every variable and method is declared within a class
and forms part of that class.
• Java does not use pointers.
• Java has replaced the destructor function with a finalize( ) function.
Application Programming Interface
The Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are
Language Support Package: A collection of classes and methods required for implementing
basic feature of Java.
Utilities Package: A collection of classes to provide utility functions such as Date and Time.
Input/output Package: A collection of classes required for input and output manipulation.
Networking Package: A collection of classes for communicating with other computers via
Internet.
AWT Package: The abstract window toolkit package contains classes that implements platform
independent graphical user interface.
Applet Package: This includes a set of classes that allows us to create Java applets.

❖ Data Types
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 Integer, Character, Boolean, and
Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
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
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

❖ Variables
A variable is a container which holds the value while the java program is executed. A variable is
assigned with a datatype.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
int data=50;//Here data is variable

❖ Operators
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:
• Increment / Decrement operators
• Arithmetic Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.
Operator
Category Precedence
Type
Increment/ postfix expr++ expr--
Decrement
prefix ++expr --expr
Arithmetic multiplicative */%
additive +-
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

❖ Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.
Types of Comments
There are 2 types of comments in java.
1. Single Line Comment
2. Multi Line Comment

1 Single Line Comment


The single line comment is used to comment only one line.
Syntax:
//This is single line comment
2) Multi Line Comment
The multi line comment is used to comment multiple lines of code.
Syntax:
/* This
is
multi line
comment */

❖ Simple Java Program:


Let's look more closely at about the simplest Java program you can have-one: simply
Print’s. a message to the console window.
public class FirstSample
{
public static void main(String[] args)
{
System. out .println ("Hello Java World");
}
}
First and foremost, Java is case sensitive. If you made any mistakes in capitalization (such as
typing Main instead of main) the program will not run. Now let's look at this source code line by
line. The keyword public is called an access modifier, these modifiers control what other parts
of a program can use this code. The keyword class is there to remind you that everything in a
Java program lives inside a class.
Following the keyword class is the name of the class. The rules for class names in Java are quite
generous. Names must begin with a letter, and after that, they can have any combination of
letters and digits. The length is essentially unlimited. You cannot use a Java reserved word (such
as public or if ) for a class name.
You need to make the file name for the source code the same as the name of the public class, with
the extension .java appended. Thus, we must store this code in a file called FirstSample.java.
(Again, case is important don't use firstsample.java.) If you don't do this, you'll get a pretty
obvious error message when you try to run this source code through a Java compiler ("Public
class FirstSample must be defined in a file called 'FirstSample .java''').
Compiling the Program:
To compile the program, we must run the java compiler, with the name of the source file on the
command line as shown below
javac FirstSample.java
If everythinq is Ok, the javac compiler creates a file called FirstSample.class containing the byte
code of the program. Note that the compiler automatically names the bytecode file as <class
name> .class
Running the Program:
We need to use the Java interpreter to run the program. At the command prompt, type
java FirstSample
Now, the interpreter looks for the main method in the program and begins execution from there.
When the program executes, it simply displays the string Hello Java World on the console. Here,
we are using the System.out object and calling its println() method.
Notice the periods used to invoke a method. Java uses the general syntax object.method
(parameters) for its equivalent of function calls.
In this case, we are calling the println() method and passing it a string parameter. The method
displays the string parameter on the console. It then terminates the output line so that each call
to println() displays its output on a new line.
Java Input
Using Scanner
There are several ways to get input from the user in Java. You will learn to get input by
using Scanner object in this article.
For that, you need to import Scanner class using:

import java.util.Scanner;

Learn more about Java import


Then, we will create an object of Scanner class which will be used to get input from the user.

Scanner input = new Scanner(System.in);


int number = input.nextInt();
Example 5: Get Integer Input From the User
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("You entered " + number);
}
}
When you run the program, the output will be:

Enter an integer: 23
You entered 23

Here, input object of Scanner class is created. Then, the nextInt() method of the Scanner class is
used to get integer input from the user.
To get long, float, double and String input from the user, you can
use nextLong(), nextFloat(), nextDouble() and next() methods respectively.
Example 6: Get float, double and String Input

import java.util.Scanner;

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

// Getting float input


System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);

// Getting double input


System.out.print("Enter double: ");
float myDouble = input.nextFloat();
System.out.println("Float entered = " + myDouble);

// Getting String input


System.out.print("Enter text: ");
String myString = input.next();
System.out.println("Text entered = " + myString);
}
}
When you run the program, the output will be:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Float entered = -23.4
Enter text: Hey!

Text entered = Hey!


❖ Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used
as an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.
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
❖ Control Flows
If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
❖ Loops
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in java.
for loop
while loop
do-while loop
For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
}
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;
Break Statement with Loop
Example:
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Continue Statement
The continue statement is used in loop control structure when you need to immediately jump to
the next iteration of the loop. It can be used with for loop or while loop.
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
Syntax:
jump-statement;
continue;
Java Continue Statement Example
Example:
public class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
6
7
8
9
10

❖ Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object the contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based; first element of the array is stored at 0 index.

Advantage of Java Array


o Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
o Random access: We can get any data located at any index position.
Disadvantage of Java Array
o Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single Dimensional Array in java
Syntax to Declare an Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Multidimensional array in java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

❖ String:
Strings are sequences of characters, such as "Hello". Java does not have a built-in string type.
Instead, the standard Java library contains a predefined class called, String. Each quoted string
is an instance of the String class:
String e = “” ; // an empty string
String greeting=”Hello”;
Methods Of String class:
java.lang.String
1) char charAt(int index)
returns the character at the specified location,
2) int compareTo(String other)
returns a negative value if the string comes before other in dictionary order, a positive value if
the string comes after other in dictionary order, or 0 if the strings are equal.
3) boolean equals(String other)
returns true if the string is equals.
4) boolean equalsIgnoreCase(String other)
returns true if the string equals other, except for upper/lowercase distinction.
5) int lngth()
returns the length of the string,
6) String replace(char oldChar, char newChar)
Return a new string that is obtained by replacing all characters oldChar in the string with
newChar.
7) String substring(int beginindex)
String substring(int beginlndex, int endlndex)
Return a new string consisting of all characters from begin Index until the end of the string or
until end Index (exclusive).
8) String toLowerCase()
returns a new string containing all characters in the original string, with uppercase characters
converted to lower case.
9) String toUpperCase()
returns a new string containing all characters in the original string, with lowercase characters
converted to upper case.
10) String trim()
returns a new string by eliminating all leading and trailing spaces in the original string.

*****

You might also like