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

1. Introduction to Java - Walys (10)

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

1. Introduction to Java - Walys (10)

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

WALYS Life Skills International Pvt. Ltd.

Introduction to Java

JAVA
Java was introduced in 23rd January 1996. But it was started by Sun
Microsystems in 1991. At that time Sun Microsystems had a requirement to
prepare software for consumer electronic devices like remote controllers,
cable TV switch boxes etc… They create 30 members team with James
Gosling and Patrck Naughtan starts "Green" project.
The language was initially called Oak after an oak tree that stood
outside Gosling's office. Later the project went by the name Green and was
finally renamed Java, from Java coffee, the coffee from Indonesia.

They need for new qualities for new programming language:


1. Simple PL
2. Tight coded PL
3. Arch. Neutral PL
Simple PL:
Less execution time ---> More performance
Less memory consumption ---> Less cost for the End product
Less power consumption. ---> Less maintenance cost for the end product.

Tight coded PL:


If any programming language takes more-number of instructions to achieve a
particular requirement that programming language is called loose codded
programming language.
C and C++ are loose codded programming languages:
For example stack operations first we can create
push() – 20 line of code
pop() – 20 line of code
peek() – 20 line of code
total 60 lines of code.

1
WALYS Life Skills International Pvt. Ltd. Introduction to Java

If any programming language takes less number of instructions to achieve a


particular requirement that programming language is called tight codded
programming language.
Java is tight codded programming languages:
For example stack operations first we can create
Stack s=new Stack();
s.push("aaa")
s.pop()
s.peek()

Arch. Neutral PL:


Java applications are compiled in one Architecture/hardware (RAM, Hard
Disk) and that Compiled program runs on any architecture(hardware) is called
Architectural Neutral.

JAVA introduction:-
Author: James Gosling
Vendor: Sun Micro System(merged into Oracle Corporation)
Objective: To prepare simple electronic consumer goods.
Project: Green
Initial Name: OAK language
Present Name: Java
First Version: JDK1.0 [1996, Jan-23rd]
Type: open source & free software
Symbol: coffee cup with saucer
SUN: Stanford Universally Network
Slogan/Motto: WORA (write once run anywhere)

2
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Importance of java: - According to the SUN, 3 billion devices run on the java
language only.
1) Java is used to develop Desktop Applications such as MediaPlayer,
Antivirus etc.
2) Java is Used to Develop Web Applications such as sravyajobs.com,
irctc.co.in etc.
3) Java is used to Develop Enterprise Application such as Banking
applications.
4) Java is used to Develop Mobile Applications.
5) Java is used to Develop Embedded System.
6) Java is used to Develop SmartCards.
7) Java is used to Develop Robotics.
8) Java is used to Develop Games ………………………..etc.

Java Evolutions:
Version Name
Code Release Date
Name
This was the initial release and was originally
JDK 1.0 Oak January 1996
called Oak. This had very unstable APIs and
one java web browser named WebRunner.
The first stable version, JDK 1.0.2, was called
Java 1.

JDK 1.1 (none) February 1997  AWT event model


 Inner classes
 JavaBeans
 JDBC
 RMI
 Reflection which supported
Introspection only, no modification at
runtime was possible.
 JIT (Just In Time) compiler for Windows

3
WALYS Life Skills International Pvt. Ltd. Introduction to Java

J2SE 1.2 Playgro December 1998  strictfp keyword


und
 Swing graphical API
 Sun’s JVM was equipped with a JIT
compiler for the first time
 Java plug-in
 Collections framework

J2SE 1.3 Kestrel May 2000  HotSpot JVM


 Java Naming and Directory Interface
(JNDI)
 Java Platform Debugger Architecture
(JPDA)
 JavaSound
 Synthetic proxy classes

J2SE 1.4 Merlin Febuary 2002  assert keyword

 Regular expressions
 Exception chaining
 Internet Protocol version 6 (IPv6)
support
 New I/O; NIO
 Logging API
 Image I/O API
 Integrated XML parser and XSLT
processor (JAXP)
 Integrated security and cryptography
extensions (JCE, JSSE, JAAS)
 Java Web Start
 Preferences API (java.util.prefs)

4
WALYS Life Skills International Pvt. Ltd. Introduction to Java

J2SE 5.0 Tiger September 2004  Generics


 Annotations
 Autoboxing/unboxing
 Enumerations
 Varargs
 Enhanced for each loop
 Static imports
 New concurrency
utilities in java.util.concurrent
 Scanner class for parsing data from
various input streams and buffers.

JAVA 6 Mustang December 2006  Scripting Language Support


 Performance improvements
 JAX-WS
 JDBC 4.0
 Java Compiler API
 JAXB 2.0 and StAX parser
 Pluggable annotations
 New GC algorithms

JAVA 7 Dolphin July 2011  JVM support for dynamic languages


 Compressed 64-bit pointers
 Strings in switch
 Automatic resource management in try-
statement
 The diamond operator
 Simplified varargs method declaration
 Binary integer literals
 Underscores in numeric literals
 Improved exception handling

5
WALYS Life Skills International Pvt. Ltd. Introduction to Java

 ForkJoin Framework
 NIO 2.0 having support for multiple file
systems, file metadata and symbolic
links
 WatchService
 Timsort is used to sort collections and
arrays of objects instead of merge sort
 APIs for the graphics features
 Support for new network protocols,
including SCTP and Sockets Direct
Protocol

JAVA 8 March 2014  Lambda expression support in APIs


 Stream API
 Functional interface and default
methods
 Optionals
 Nashorn – JavaScript runtime which
allows developers to embed JavaScript
code within applications
 Annotation on Java Types
 Unsigned Integer Arithmetic
 Repeating annotations
 New Date and Time API
 Statically-linked JNI libraries
 Launch JavaFX applications from jar files
 Remove the permanent generation
