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

Java Notes B.Sc-1-1 PDF

The document provides an overview of the Java programming language. It discusses Java's history, describing how it was initially created at Sun Microsystems in 1991. It then covers the key aspects of Java including its use as a programming language, development environment, application environment, and deployment environment. The document also discusses why Java is used, highlighting features like being object-oriented, platform independent, secure, and robust. It then goes into details on Java basics, syntax, data types, operators, control flow statements, arrays, and naming conventions.

Uploaded by

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

Java Notes B.Sc-1-1 PDF

The document provides an overview of the Java programming language. It discusses Java's history, describing how it was initially created at Sun Microsystems in 1991. It then covers the key aspects of Java including its use as a programming language, development environment, application environment, and deployment environment. The document also discusses why Java is used, highlighting features like being object-oriented, platform independent, secure, and robust. It then goes into details on Java basics, syntax, data types, operators, control flow statements, arrays, and naming conventions.

Uploaded by

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

1.

Java Introduction
1.1 Java History
 It was created in 1991 by James Gosling et al. of Sun Microsystems.
 Initially called Oak, in honor of the tree outside Gosling's window, its name was changed
to Java because there was already a language called Oak.
 The original motivation for Java
- The need for platform independent language that could be embedded in various
consumer electronic products like toasters and refrigerators.
- One of the first projects developed using Java.
- A personal hand-held remote control named Star 7.
- At the same time, the World Wide Web and the Internet were gaining popularity.
Gosling et. al. realized that Java could be used for internet programming.

1.2 Java Technology

 The Java technology is:


- A programming language
- A development environment
- An application environment
- A deployment environment
 Programming Language
- As a programming language, Java can create all kinds of applications that you
could create using any conventional programming language.
 Development Environment
As a development environment, Java technology provides you with a large suite of tools:
- A compiler (javac)
- An interpreter (java)
- A documentation generator (javadoc)
- A class file packaging tool and so on...
 Application Environment
- Java technology applications are typically general-purpose programs that run on
any machine where the Java Runtime Environment (JRE) is installed.
 Deployment Environment
- There are two main deployment environments:
- The JRE supplied by the Java 2 Software Development Kit (SDK) contains the
complete set of class files for all the Java technology packages, which includes
basic language classes, GUI component.
- The other main deployment environment is on your web browser.
 Most commercial browsers supply a Java technology interpreter and runtime
environment.

1.3 Why Java?


 An Object Oriented Programming Language (Developed at Sun Microsystems)
 A General Purpose Programming Language.
 Garbage Collection(No need to delete or return storage)
 Dynamic Loading (Classes are loaded as required)
 Platform Independence (Java Virtual Machine)
 Multithreading (Supports for multithreaded application)
 Secure
 Robust(Highly Supported Language, It’s portable across many OS.)
 Purely developed for networking support
1.4 Some difference with c/c++?
 Automatic memory management
- Garbage Collector
- No Dangling pointer or Memory Leaks
 No Pointer Handling
- No explicit reference or De-reference operations
 No Make files
 No Header files
- Like imported packages
 No function declaration like C
 No default function argument

1.5 Java Process

1.6 Java Platform


Software platform for running Java on top of any platform.
- Java Virtual Machine (JVM)
- Java Application Programming Interface(JAVA API)
1.7 Java Architecture
Java architecture arises out of four distinct but interrelated technologies:
– The Java Programming Language
– The Java Class File Format
– The Java Application Programming Interface
– The Java Virtual Machine

Java Programming Language


 Object-orientation
 Multi-threading
 Structured error-handling
 Garbage collection
 Dynamic linking

Class File
 The Java class file helps Java suitable for networks mainly in the areas of platform-
independence and network-mobility.
 Its role in platform independence is serving as a binary form for java programs that is
expected by the Java virtual machine but independent of underlying host platforms.
 The Java class file plays a critical role in Java's architectural support for network-
mobility. First, class files were designed to be compact, so they can more quickly move
across a network. Also, because Java programs are dynamically linked and dynamically
extensible, class files can be downloaded as needed.

Java API
The Java API is set of runtime libraries that give you a standard way to access the system
resources of a host computer.

Java Virtual Machine


 Java Virtual Machine is an abstract computer. It is a specification, defines certain
features, every java virtual machine must have, but leaves many choices to the designer
for each implementation.
 It can be implemented any percentage of hardware or software.

