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

CH1_1

Uploaded by

abhishekmane280
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)
17 views

CH1_1

Uploaded by

abhishekmane280
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/ 19

CH1.

Introduction to JAVA
What is Java?
 Java is a Platform Independent Programming language
 Any hardware or software environment in which a program runs, known as a platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.
 Java Version
JDK Alpha and Beta (1995) JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997) J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000) J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004) Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011) ……………
What it is Used?
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in..etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types of Java Application?
There are mainly 4 type of applications that can be created using java:
 1) Standalone Application
 It is also known as desktop application or window-based application.
 An application that we need to install on every machine such as media player, antivirus
etc.
 AWT and Swing are used in java for creating standalone applications.
 2) Web Application
 An application that runs on the server side and creates dynamic page, is called web
application.
 Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications
in java.
 3) Enterprise Application
 An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering.
 In java, EJB is used for creating enterprise applications.
 4) Mobile Application
 An application that is created for mobile devices.
 Currently Android and Java ME are used for creating mobile applications.
Brief History of JAVA
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
 originally designed for small, embedded systems in electronic appliances like set-top boxes.
 initially called Oak and was developed as a part of the Green project
 In 1995, Oak was renamed as "Java". Java is just a name not an acronym.
 originally developed by James Gosling at Sun Microsystems(which is now a subsidiary of Oracle
Corporation) and released in 1995.
 JDK 1.0 released in(January 23, 1996).
Features of Java
 Simple
 Java is simple in the sense that:
 syntax is based on C++ (so easier for programmers to learn it after C++).
 removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
 Object-Oriented
 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 simplify software
development and maintenace by providing some rulues.
 Basic concepts of OOPs are:
 1. Object
 2. Class
 3. Inheritance
 4. Polymorphism
 5. Abstraction
 6. Encapsulation

 Platform Independent
 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's a software-based platform that runs on top of other hardware-based platforms. It
has two components:
 Runtime Environment & 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 Secured because:
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Class loader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
• Byte code Verifier- checks the code fragments for illegal code that can violate access
right to objects.
• Security Manager- determines what resources a class can access such as reading and
writing to the local disk. Security can also be provided by through SSL, JAAS,
cryptography etc.

 Robust
 Java is Robust because –
 Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
 There is exception handling and type checking mechanism in java. All these points
makes java robust.
 Architecture-neutral
 There is no implementation dependent features e.g. size of primitive types is set.

 C/C++Program Execution

 Java Program Execution


 Portable : We may carry the java byte code to any platform.
 High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
 Distributed : We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may 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 shares the same memory. Threads are important for multi-media, Web
applications etc.
STEPS for JAVA Program
Requirement: install the JDK if you don't have installed it You may also use the eclipse different version.
 Write java program in notepad (IDEs like Eclipse can be used) and save file with .java extension.
 Before compile and run program, we need to set the path of the bin directory under jdk.
[required only once after installation]
 To compile program
javac Simple.java
 To execute:
java Simple
Output: Hello World

Hello World Java Program


Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello World");
}
}
 class is used to declare a class in java.
 public is an access modifier which represents visibility, it means it is visible to all.
 static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create object to invoke the
main method. So it saves memory.
 void is the return type of the method, it means it doesn't return any value.
NOTE:
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

Difference between JDK,JRE and JVM


JRE
 JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is
the implementation of JVM. It contains set of libraries + other files that JVM uses at runtime.
JDK
 JDK is an acronym for Java Development Kit. It contains JRE + development tools.

JVM:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
 JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
 The JVM performs four main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
 JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

JVM Architecture of Java


1) Classloader: Class loader is a subsystem of JVM it is used to load class files.
2) Class(Method) Area: stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.
3) Heap: It is the runtime data area in which objects are allocated.
4) Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return. Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register: PC (program counter) register. It contains the address of the Java virtual
machine instruction currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter: Read byte code stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of
time needed for compilation. Here the term ‘compiler’ refers to a translator from the instruction
set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Different ways to write java program:


There are many ways to write a java program. The modifications that can be done in a java program are
given below:
1) By changing sequence of the modifiers, method prototype is not changed.
static public void main(String args[])
2) subscript notation in java array can be used after type, before variable or after variable.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
3) You can provide var-args support to main method by passing 3 ellipses (dots)
public static void main(String... args)
4) Having semicolon at the end of class in java is optional.
Let's see the simple code.
class A{
static public void main(String... args){
System.out.println("Hello Java"); } };

EX1: Program of swapping two numbers without using third variable and +,-.

Java Development Kit (JDK) Tools