from GC

JAVA 9 September, 21st  Java platform module system


2017
 Interface Private Methods
 HTTP 2 Client

6
WALYS Life Skills International Pvt. Ltd. Introduction to Java

 JShell – REPL Tool


 Platform and JVM Logging
 Process API Updates
 Collection API Updates
 Improvements in Stream API
 Multi-Release JAR Files
 @Deprecated Tag Changes
 Stack Walking
 Java Docs Updates
 Miscellaneous Other Features

JAVA 10 March, 20th 2018  JEP 286: Local Variable Type Inference
 JEP 322: Time-Based Release Versioning
 JEP 304: Garbage-Collector Interface
 JEP 307: Parallel Full GC for G1
 JEP 316: Heap Allocation on Alternative
Memory Devices
 JEP 296: Consolidate the JDK Forest into
a Single Repository
 JEP 310: Application Class-Data Sharing
 JEP 314: Additional Unicode Language-
Tag Extensions
 JEP 319: Root Certificates
 JEP 317: Experimental Java-Based JIT
Compiler
 JEP 312: Thread-Local Handshakes
 JEP 313: Remove the Native-Header
Generation Tool
 New Added APIs and Options
 Removed APIs and Options

7
WALYS Life Skills International Pvt. Ltd. Introduction to Java

JAVA 11 September, 25th  HTTP Client API


2018
 Launch Single-File Programs Without
Compilation
 String API Changes
 Collection.toArray(IntFunction)
 Files.readString() and Files.writeString()
 Optional.isEmpty()

JAVA 12 March, 19th  Collectors.teeing() in Stream API


2019
 String API Changes
 Files.mismatch(Path, Path)
 Compact Number Formatting
 Support for Unicode 11
 Switch Expressions (Preview)

 JEP-350: Dynamic CDS Archives


JAVA 13 September,
17th 2019  JEP-351: ZGC: Uncommit Unused
Memory
 JEP-353: Reimplement the Legacy
Socket API
 JEP-354: Switch Expressions
 JEP-355: Text Blocks
JAVA 14 March, 17th 2020  Switch Expressions (Standard) – JEP
361
 Pattern Matching
for instanceof (Preview) – JEP 305
 Helpful NullPointerExceptions – JEP
358
 Records (Preview) – JEP 359
 Text Blocks (Second Preview) – JEP
368
 Packaging Tool (Incubator) – JEP
343
 NUMA-Aware Memory Allocation for

8
WALYS Life Skills International Pvt. Ltd. Introduction to Java

G1 – JEP 345
 JFR Event Streaming – JEP 349
 Non-Volatile Mapped Byte Buffers –
JEP 352
 ZGC on macOS – JEP 364
 ZGC on Windows – JEP 365
 Foreign-Memory Access API
(Incubator) – JEP 370

JAVA 15 September,  Sealed Classes (Preview) – JEP 360


15th 2020  Pattern Matching
for instanceof (Second Preview) –
JEP 375
 Records (Second Preview) – JEP
359
 Text Blocks (Standard) – JEP 378
 Hidden Classes – JEP 371
 Remove the Nashorn JavaScript
Engine – JEP 372
 Reimplement the Legacy
DatagramSocket API – JEP 373
 Disable and Deprecate Biased
Locking – JEP 374
 Shenandoah: A Low-Pause-Time
Garbage Collector – JEP 379
 Remove the Solaris and SPARC
Ports – JEP 381
 Foreign-Memory Access API
(Second Incubator) – JEP 383
 Deprecate RMI Activation for
Removal – JEP 385

JAVA 16 16th March  JEP 338: Vector API (Incubator)


2021  JEP 347: Enable C++14 Language
Features
 JEP 357: Migrate from Mercurial to
Git
 JEP 369: Migrate to GitHub
 JEP 376: ZGC: Concurrent Thread-
Stack Processing
 JEP 380: Unix-Domain Socket
Channels
 JEP 386: Alpine Linux Port – not yet
stable

9
WALYS Life Skills International Pvt. Ltd. Introduction to Java

 JEP 387: Elastic Metaspace


 JEP 388: Windows/AArch64 Port
 JEP 389: Foreign Linker API
(Incubator)
 JEP 390: Warnings for Value-Based
Classes
 JEP 392: Packaging Tool
 JEP 393: Foreign-Memory Access
API (Third Incubator)
 JEP 394: Pattern Matching for
instanceof
 JEP 395: Records
 JEP 396: Strongly Encapsulate JDK
Internals by Default
 JEP 397: Sealed Classes (Second
Preview)

JAVA 17 14th  JEP 306: Restore Always-Strict


September Floating-Point Semantics
2021  JEP 356: Enhanced Pseudo-Random
Number Generators
 JEP 382: New macOS Rendering
Pipeline
 JEP 391: macOS/AArch64 Port
 JEP 398: Deprecate the Applet API
for Removal
 JEP 403: Strongly Encapsulate JDK
Internals
 JEP 406: Pattern Matching for switch
(Preview)
 JEP 407: Remove RMI Activation
 JEP 409: Sealed Classes
 JEP 410: Remove the Experimental
AOT and JIT Compiler
 JEP 411: Deprecate the Security
Manager for Removal
 JEP 412: Foreign Function & Memory
API (Incubator)
 JEP 414: Vector API (Second
Incubator)
 JEP 415: Context-Specific
Deserialization Filters

JAVA 18 22th March  JEP 400: UTF-8 by Default

10
WALYS Life Skills International Pvt. Ltd. Introduction to Java

2022  JEP 408: Simple Web Server


 JEP 413: Code Snippets in Java API
Documentation
 JEP 416: Reimplement Core