2. Java Basics
2.1 Java Features
 Simple
 Object Oriented
 Distributed
 Interpreted
 Robust
 Secure
 Architectural Neutral
 Portable
 High Performance
 Multithreaded and Dynamic
2.2.1 JDK
Java Development kit(JDK) : JDK is a superset of the JRE, and contains everything that is in the
JRE, plus tools such as the compilers and debuggers necessary for developing applets and
applications. The above illustrates all the component technologies in Java SE platform and how
they fit together.
– applet viewer : Allows you run applet without browser.
– Javac (Compiler): The Java Compiler that use to compile programs written in java
to byte codes.
– Java (interpreter ) : it interprets the byte code
– Javadoc (Doc. Generator) : Generates documentation in HTML Format from java
source code.
– Javap (Disaasembler): Disassembles the byte code generates java code in text
format.
– Jdb (debugger): The debugger helps to fix the bugs in java program.

2.2.2 JRE
Java Runtime Environment (JRE) : The Java Runtime Environment (JRE) provides the libraries,
the Java Virtual Machine, and other components to run applets and applications written in the
Java programming language. In addition, two key deployment technologies are part of the JRE:
Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which
deploys standalone applications over a network. It is also the foundation for the technologies in
the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and
deployment. The JRE does not contain tools and utilities such as compilers or debuggers for
developing applets and applications.

2.3 Java Basic Syntax


 Case sensitive.
 Each statement ends with ‘;’.
 To begin and end block you use ‘{‘ and ‘}’
 Space, tab, and enter characters can be used to make the code readable.
2.3.1 Comments
Three ways of commenting:
- Comment on rest of line
// rest of this line is comment
- Multiple lines comment
/* This is multiple line comment like c and c++
*/
- Java doc comments
/* *
* This comment will be included
* in documentation
* generated with javadoc
*/

2.3.2 Identifiers
 Identifiers can contain any combination of upper case, lower case, numbers and ‘$’, ‘_’.
 An identifier must not begin with a number.

2.3.3 Java Keywords


2.3.5 Type casting

Type casting = to change a basic type to another


– Int my_int = 70
– Char c = (char) my_int;

2.3.6 Constants

2.3.7 Operator Precedence


2.3.8 Branching if else statement

2.3.9 Branching switch statement

2.3.10 Looping constructs, while


2.3.11 Branching do while statement

2.3.12 looping constructs


2.3.13 Labeled blocks and branching
There is no ‘goto’ statements in java, instead have labeled break statement.

2.4 Naming convention


 Methods, variables and objects starts with leading lower case letter.
– next() , getData(), readLine() e.t.c
 Classes starts with leading upper case letter.
– String, StringBuffer, Vector, Calculator e.t.c
 Constants (final) are all upper case.
– DEBUG , MAX_SCROLL_X, CAPACITY
 Word separation in identifiers is done by capitalization except for constants where
underscore is used.
2.5 Arrays
Array is a homogeneous collection of data items stored in contiguous memory.

Declaring Array:
– To declare an array, write the data type, followed by a set of square brackets [],
followed by the identifier name.
– e.g.: int ages[] or int []ages;
– Int v[]; //simple array of ints
v = new int[10]; //fixed length of array
Some points of Arrays
 To access an array element, or a part of the array, you use a number called an index or a
subscript.
 Elements inside your array are from 0 to (sizeOfArray-1).
 In order to get the number of elements in an array, you can use the length field of an
array. The length field of an array returns the size of the array.
It can be used by writing, i.e., arrayName.length
 Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays
are declared by appending the appropriate number of bracket pairs after the array name.
// integer array 512 x 128 elements
int [][] twoD = new int[512][128];