1. javac: The Java compiler which converts Java source code into bytecode.
2. java: The Java application launcher which runs Java applications by starting the Java
Virtual Machine (JVM).
3. javadoc: A documentation generator which creates HTML documentation from Java
source code comments.
Syntax: javadoc filename
4. javap: The Java class file disassembler, used to view the contents of compiled class files.
The javap tool allows you to query any class and find out its list of methods and constants.
Syntax: javap [ options ] class
Example: javap java.lang.String
It is a disassembler which allows the bytecodes of a class file to be viewed when used with a
classname and the –c option.
Syntax: javap -c class
5. jdb: - jdb helps you find and fix bugs in Java language programs. This debugger has limited
functionality.
Syntax: jdb [ options ] [ class ] [ arguments ]
options : Command-line options.
class : Name of the class to begin debugging.
arguments : Arguments passed to the main() method of class.

Java comments
Java supports three types of comments that can be used to annotate the code: single-line comments,
multi-line comments, and documentation comments.
 Single-Line Comments : Single-line comments start with // and continue to the end of the line. They
are typically used for brief explanations or notes.
 Multi-Line Comments: Multi-line comments start with /* and end with */. They can span multiple
lines and are useful for longer explanations or temporarily disabling blocks of code.
 Documentation Comments: Documentation comments start with /** and end with */. They are
used to generate API documentation and are typically placed before classes, methods, or fields. The
javadoc tool processes these comments to create HTML documentation.

Data Types
 “Java Is a Strongly Typed Language.”
- Every variable has a type, every expression has a type, and every type is strictly defined.
- all assignments, whether explicit or via parameter passing in method calls, are checked for
type compatibility
- no automatic conversions of conflicting types.
- Any type mismatches are errors.
 The Primitive Types:
- Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
- Integers/Numeric - includes byte, short, int, and long, which are for whole-valued
signed numbers.

- Floating-point numbers - includes float and double, which represent numbers with
fractional precision.

- Characters - includes char, which represents symbols in a character set, like letters and
numbers. Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages. In Java
char is a 16-bit type (2 Bytes). The range of a char is 0 to 65,536.
- Booleans- Java has a primitive type, called boolean, for logical values. It can have only one
of two possible values, true or false.

Non-primitive data types:


The non-primitive data types include Classes, Interfaces, String and Arrays.
Accepting Console input:
There are three/four main ways to read console input in Java:
1. Scanner Class: This is the most common and preferred method. Scanner reads user input from
the standard input stream (System.in). It provides methods to read different data types like
String, int, double etc.
import java.util.Scanner;
public class ScannerDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter firstname and lastname:");
String fname = sc.next();
String lname = sc.next();
System.out.println("Firstname ="+fname);
System.out.println("Lastname ="+lname);
}
}
Other methods of Scanner class are:

2. BufferedReader Class: This is a more traditional method but involves more code. It requires
wrapping System.in with InputStreamReader and then with BufferedReader for efficient
reading. Reads text from a character-input stream.
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BRDemo {


public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your age: ");
String ageStr = reader.readLine();
int age = Integer.parseInt(ageStr); // Convert String to int
System.out.println("Your age is: " + age);
}
}
o Methods of BufferedReader Class:
 read() - Reads a single character.
 readLine() - Reads a line of text.
o As BufferedReader Class methods reads text input, we need to convert it into respective
types.
o It can be done using Class Integer and Class Double.
 Integer.parseInt() - parseInt() is a static method that takes in a String object and
returns an int whose value associates with the content of that String.
 Double.parseDouble() - parseDouble() is a static method that takes in a String
object and returns an double whose value associates with the content of that
String.

3. Command-Line Arguments: You can pass arguments directly when running the program. These
arguments are stored in the String args[] array of the main method.
public class CommandLineDemo {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a name as argument");
return;
}
For(int i=0;i<args.length;i++)
{
System.out.println("Argument 1:”+args[i]);
}
}
}

EX2: Write a Program to accept two numbers and display result of arithmetic operations.

EX3: Write a Program to accept a number and display result of factorial of it.

EX4: Write a program to calculate perimeter and area of rectangle

Useful Methods and Values in Class Integer and Class Double


Integer.MAX_VALUE is an int holding the maximum value an int can have (231-1).
Integer.MIN_VALUE is an int holding the minimum value an int can have (-231).
Integer.toBinaryString() returns a String of the int argument as an unsigned integer in base 2.
Integer.toOctalString() returns a String of the int argument as an unsigned integer in base 8.
Integer.toHexString() returns a String of the int argument as an unsigned integer in base 16.
Integer.toString() returns the String representation of the int argument
Double.MAX_VALUE is the largest positive finite value of type double.
Double.MIN_VALUE is the smallest positive nonzero value of type double.
Double.NaN is a Not-a-Number (NaN) value of type double.
Double.POSITIVE_INFINITY is the positive infinite value of type double.
Double.NEGATIVE_INFINITY is the negative infinite value of type double.
Double.isInfinite() returns true if the double argument is infinitely large in magnitude.
Double.isNaN() returns true if the double argument is an NaN value.
Double.toHexString() returns the hexadecimal String of the double argument.
Double.toString() returns the String representation of the double argument.