Reflection with Method Handles
 JEP 417: Vector API (Third
Incubator)
 JEP 418: Internet-Address
Resolution SPI
 JEP 419: Foreign Function & Memory
API (Second Incubator)
 JEP 420: Pattern Matching for switch
(Second Preview)
 JEP 421: Deprecate Finalization for
Removal

JAVA 19 20th  JEP 405: Record Patterns (Preview)


September  JEP 422: Linux/RISC-V Port
2022  JEP 424: Foreign Function & Memory
API (Preview)
 JEP 425: Virtual Threads (Preview)
 JEP 426: Vector API (Fourth
Incubator)
 JEP 427: Pattern Matching for switch
(Third Preview)
 JEP 428: Structured Concurrency
(Incubator)

JAVA 20 March 2023 

JAVA 21 September 
2023
Up to Java6 version, Java managed by Sun Microsystems and from Java7
version onwards Java managed by Oracle Corporation.
Parts of the java:-
Core java & Advanced Java are not official words, as per the Sun Micro
System standard the java language is divided into three parts.
1) J2SE
2) J2EE
3) J2ME

11
WALYS Life Skills International Pvt. Ltd. Introduction to Java

1) J2SE/JSE(Java 2 Standard Edition)


 Fundamentals of Java programming
To develop stand-alone applications
If we design and execute any application without using client server
architecture then that application is called standalone application.
5% of the applications are standalone applications.

2) J2EE/JEE(Java 2 Enterprise Edition)


It will cover server side programming.
To develop Distributed/ Enterprise applications.
 It will design and execute any application based on client server
architecture or by distributing application logic over multiple machines then
that application is called Distributed/ Enterprise application.
 95% of the applications are client server applications.

3) J2ME/JME(Java 2 Micro Edition)


 It will cover micro programming.
To develop Mobile based applications.
 If we design and execute any application based on Mobile hardware then
that application is called mobile-based application.

Differences between Java and Others[C and C++]


• C and C++ are Static programming Languages but Java is a dynamic
programming language.
• C and C++ are required pre-processor but Java is not required pre-
processor.
• C and C++ are platform Dependent but Java is platform independent.
• Pointers are available in C and C++ but pointers are not possible in
JAVA.
• Multiple inheritance is not possible in Java.

12
WALYS Life Skills International Pvt. Ltd. Introduction to Java

• Destructors are required in C++ but Destructors are not required in


JAVA.
• Operator overloading is not possible in Java.
• C,C++ are following "call by value" and "call by reference" parameter
passing mechanism but Java is following only "call by value" parameter
passing mechanism.

JAVA Features (Buzzwords)


To expose the nature of Java, Java has given the following features:
• Simple
• Object Oriented
• Platform Independent
• Architectural Neutral
• Portable
• Robust
• Secure
• Dynamic
• Distributed
• Multi-Threaded
• Interpreted
• High Performance

1. Simple
Java is simple programming language, because,
1.Java applications will take less memory and less execution time.
2.Java has removed almost all the confusion oriented features like
pointers, multiple inheritance,.....
3.Java is using all the simplified syntaxes from C and C++.
2. Object Oriented
Java is an object-oriented programming language, because, JAVA is able to
store data in the form of Objects only.

13
WALYS Life Skills International Pvt. Ltd. Introduction to Java

3. Platform Independent
Java is platform independent programming Language, because, Java allows
its applications to compile on one operating system and to execute on another
operating system.
4. Architectural Neutral
Java is an Arch Nuetral Programming language, because, Java allows its
applications to compile on one H/W Arch and to execute on another H/W
Arch.
5. Portable
Java is a portable programming language, because, JAVA is able to run its
applications under all the operating systems and under all the H/W Systems.
6. Robust
Java is Robust programming language, because,
1.Java is having very good memory management system in the form of heap
memory Management System, it is a dynamic memory management system,
it allocates and deallocates memory for the objects at runtime.
2.JAVA is having very good Exception Handling mechanisms, because, Java
has provided very good predefined library to represent and handle almost all
the frequently generated exceptions in java applications.
7. Secure
Java is very good Secure programming language, because,
1.JAVA has provided an implicit component inside JVM in the form of
"Security Manager" to provide implicit security.
2.JAVA has provided a seperate middleware service in the form of JAAS
[Java Authetication And Autherization Service] inorder to provide web security.
3.Java has provided very good predefined implementations for almost all well
known network security algfor the Java applications java.security package.
8. Dynamic
If any programming language allows memory allocation for primitive data
types at RUNTIME then that programming language is called as Dynamic
Programming Language.

14
WALYS Life Skills International Pvt. Ltd. Introduction to Java

JAVA is a dynamic programming language, because, JAVA allows memory


allocation for primitive data types at RUNTIME.
9. Distributed
By using JAVA we are able to prepare two types of applications
a)Standalone Applications b)Distributed Applications
a) Standalone Applications: If we design any java application with out using
client-Server arch then that java application is called as Standalone
application.
b)Distributed Applications: If we design any java application on the basis of
client-server arch then that java application is called as Distributed application.
To prepare Distributed applications, JAVA has provided a seperate module
that is "J2EE/JAVA EE".
10. Multithreaded
Thread is a flow of execution to perform a particular task.
There are two thread models a)Single Thread Model b)Multi Thread Model
a)Single Thread Model: It able to allow only one thread to execute the
complete application,it follows sequential execution, it will take more execution
time, it will reduce application performance.
b)Multi Thread Model: It able to allow more than one thread to execute
application, It follows parallel execution, it will reduce execution time, it will
improve application performance.
JAVA is following Multi Thread Model, JAVA is able to provide very good
environment to create and execute more than one thread at a time, due to this
reason, JAVA is Multi threaded Programming Language.
11. Interpreted
JAVA is both completive programming language and Interpretive
programming language.
1.To check developers mistakes in java applications and to translate java
program from High level representations to low level representation we need
to compile java programs 2.To execute java programs , we need an
interpreter inside JVM.