// character array 8 x 16 x 24
char [][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns


String [][] dogs = {{ "terry", "brown" },
{"Kristin", "white"},
{"toby", "gray"},
{"fido", "black"}
};
Example:
public class InitArray {
public static void main(String[] args) {
int[] initarray;
initarray = new int[10];

for(int i=0; i < initarray.length; i++) {


initarray[i] = i * 2;
}
for(int j=0; j<initarray.length; j++) {
System.out.println("i value: "+j+ " :initarray: "+initarray[j]);
}
}
}
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.
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.

Example: Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range
lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A
short data type is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its
minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.

The int data type is generally used as a default data type for integral values unless
if there is no problem about memory.

Example: int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -
1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum
value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is
used when you need a range of values more than those provided by int.

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

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value
range is unlimited. It is recommended to use a float (instead of double) if you need
to save memory in large arrays of floating point numbers. The float data type
should never be used for precise values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just
like float. The double data type also should never be used for precise values, such
as currency. Its default value is 0.0d.

Example: double d1 = 12.3


Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to
store characters.

Example: char letterA = 'A'

2. Non Primitive Data Types in


Java
The non-primitive Java data types are created by the
programmer during the coding process, they are known as
the “reference variables” or “object variables” as they
refer to a location where data is stored.
2.1 Java String
Strings are basically a collection of characters, they cannot
change once they are created.
Wait, take a break and learn Strings in Java
2.2 Java Array and object
An array in Java is a group of variables that are similar in
nature and we can allocate them dynamically. Their size
has to specify in int, and their length can be found by
member length. Their indexing always starts with zero.
They have methods, which a primitive data type cannot
have.
Literals:
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.
Literals can be assigned to any primitive type variable.

Example
byte a = 68;
char a = 'A'

Type Conversion:

Type conversion means converting a variable of one data type to another.

For example, we can assign variable of integer data type into a variable of long data type.
Now, this is just a simple example of type conversion. There are other types of
conversion as well in Java.

Java has two types of conversion:

1. Automatic Conversion / Implicit conversion


2. Explicit Conversion
Automatic Conversion / Implicit
conversion

Automatic conversion is the type of conversion where we


don’t need to do any explicit conding for converting a datatype
to another, we just assign a variable into another.

Consider the following example:

public class Conversion {

public static void main(String[] args) {

int i = 10;

long l = i;

System.out.println("The long value is : " + l);

}
Output :

The long value is : 10

Explicit type casting in Expressions

While evaluating expressions, the result is automatically updated to


larger data type of the operand. But if we store that result in any
smaller data type it generates compile time error, due to which we
need to type cast the result.
Example:

//Java program to illustrate type casting int to byte


class Test
{
public static void main(String args[])
{
byte b = 50;

//type casting int to byte


b = (byte)(b * 2);
System.out.println(b);
}
}
Output
100
Automatic Type Promotion in Expressions
For example, examine the following expression:

public class Main {


public static void main(String[] argv) {
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
}
}

The result of a * b exceeds the range of byte. To handle this kind of problem, Java
automatically promotes each byte or short operand to int. a * b is performed using
integers.

3. 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:

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 Bitwise Operator:


The Java Bitwise Operators allow access and modification of a
particular bit inside a section of the data. It can be applied to integer
types and bytes, and cannot be applied to float and double.
public class bitwiseop {
public static void main(String[] args) {
//Variables Definition and Initialization
int num1 = 30, num2 = 6, num3 =0;

//Bitwise AND
System.out.println("num1 & num2 = " + (num1 & num2));

//Bitwise OR
System.out.println("num1 | num2 = " + (num1 | num2) );

//Bitwise XOR
System.out.println("num1 ^ num2 = " + (num1 ^ num2) );

//Binary Complement Operator


System.out.println("~num1 = " + ~num1 );

//Binary Left Shift Operator


num3 = num1 << 2;
System.out.println("num1 << 1 = " + num3 );

//Binary Right Shift Operator


num3 = num1 >> 2;
System.out.println("num1 >> 1 = " + num3 );

//Shift right zero fill operator


num3 = num1 >>> 2;
System.out.println("num1 >>> 1 = " + num3 );

}
}

Java Relational Operator

Java has six relational operators that compare two numbers and return a
boolean value. The relational operators are < , > , <= , >= , == , and != .

public class Test {

public static void main(String args[]) {


int a = 40;
int b = 50;

System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Java Boolean Operators

Java Logical Operators


The Java Logical Operators work on the Boolean operand. It's also
called Boolean logical operators. It operates on two Boolean values,
which return Boolean values as a result.
Java Assignment Operators
The Java Assignment Operators are used when you want to assign a value to the expression. The
assignment operator denoted by the single equal sign =.

Java ? Operator Or 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


Following is an example −
Example

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 );
}
}

Operator Precedence

In an expression that contains multiple operators, Java uses a number of


rules to decide the order in which the operators are evaluated. The first and
most important rule is called operator precedence. Operators in an
expression that have higher precedence are executed before operators with
lower precedence

The operators in the table are listed below according to the


precedence. The one with the highest precedence is on the top
and then are of lower precedence and so on.

You might also like