.
Operators in Java
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Control Structures


1. Java If-else Statement
if(condition){ if(condition){
//code to be executed //code if condition is true
} }else{
//code if condition is false
}
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
}
Ex: Program to check min, max

Ex Program to check +ve, -ve, zero number

Switch Statement
- The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long.
- Java Switch Statement is fall-through. The Java switch statement is fall-through. It means it
executes all statements after the first match if a break statement is not present.
- 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;
}

Ex. Write program to accept char +,-,*, / to perform arithmetic operations.

JAVA Loops/ Iterations


- Java’s iteration statements are for, while, and do-while.

while
- The while loop is Java’s most fundamental loop statement.
- It repeats a statement or block while its controlling expression is true.
- Syntax:
while(condition)
{
// body of loop
}
- the body of the loop will be executed as long as the conditional expression is true.
- When condition becomes false, control passes to the next line of code immediately following
the loop.
- The curly braces are unnecessary if only a single statement is being repeated.
do-while
- .The do-while loop always executes its body at least once, because its conditional expression is
at the bottom of the loop.
- Syntax:
do {
// body of loop
} while (condition);
- Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression.
- If this expression is true, the loop will repeat. Otherwise, the loop terminates.

for
- Java supports to forms of for
- Syntax 1:
for(initialization; condition; iteration)
{
// body
}
- Syntax 2:
for(type itr-var : collection)
statement-block
- type specifies the type and itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end. The collection being cycled
through is specified by collection.
EX. Program to print even numbers between 1 to 100.
EX. Program to print multiples of 3 between 1 to 100.
Ex. Program to print the pattern

Pattern 1 Pattern 2 Pattern 3


* 1 12345
** 12 1234
*** 123 123
**** 1234 12
***** 12345 1

***** $* * * * $*** $
* * * $ * * $ $*
* * * $ * * $ *
* * * $ * * $ $*
***** ****$ $*** $

*
**
***
****
*****
****
***
**
*
EX. Program to print reverse of a number
EX Program to check a number is Armstrong or not

Arrays
- An array is a group of like-typed variables that are referred to by a common name.
- Arrays of any type can be created and may have one or more dimensions.
- A specific element in an array is accessed by its index.
- Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
- Syntax: array declaration is
type var_name[ ];
eg. int month_days[];
- type determines the data type of each element that comprises the array.
- to allocate memory a special operator new is used.
Var_name = new type[size];
eg. month_days = new int[12];
- to use new to allocate an array, you must specify the type and number of elements to allocate.
The elements in the array allocated by new will automatically be initialized to zero.
- in Java, all arrays are dynamically allocated.
- Arrays can be initialized when they are declared.
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
- To find out how many elements an array has, use the length property:
Eg. System.out.println(month_days.length);
- Iterating through array:
1. We can loop through the array elements with the for loop, and use the length property
to specify how many times the loop should run.
 eg.
for (int i = 0; i < month_days.length; i++) {
System.out.println(month_days [i]);
}
2. There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:
Syntax:
for (type variable : arrayname) {
...
}
eg.
for (int d : month_days) {
System.out.println(d);
}

Ex. Write a program to accept the array element and display in reverse order.
Ex. Write a program to accept the array element and display Sum and Average of elements in a
array.
Ex. Write a program to accept the array element and display Min and Max in a array.

Multidimensional Arrays
- In Java, multidimensional arrays are actually arrays of arrays.

- Syntax
dataType[][] arrayRefVar;
dataType [][]arrayRefVar;
dataType arrayRefVar[][];
dataType []arrayRefVar[];
eg.
int twoD[][] =new int[4][5];
OR
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
- Jagged Array in Java : If we are creating odd number of columns in a 2D array, it is known as a
jagged array.
Eg.
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];

-
- EX: Write a java program to accept matrix and print its transpose.
- EX: Write a java program to accept matrix and row wise sum.
ADDITIONAL: Console Class (Java 1.5 and above): This class offers methods specifically for console
input/output. It can read text and passwords (without echoing characters)
import java.io.Console;

import java.io.Console; public class ConsoleDemo {


class ReadStringTest{ public static void main(String[] args) {
public static void main(String args Console console = System.console();
[]){ if (console == null) {
Console c=System.console();
System.err.println("Console not available");
System.out.println("Enter your nam
e: ");
return;
String n=c.readLine(); }
System.out.println("Welcome "+n); String password = new
String(console.readPassword("Enter your password: "));
} System.out.println("Your password (not echoed): " +
} password);
}
}

You might also like