15
WALYS Life Skills International Pvt. Ltd. Introduction to Java

12. High Performance


JAVA is high performance programming language due to its rich set of
features like Platform independent, Arch Nuetral, Portable, Robust,
Dynamic,......

Java Naming conventions:


Java is a case sensitive language, where in Java applications there is a
separate reorganization for lower case letters and for upper case letters.
To use lower case and upper-case letters we have to use the following
conventions:
1. All Java classes, abstract classes and interface names must be
started with upper case letter and the subsequent symbols must also be
upper case characters.
Ex:
String
StringBuffer
InputStreamReader
2. All Java variable names must be started with lower case letter and the
subsequent symbols must be upper case characters.
Ex:
in, out, err
pageContext
3. All Java method names must be started with lower case letter and the
subsequent symbols must be upper case characters.
Ex:
concat()
forName()
getInputStream()
4. All constant variables must be provided in upper case letters.
Ex:
MIN_PRIORITY, NORM_PRIORITY

16
WALYS Life Skills International Pvt. Ltd. Introduction to Java

5. All package names must be provided in lower case letters.


Ex:
java.awt
java .util;
Note: All the above conventions are mandatory for predefined library, they are
optional form User defined library, but, suggestible.

Java Programming Format:


To design java applications, we have to use the following Structure.

Comment Section:
Comments are used to write the detailed description about application logics
to understand the logics easily.
When we write the comments the application maintenance will become easy.
Comments are non-executable code these are ignored during compilation.
There are 3 types of comments.
1) Single line Comment: -Possible to write the description in single line.
Syntax:- //description
2) Multi line Comment: -To write the description in more than one line. Starts
/* ends */
Syntax: - /* satement-1
Statement-2

17
WALYS Life Skills International Pvt. Ltd. Introduction to Java

;;;;;;;;;;;;;;
Statement-n
*/
3)Documentation Comments: - To write the description in more than one
page.
Syntax: - /*
*statement-1
*statement-2
*/
Note: We will use documentation comments to prepare API kind of
documentations, but it is not suggestible.
2. Package Section:
Package is a collection of related classes and interfaces as a single unit.
There are two types of packages in java:
Predefined packages
These packages are provided by Java along with software.
Ex: java.io
java.util
java.awt
User-defined Package
These packages are provided by the developers as per their application
requirements.
To declare user defined packages in java program we have to use
"Package section".
If we want to declare user defined packages in java programmer then we have
to use the following
Syntax.
package package_Name ;
Ex:
package satish;

18
WALYS Life Skills International Pvt. Ltd. Introduction to Java

3. import Section:
We want to use a particular package classes and interfaces in the present
java file, we can use import statement.
The default import package is java.lang.*;
Syntax:
import package_Name.*;
It will import all the classes and interfaces from the specified package.
Ex:
import java.io.*;

import package_Name.Member_Name;
It will import only the specified class or interface from the specified package.
Ex:
import java.io.BufferedReader
In java files, we are able to provide more than one import statement.
A java program with import statement:
import java.io.*;
---
---
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
----
----
A Java program without import statement:
java.io.BufferedReader br=new java.io.BufferedReader(new
java.io.InputStreamReader(System.in));

classes/interfaces section:
In Java files, we are not having any restrictions about the number of classes
and interfaces, it is possible to provide any no of classes and interfaces with in
a single java file.

19
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Main class Section:


Main Class is a java class, it includes main() method.
The main intention of main() method is,
1.To manage application logic which we want to execute by JVM directly we
have to use main() method.
2.To define starting point and ending point of the application execution we
have to use main() method.
Syntax:
public static void main(String args[ ])
{
----instructions----
}

Note:main() method is a conventional method with fixed prototype and with


user defined implementation part.
Steps to Design a First Application:
Step-1: Select the Editor.
Step-2: Write the application.
Step-3: Save the application.
Step-4: Compilation Process.
Step-5: Execution process.

Step1: Select an Editor


Editor is a software; it will provide very good env to write java programs and to
save java programs in our system.
EX: Notepad, Notepadplus, Editplus,....

Note: In real time application development, it is not suggestible to use Editors,


it is always suggestible to use IDEs[Integrated Development Environment].
EX: Eclipse, MyEclipse, Netbeans,........
Note: do the practical’s of core java by using edit plus editor.

20
WALYS Life Skills International Pvt. Ltd. Introduction to Java

2. Write Java Program:


To write java program we have to use some prederfined library provided by
JAVA API[Application Programming Interface].
EX :
D:\javaprog\ Test.java
class Test
{
public static void main(String args[])
{
System.out.println("First Java Application");
}
}
3. Save Java File:
To save java file in our system, we have to follow the following two conditions.
1. If the present java file contains any public element[class, abstract class,
interface, enum] then we must save java file with public element name only. If
we violate this condition then compiler will rise an error.
2. If no public element is identified in our java file then it is possible to save
java file with any name like abc.java or xyz.java, but, it is suggestible to save
java file with main() method class name.
Ex: Test.java
4. Compilation process.
1.The main purpose of compiling JAVA file is to convert JAVA programme
from High Level Representation to LowLevelRepresentation.
2.To Check compilation errors.
To compile JAVA file,we have to use the following command on command
prompt from the location where JAVA File is Saved
javac File_Name.java
D:\satish>javac Test.java compilation process
Compiler responsibilities:-

21
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Compiler check the syntax errors, If the application contains syntax errors
then compiler will generate error message in the form of compilation error.
If the application does not contain syntax, errors then compiler translate
.java to .class file.
Note: - In java compiler generate .class files based on number of classes
present in source file.
If the source file contains 100 classes after compilation compiler generates
100 .class files
5. Execution process.
Run /execute the java application by using java command.
Syntax:- java classname
java Test
D:\satish>java Test
Hi Satish
Note:
1. JVM will take Main_Class name from command prompt.
2. JVM will search for Main_Class at current location,at Java predefined
library and at the locations referred by "classpath" environment variable.
3. If the required Main_Class .class file is not available at all the above
locations then JVM will provide the following.
JAVA6: java.lang.NoClassDefFoundError:Test
JAVA7: Error:Could not find or load main class Test
4. If the required main class .class file is available at either of the above
locations then JVM will load main class bytecode to the memory by using
"Class Loaders".
5. After loading main class bytecode to the memory, JVM will search for
main() method.
6. If main() method is not available at main class byteCode then JVM will
provide the following.
JAVA6: java.lang.NoSuchMethodError:main

22
WALYS Life Skills International Pvt. Ltd. Introduction to Java

JAVA7: Error:Main method not found in class Test, please define main
method as:
public static void main(String args[])
7. If main() method is available at main class bytecode then JVM will access
main() method by creating a thread called as "Main thread".
8. JVM will access main() method to start application execution by using main
thread, when main thread reached to the ending point of main() method then
main thread will be in destroyed/dead state.
9. When main Thread is in dead state then JVM will stop all of its internal
processes and JVM will go to ShutDown mode.

23
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Main Method
 Whether the class contains main() method or not and whether it is properly
declared or not these checking‟s are not responsibilities of the compiler, at
runtime JVM is responsible for this.
Example:
class Test
{ }
Output:
javac Test.java
java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)

· JVM always searches for the main() method with the following signature.

· If we are performing any changes to the above signature then the code won‟t
run and will get Runtime exception saying Main method not found in class
Test.

Anyway the following changes are acceptable to main() method.


1) The order of modifiers is not important that is instead of public static we can
take static public.
2) We can declare string[] in any acceptable form
String[] args
String []args
String args[]
3) Instead of args we can use any valid java identifier.
String[] satish
4) We can replace string[] with var-arg parameter.

24
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Example:
main(String... args)
5) main() method can be declared with the following modifiers.
· final, synchronized, strictfp.

Creating hello java example


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

save this file as Test.java


To compile: javac Test.java
To execute: java Test
Output:Hello Java

25
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Language Fundamentals:
To prepare java applications, we need some fundamentals provided by Java
programming language.
1. Tokens
2. Data Types
3. Type Casting
4. Java Statements
5. Arrays

1. Tokens:
Smallest logical unit in java programming is called as "Lexeme".
The Collection of Lexemes come under a particular group is called as "Token"
int a=b+c*d;
Lexemes: int, a, =, b,+, c, *, d, ;-----> 9
Tokens:
1) Data Types: int
2) Identifiers: a, b, c, d
3) Operators: =, +, *
4) Special Symbol: ;

Types of tokens: 4
To prepare java applications, java has provided the following list of tokens.
1. Identifiers
2. Literals
3. Keywords/ Reserved Words
4. Operators

Identifiers: - A name in Java program is called identifier, which can be used


for identification purpose. It can be method name, variable name, class name
or label name.

26
WALYS Life Skills International Pvt. Ltd. Introduction to Java

EX: int a=10;


int ----> Data Type
a ------> variable[Identifier]
= ------> Operator
10 -----> constant
; ------> Terminator
Rules to define java identifiers:
Rule 1: The only allowed characters in java identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _
5) $
Rule 2: If we are using any other character we will get compile time error.
Example:
1) total_number-------valid
2) Total#------------------invalid
Rule 3: identifiers are not allowed to starts with digit.
Example:
1) ABC123---------valid
2) 123ABC---------invalid
Rule 4: java identifiers are case sensitive, Java language itself treated as
case sensitive language.
Example:
class Test
{
int number=10;
int Number=20;
int NUMBER=20; we can differentiate with case.
intNuMbEr=30;
}

27
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Rule 5: There is no length limit for java identifiers.


Rule 6: We can‟t use reserved words as identifiers.
Example: int if=10; --------------invalid
Rule 7: All predefined java class names and interface names we use as
identifiers.
Example 1:
class Test
{
public static void main(String[] args)
{
int String=10;
System.out.println(String);
}
}
Output:
10
Even though it is legal to use class names and interface names as
identifiers but it is not a good programming practice.

2. Literals:
Literal is a constant assigned to the variables.
EX:
int a=10;
int ----> data type
a ------> variables/ identifier
= ------> Operator
10 -----> constant[Literal].
; ------> Special symbol.
To prepare java programs, JAVA has provioded the following set of literals.
1. Integer / Integral Literals:
byte, short, int, long ----> 10, 20, 30,.... char -----> 'A','B',.....

28
WALYS Life Skills International Pvt. Ltd. Introduction to Java

2. Floating Point Literals:


float ----> 10.22f, 23.345f,..... double----> 11.123, 456.345,....
3. Boolean Literals:
boolean -----> true, false
4. String Literals:
String ---> "abc", "def",......
Note: JAVA7 has given a flexibility like to include '_' symbols in the middle of
the literals inorder to improve readability.
EX:
float f=12345678.2345f;
float f=1_23_45_678.2345f;
If we provide '_' symbols in the literals then compiler will remove all '_'
symbols which we provided, compiler will reformate that number as original
number and compiler will process that number as original number.

Reserved Words: 53
In Java some words are reserved to represent some meaning or
functionality, such type of words are called reserved words.

Conclusions:
• All 53 reserved words in Java contain lower case alphabets.
• In Java, we have only new keyword, and there is no delete keyword
because destruction of useless objects is the responsibility of garbage
collector.
• The following new keywords in Java.
strictfp(1.2), assert(1.4), enum(1.5)

29
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Operators:-

Operator is a symbol used to perform the operation. There are different types
of operators in Java

1. Arithmetic Operators:-

+,-,*,/,%

Ex:

class Test

public static void main(String[] args)

int a=10,b=20;

System.out.println(a+b);

System.out.println(a-b);

System.out.println(a*b);

System.out.println(a/b);

System.out.println(a%b);

System.out.println(10*10/5+3-1*4/2);

2. Relational operator or Comparision operators:

<,>,<=,>=,==,!=

Ex:

class ComparisonDemo

30
WALYS Life Skills International Pvt. Ltd. Introduction to Java

public static void main(String[] args)

int value1 = 1;

int value2 = 2;

if(value1 == value2)

System.out.println("value1 == value2");

if(value1 != value2)

System.out.println("value1 != value2");

if(value1 > value2)

System.out.println("value1 > value2");

if(value1 < value2)

System.out.println("value1 < value2");

if(value1 <= value2)

System.out.println("value1 <= value2");

3. Increment and Decrement operators:

++,--

a++ : post increment : print the value then increment

++a : pre increment : increment the value then print

a-- : post decrement : print the value then decrease

--a : pre decrement : decrease the value then print

31
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Example :-

class Test

public static void main(String[] args)

int a=10;

System.out.println(a++);

System.out.println(++a);

System.out.println(a--);

System.out.println(--a);

Example :

class Test

public static void main(String[] args)

byte b1=-10;

byte b2=+10;

System.out.println(~b1);

System.out.println(~b2);

boolean b=true;

System.out.println(!b);

32
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Example :-

class Test

public static void main(String[] args)

int a=10;

System.out.println(a++ + ++a );

System.out.println(a++ - ++a );

System.out.println(a-- + --a );

System.out.println(a-- - --a );

System.out.println(a++ + ++a + --a + a--);

System.out.println(a++ - ++a - --a - a--);

4.Logical operator:-

&&, ||, !

33
WALYS Life Skills International Pvt. Ltd. Introduction to Java

!(condtion) – If condition true it returns false, if false it returns true.

Ex:

class Test

public static void main(String[] args)

int a=20,b=10,c=30;

System.out.println(a>b && a>c); //false

System.out.println(a>b || a<c); //true

System.out.println(! a<c); //true

5.Bitwise operators:-

&, |, ^,~,<<,>>,>>>

& (AND): If both arguments are true then result is true.

| (OR): if at least one argument is true. Then the result is true.

^ (X-OR): if both are different arguments. Then the result is true.

Ex:

public class Test

public static void main(String []args)

int a=12,b=5;

34
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println(a&b);

System.out.println(a|b);

System.out.println(a^b);

System.out.println(~a);

Logical && bitwise & operator:-

The logical && operator does not check second condition if the first condition
is false. It checks the second condition if the first condition is true.

The bitwise & always checking both conditions if the condition is true or false.

Ex:

class Test

public static void main(String[] args)

int a=10,b=20,c=30;

System.out.println(a>b && a<c); //false

System.out.println(a>b & a<c); //false

Ex:

35
WALYS Life Skills International Pvt. Ltd. Introduction to Java

class Test

public static void main(String[] args)

int a=10,b=20,c=30;

System.out.println(a>b && a++<c);

System.out.println(a);

System.out.println(a>b & a++<c);

System.out.println(a);

Logical || bitwise | operator:-

The logical || operator does not check the second condition if the first condition
true. It will check the second condition if the first condition false.

The bitwise | always checking both conditions if the condition is true or false.

Ex:

class Test

public static void main(String[] args)

int a=10,b=20,c=30;

System.out.println(a<b || a++<c);

System.out.println(a);

36
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println(a<b | a++<c);

System.out.println(a);

Note :

&&,|| are called short circuit operators.

The && and || operators perform Conditional-AND and Conditional-OR


operations on two boolean expressions. These operators exhibit "short-
circuiting" behavior, which means that the second operand is evaluated only if
needed.

shift Operators

Left Shift Operator

The left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.

Example

class OperatorExample

public static void main(String args[])

System.out.println(10<<2);//10*2^2=10*4=40

System.out.println(10<<3);//10*2^3=10*8=80

System.out.println(20<<2);//20*2^2=20*4=80

System.out.println(15<<4);//15*2^4=15*16=240

37
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Right Shift Operator

The right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.

Example

class OperatorExample

public static void main(String args[])

System.out.println(10>>2);//10/2^2=10/4=2

System.out.println(20>>2);//20/2^2=20/4=5

System.out.println(20>>3);//20/2^3=20/8=2

Example: >> vs >>>

class OperatorExample

public static void main(String args[])

//For positive number, >> and >>> works same

System.out.println(20>>2);

System.out.println(20>>>2);

//For negative number, >>> changes parity bit (MSB) to 0

38
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println(-20>>2);

System.out.println(-20>>>2);

Ternary operators : (?,:)

class ConditionalDemo2

public static void main(String[] args)

int value1 = 1;

int value2 = 2;

boolean result = value1>value2? true : false;

System.out.println(result);

Assignment operator :

They are three types of assignment operators.

Simple assignment:

Example: int x=10;

Chained assignment:

Example:

int a,b,c,d;

a=b=c=d=20;

39
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println(a+"---"+b+"---"+c+"---"+d);//20---20---20---20

Compound assignment:

Sometimes we can mix assignment operator with some other operator.

The following is the list of all possible compound assignment operators in java.

a+=5; //a=a+5;

Data types:-
1. Data types are used to represent type of the variable & expressions.
2. Representing how much memory is allocated for variable.
3. Specifies range value of the variable.
Note: Java is strictly a typed programming language.

Except boolean and char, remaining data types are considered as


signed data types. That‟s why we can represent both positive and negative
numbers.

40
WALYS Life Skills International Pvt. Ltd. Introduction to Java

byte: - This data type is suitable for file stream classes. Java file streams are
read and write data in byte form.
Size: 1byte (8bits)
Range:-128to 127[-27 to 27-1]

byte b=127; //valid


byte b=128; //Compile time error: Incompatible types: Possible lossy
conversion from int to byte.
byte b=12.7; // Compile time error: Incompatible types: Possible lossy
conversion from double to byte.
byte b=true; // Compile time error: Incompatible types: Boolean cannot
convert to byte.
byte b=”satish”; // Compile time error: Incompatible types: String cannot
convert to byte.
short: - short data type is best suitable for 16bit processors like 8085. But
these processors are completely outdated and hence corresponding short
data type is also outdated data type.
This is most rarely used data type in Java.
Size: 2 bytes(16 bits)
Range: -215 to 215-1 (-32,768 to 32,767)
Example:
short s=130;
short s=32768;//C.E: Incompatible types: Possible lossy
conversion from int to short.
short s=true;//C.E: Incompatible types: Boolean cannot convert to short.
int: - The most commonly used data type in Java is int.
size: 4bytes(32bits)

41
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Range: -231 to 231-1 (-2147483648 to 2147483647)


Example:
int i=130;
int i=10.5
int i=true;//C.E: Incompatible types: Boolean cannot convert to int.
long: - Sometimes int may not enough to hold huge values then we should go
for long type.
Size: 8bytes
Range: -263 to 263-1
floating point type:- Floating point type numbers are used to hold numbers
containing fractional parts there are two types of floating point types :
float and double.
float: - If we want 5 to 6 decimal places of accuracy then we should go for
float.
Size: 4bytes
Range: -3.4e38 to 3.4e38
double: - If we want 14 to 15 decimal places of accuracy then we should go
for double.
Size: 8bytes
Range: -1.7e308 to 1.7e308
boolean type:- Boolean data type is used when a particular condition is to be
tested during the execution of a program. The Boolean type is used for logical
values. It has only one of the two possible values - true or false. It has only
one byte of storage. All comparison operators return Boolean type values.
True or False known as Tuples.
Note: Tuples are predefined constants which represent only one value.
Size: 1byte
Range: NA
Example 1:
boolean b=true;
boolean b=True;//C.E:cannot find symbol

42
WALYS Life Skills International Pvt. Ltd. Introduction to Java

boolean b="True";//C.E:incompatible types


boolean b=0;//C.E:incompatible types
char:- Char is the data type that is used to store characters in Java. Char in
Java is not the same as char in C or C++. In C/C++, char is an integer type
that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to
represent characters. Unicode defines fully an international character set that
can represent all of the characters found in all human languages. Thus, in
Java char is 16 bit and the range is 0 to 65535.
Ex:- char ch;
ch = „A‟ or ch = 65
UNICODE is one of the character representation, it is universally accepted
code and it able to represent all the alphabet from all the natural languages
like English, Hindi, Marati, chinees, italian,...... and it will provide very good
Internationalization[I18N] support.
Data Type size(in Range default
bytes) values
byte 1 -128 to 127 0
short 2 -32768 to 32767 0
int 4 -2147483648 to 2147483647 0
long 8 –9,223,372,036,854,775,808 to 0
9 ,223,372,036,854,775,807
float 4 -3.4e38 to 3.4e38 0.0
double 8 -1.7e308 to 1.7e308 0.0
char 2 0 to 65535 Space
bool 1 No-range (true or false) false

String: -
String is not a data type & it is a class present in java.lang package to
represent group of characters or character array enclosed with in double
quotes.
The default value of the String is null

43
WALYS Life Skills International Pvt. Ltd. Introduction to Java

For any class type the default value Is null.


String ename="satish";
System.out.println(ename);

44
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println ( );

• This statement is used for displaying the data or messages on to the console
(monitor).

• Here, println is the predefined instance method of print stream class.

• • The object of print stream class is called out is created as a static data
member in system class (system is a predefined class).

• Hence to call the println method we must use the following statement:

System.out.println (“WELCOME TO JAVA”);

print() vs println ():-

print():-This method used to print the data after printing control present in
same line.

println():-This method used to print the data after printing control present in
new line.

Ex:

class Test

public static void main(String[] args)

System.out.print("satish");

System.out.print("lokesh");

System.out.println("rajesh");

System.out.println("gopi");

45
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Escape Sequences:- A character preceded by a backslash (\) is an escape


sequence and has special meaning to the compiler. The following table shows
the Java escape sequences

class Test

public static void main(String[] args)

System.out.println("hi \"satish\" sir");

System.out.println("hi \' satish \' sir");

System.out.println("hi \\ satish \\ sir");

System.out.println("hi\t satish \tsir");

System.out.println("hi\n satish \nsir");

46
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Ex: sum of two numbers

class Sum

public static void main(String[] args)

int a,b;

a=10;

b=20;

int s=a+b;

System.out.println("sum="+s);

//Square root program

public class MathDemo

public static void main(String[] args)

double x = 9;

double y = 25;

System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));

System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));

47
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Ex: Average of three numbers

class Average

public static void main(String[] args)

int a,b,c;

a=20;

b=30;

c=50

float s=(a+b+c)/3;

System.out.println("Average="+s);

Type casting: Type casting is a method for converting one data type to
another data type.

1.Primitive data Types Type Casting


2.User defined Data Types Type Casting
1.Primitive data Types Type Casting:
The process of converting data from one primitive data type to another
primitive data type is called as Primitive data types type casting.

There are two types of primitive data types type castings.


Implicit type casting.
Explicit type casting.

48
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Implicit type casting: -


The process of converting data from lower data type to higher data type is
called as Implicit Type Casting.
To cover all the possibilities of implicit type casting JAVA has provided the
following chart.

Ex:
int x=‟a‟;
System.out.println(x); 97
double d=10;
System.out.println(d); 10.0

EX:
class Test
{
public static void main(String[] args)
{
byte b=10;
byte i=b;
System.out.println(b+" "+i);
}
}
Status: No Compilation Error
10 10

If we compile the above code, when compiler encounter the above


assignment stattement then compiler will check whether right side variable
data type is compatible with left side variable data type or not, if not, compiler
will rise an error like "possible loss of precision". If right side variable data

49
WALYS Life Skills International Pvt. Ltd. Introduction to Java

type is compatible with left side variable data type then compiler will not rise
any error and compiler will not perform any type casting.

When we execute the above code, when JVM encounter the above
assignment statement then JVM will perform the following two actions.
1.JVM will convert right side variable data type to left side variable data type
implicitly [Implicit Type Casting]
2.JVM will copy the value from right side variable to left side variable.
Note: Type Checking is the responsibility of compiler and Type Casting is the
responsibility of JVM.

EX:
class Test
{
public static void main(String[] args)
{
int i=10;
byte b=i;
System.out.println(i+" "+b);
}
}
Status: Compilation Error, Possible loss of precision.

EX:
class Test
{
public static void main(String[] args)
{
byte b1=30;
byte b2=30;
byte b=b1+b2;

50
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println(b);
}
}
Status: Compilation Error, Possible loss of precision.
Reason: X,Y and Z are three primitive data types.
X+Y=Z
1.If X and Y belongs to {byte, short, int} then Z should be int.
2.If either X or Y or both X and Y belongs to {long, float, double} then Z should
be higher(X,Y).

byte+byte=int
byte+short=int
short+int=int
byte+long=long
long+float=float
float+double=double

EX:
class Test
{
public static void main(String[] args)
{
long l=10;
float f=l;
System.out.println(l+" "+f);
}
}
Status: No Compilation Error
OP: 10 10.0

51
WALYS Life Skills International Pvt. Ltd. Introduction to Java

EX:
class Test
{
public static void main(String[] args)
{
float f=22.22f;
long l=f;
System.out.println(f+" "+l);
}
}
Status: Compilation Error, possible loss of precision.
Reason:
two class rooms
Class Room A: 25[Size] banches---> 3 members per bench---> 75
Class Room B: 50[Size] banches---> 1 member per bench----> 50
long---> 8 bytes--> less data as per its internal data arrangement.
float--> 4 bytes--> more data as per its internal data arrangement.
Due to the above reason, float data type is higher when compared with long
data type so that, we are able to assign long variable4 to float variable directly,
but, we are unable to assign float variable to long variable directly.

Explicit Type casting: -

The process of converting data from higher data type to lower data type is
called as Explicit Type Casting.
To perform explicit type casting we have to use the following pattern.
P a = (Q) b;
(Q)----> Cast operator
Where P and Q are two primitive data types, where Q must be either same as
P or lower than P as per implicit type casting chart.

52
WALYS Life Skills International Pvt. Ltd. Introduction to Java

EX:
class Test
{
public static void main(String[] args)
{
int i=10;
byte b=(byte)i;
System.out.println(i+" "+b);
}
}
Status: No Compilation Error
OP: 10 10

When we compile the above code, when compiler encounter the above
assignment statement, compiler will check whether cast operator provided
data type is compatible with left side variable data type or not, if not, compiler
will rise an error like "Possible loss of precision". If cast operator provided data
type is compatible with left side variable data type then compiler will not rise
any error and compiler will not perform type casting.
When we execute the above program, when JVM encounter the above
assignment statement then JVM will perform two actions.
1.JVM will convert right side variable data type to cast operator provided data
type.
2.JVM will copy value from right side variable to left side variable.

Example:

int x=130;

byte b=(byte)x;

System.out.println(b);//-126

53
WALYS Life Skills International Pvt. Ltd. Introduction to Java

Analysis:

Java.util.Scanner(Dynamic Input):-

Scanner class present in java.util package and it is introduced in 1.5


version. Scanner class is used to take dynamic input from the keyboard.

Scanner s = new Scanner(System.in);

to get int value ----> s.nextInt()

to get float value ---> s.nextFloat()

to get byte value ---> s.nextByte()

to get String value ---> s.next()

to get single line ---> s.nextLine()

to close the input stream ---> s.close()

//Sum of two numbers

import java.util.*;

class Sum

54
WALYS Life Skills International Pvt. Ltd. Introduction to Java

public static void main(String[] args)

Scanner s=new Scanner(System.in);

int a,b;

System.out.println(“Enter two numbers:”);

a=s.nextInt();

b=s.nextInt();

int s=a+b;

System.out.println("sum="+s);

Ex:

import java.util.*;

class Test

public static void main(String[] args)

Scanner s=new Scanner(System.in);

//used to take dynamic input from keyboard

System.out.println("enter emp hobbies");

String ehobbies = s.nextLine();

System.out.println("enter emp no");

int eno=s.nextInt();

55
WALYS Life Skills International Pvt. Ltd. Introduction to Java

System.out.println("enter emp name");

String ename=s.next();

System.out.println("enter emp salary");

float esal=s.nextFloat();

System.out.println("*****emp details*****");

System.out.println("emp no----->"+eno);

System.out.println("emp name---->"+ename);

System.out.println("emp sal------>"+esal);

System.out.println("emp hobbies------>"+ehobbies);

s.close(); //used to close the stream

56

You might also like