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

Java Unit 1 Final

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

Java Unit 1 Final

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

1

Course Objectives:
To understand the structure and environment of Java.
To implement the relationship between objects.
To apply data hiding strategy in objects.
To implement text processing and error handling.
To organize data using different data structures.
To create multi threaded graphical user interface applications.
Course Outcomes:
1. Understand the environment of JRE and Control Statements.
2. Implement real world objects using class Hierarchy.
3. Implement generic data structures for iterating distinct objects.
4. Implement error handling through exceptions and file handling through streams.
5. Design thread-safe GUI applications for data communication between objects.

Unit I: Java Environment and Program Structure


History of Java, Features, Applications, Java Installation - JDK and JRE, JVM
Architecture, OOPS Principles, Class and Object, Naming Convention, Data Types,
Type Casting, Type Conversion, Wrapper classes, Operators, instance of operator,
Command Line Arguments, Decision making, Arrays, and Looping statements.

Learning Outcomes: Student will be able to


1. Understand architecture of Java Virtual Machine.(L2)
2. Understand the structure of java program and its environment. (L2)

Unit II: Class Hierarchy & Data Hiding


Property, Method, Constructor, Inheritance (IS-A) , Aggregation and Composition
(HAS-A), this and super, static and initialize blocks, Method overloading and
overriding, static and final keywords, Types of Inheritance, Compile time and
Runtime Polymorphism, Access Specifiers and scope, packages and access modifiers,
Abstract class, Interface, Interface Inheritance, Achieving Multiple Inheritance, Class
casting, Object Cloning, Inner Classes.
Learning Outcomes: Student will be able to
1. Understand the class hierarchy and their scope. (L2)
2. Implement relationship between objects. (L3)
3. Understand data hiding and nested classes. (L2)
4. Implement data type casting and cloning of objects. (L3)
Unit III: Strings and Collections
String: Methods, StringBuffer and StringBuilder, StringTokenizer,
Collections: Exploring java.util.*, Scanner, Iterable, Collection Hierarchy, Set, List,
Queue and Map, Comparable and Comparator, Iterators: foreach, Enumeration,
Iterator and ListIterator.
Learning Outcomes: Student will be able to
1. Understand the usage of String and its properties and methods.(L2)
2. Understand data structures and Iterators. (L2)
3. Create the data structures and implement different utility classes. (L3)
Unit IV: IO and Error Handling
2

IO Streams: Exploring java.io.*, Character and Byte Streams, Reading and Writing,
Serialization and De-serialization,
Error Handling: Error vs Exception, Exception hierarchy, Types of Exception,
Exception handlers, User defined exception, Exception propagation.
Learning Outcomes: Student will be able to
1. Understand character and byte streams. (L2)
2. Understand the hierarchy of errors and exceptions. (L2)
3. Implement data streams and exception handlers. (L3)
Unit V: Threads and GUI
Multi Threading: Process vs Thread, Thread Life Cycle, Thread class and Runnable
Interface, Thread synchronization and communication.
GUI: Component, Container, Applet, Applet Life Cycle, Event delegation model,
Layouts, Menu, MenuBar, MenuItem.
Learning Outcomes: Student will be able to
1. Understand the Thread Life Cycle and its scheduling.(L2)
2. Implement the synchronization of threads. (L2)
3. Create graphical components using Abstract window toolkit. (L3)
TEXT BOOKS:
1. The complete Reference Java, 8th edition, Herbert Schildt, TMH.
2. Programming in JAVA, Sachin Malhotra, SaurabhChoudary, Oxford.
3. Introduction to java programming, 7th edition by Y Daniel Liang, Pearson.
4. Java: How to Program, 9th Edition (Deitel) 9th Edition.
5. Core Java: An Integrated Approach, Java 8 by R. Nageswara Rao.
REFERENCE BOOKS:
1. Swing: Introduction, JFrame, JApplet, JPanel, Componets in Swings, Layout
Managers in
2. Swings, JList and JScrollPane, Split Pane, JTabbedPane, JTree, JTable, Dialog
Box.

Unit I: Java Environment and Program Structure


History of Java, Features, Applications, Java Installation - JDK and JRE, JVM
Architecture, OOPS Principles, Class and Object, Naming Convention, Data Types,
Type Casting, Type Conversion, Wrapper classes, Operators, instance of operator,
Command Line Arguments, Decision making, Arrays, and Looping statements.
Learning Outcomes: Student will be able to
1. Understand architecture of Java Virtual Machine.(L2)
3

2. Understand the structure of java program and its environment. (L2)

History of Java :

 Java was invented by James Gosling along with his colleagues Mike Sheridan and
Patrick Naughton.The original name for Java programming language is OAK, a tree
outside of the office of James Gosling. (The project named as Green Project) and
later it changed as Java .
 JAVA got its name from an Island Java which is part of Indonesia. SUN
MicroSystems is the office where Java was developed and invented.
 JAVA 1.0 : was released to the public in the year 1996 though its initial developer
version was completed in 1995 itself. It took 4 years to get to the Java 1.0 version
from scratch.
 INTENTION : Java was developed with an intention of operating various electronic
equipment like Set Top Boxes, Televisions (TV)& and other embedded systems.
 Why it is Popular: But surprisingly Java became famous with the advent of the World
Wide Web.
 Platform dependence and security : People started using the Internet on various
computer systems with different Hardware and Operating Systems. So there was a
necessity to develop software that works platform independent. Also security was a
very big concern as EXE files easily catch and transmit Viruses and Trojans. Java
language came to rescue overcoming these platform dependence and security
concerns.
Types of java software distributions:
1. Java SE (Java Standard Edition) - GUI application, Networking,Client Side Apps
2. Java EE (Java Enterprise Edition) - Servlets and JSP for web development,Server
Side Apps
3. Java ME (Java Micro Edition) - For less powerful devices like PDAs, Printers and
Embedded Systems, mobile or wireless application by making use of a predefined
protocol called WAP(wireless Access / Application protocol).
4. JavaFX (Java EFFECTS) is a Java library that is used to develop Desktop
applications as well as Rich Internet Applications (RIA). The applications built
in JavaFX, can run on multiple platforms including Web, Mobile and Desktops.
Initially named as F3(Form Follow Function)
4

Java Product Version Numbers :


Any java version staring with number 1. (ONE POINT) is called internal version
number and the other version number is called product version number.
Starting form java 1.6 or java 6, J2SE (java 2 standard edition) is called as java SE.
The "2" was originally intended to emphasize the major changes introduced in 1.2
JDK Alpha and Beta (1995)
JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)

J2SE5 JAVA6 JAVA67 JAVA16

JAVA SE17 (September 2021) JAVA SE18 (2022)


JAVA Features or BUZZ words :

1. Simple: Java is easy to learn and its syntax is quite simple, clean and easy to
understand.
The confusing and ambiguous concepts of C++ are either left out in Java
5

Eg : Pointers and Operator Overloading are not there in java but were an important
part of C++.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2.Object Oriented: In java, everything is an object which has some data and
behaviour. Java can be easily extended as it is based on Object Model.
3. Platform Independent : Unlike other programming languages such as C, C++ etc
which are compiled into platform specific machines. Java is guaranteed to be write-
once, run-anywhere language(WORA).On compilation Java program is compiled into
bytecode. This bytecode is platform independent and can be run on any machine, plus
this bytecode format also provide security. Any machine with Java Runtime
Environment can run Java Programs.

• 4. Secured: No Explicit pointers in JAVA.With java secure features it enable us to


develop virus free, temper free system. Java program always runs in Java runtime
environment(JRE) with almost null interaction with system OS, hence it is more
secure

• The original security model provided by the Java platform is known as the sandbox
model, which existed in order to provide a very restricted environment in which to run
untrusted code obtained from the open network. The essence of the sandbox model is
that local code is trusted to have full access to vital system resources (such as the file
system) while downloaded remote code (an applet) is not trusted and can access only
the limited resources provided inside the sandbox.
• Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
• Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
6

• Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.
5.Robust:Java makes an effort to eliminate error prone codes by emphasizing mainly
on compile time error checking and runtime checking. But the main areas which Java
improved were Memory Management and mishandled Exceptions by introducing
automatic Garbage Collector and Exception Handling.
6.Architecture-neutral: Java is architecture neutral because there are no
implementation dependent features, for example, the size of primitive types is fixed.In
C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
7. Portable : Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation or changes.
8. Intepreted & High-performance : Java is faster than other traditional interpreted
programming languages because Java bytecode is "close" to native code. It is still a
little bit slower than a compiled language (e.g., C++). Java is an interpreted language
that is why it is slower than compiled languages, e.g., C, C++, etc.
9. Distributed :Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any machine
on the internet.
10. Multi-threaded: A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.
11. Dynamic : Java is a dynamic language. It supports dynamic loading of classes.
It means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

JAVA Applications :
7

1. Desktop GUI Applications:


Desktop applications can be easily developed using Java. We use APIs like
AWT, Swing, JavaFX to build these applications.
JavaFX is a modern way to develop a desktop application in Java, it is graph-based
and totally different from AWT and Swings.
Examples of desktop GUI applications are Acrobat Reader, ThinkFree, Media
Player, Antiviruses, etc.
2. Mobile Applications: A mobile application is an application created for
mobile phones and tablets. In today’s era, the majority of phones and smart devices
have Android OS and Android development is not possible without Java. Java

Micro Edition (Java ME or J2ME) is a popular cross-platform framework that is used


to build applications that run across all feature phones and smartphones.

Examples of mobile applications are Photo and video gallery apps, Simple Calendar,
Netflix, Tinder, QRReader, Google Earth, Uber, etc.
3. Enterprise Applications: An enterprise application is a large software
system which operates in a corporate environment, to satisfy the needs of an
organization, rather than of individual users.
Examples of enterprise applications are Business corporations, schools, banks, ERP
(Enterprise Resource Planning) and CRM (Customer Resource Management)
systems, clubs, charities, governments, interest-based user groups, etc.
4. Scientific Applications: A scientific application is an application that affects real-
world activities using mathematics. Java supports the development of scientific
applications, because of its powerful features.
Examples of scientific applications are applications related to research, science,
medical science, space, aeronautics, etc.
5. Web-based Applications: A web application is a client-server program that is
delivered on the Internet through a browser interface.Examples of web-based
applications are irctc.co.in, online forms, shopping carts, Gmail, Google Sheets,
Google Slides and many more.
6. Embedded Systems: An embedded system, also known as an integrated system, is
a combination of many small computing units that assemble together to perform
dedicated functions for the larger system
For example, a motor system, entertainment and multimedia in a car, E-commerce,
wireless communication, mobile computing and networking use an embedded
system.And also smart cards or sensors, SIM,BlueRay Disc etc(SIM (Subscriber
Identity Module) cards in our phones have been running a variant of the JVM (Java
Card) for nearly 20 years.BlueRay Disc players, utility meters and televisions use
Java technology)
7. Big Data Technologies: The term big data is defined as “extremely large and
complex datasets that may be analyzed to extract patterns, trends, and useful
information For example, Apache’s Java-based HBase and Accumulo (open
source), and ElasticSearch as well.
8. Distributed Applications: A distributed application is an application or software
that executes or runs on multiple computers within a network.RMI (Remote
Procedure Invocation) and CORBA (Common Object Request Broker
Architecture) are the APIs to develop distributed applications.
The Jini (Java Intelligent Networking Infrastructure) gives an infrastructure to
provide, register, and find distributed services based on its specifications. An essential
8

part of Jini is JavaSpaces, that supports distribution, persistence, and migration of


objects in a distributed environment.
9. Cloud-based Applications: Cloud computing means on-demand delivery of
IT resources via the Internet, including storage, servers, databases, networking, and
software with a pay-as-you-go pricing model
Java provides us with features that can help us build applications used in SaaS
(Software-as-a-service), IaaS (Infrastructure-as-a-service) and PaaS (Platform-as-a-
service) development.For example, Oracle Java cloud service provides a platform to
develop and configure the Oracle servers.
10. Web Servers and Application Servers
A web server is a computer program that uses HTTP (Hypertext Transfer Protocol)
and other protocols, to store, process, and respond to client requests made over WWW
(World Wide Web)
example servers:• Java provides web servers including Apache Tomcat, Simple,
Jo!, Rimfaxe Web Server (RWS) Apache HTTP server, Resin, Adobe JRun, and
Project Jigsaw.WebLogic, GlassFish, WildFly, WebSphere, and JBoss EAP occupy
commercial application server space
11. Software Tools: A software tool is a set of computer programs that developers
use to develop, analyze, maintain, debug, or support other applications and programs.
Many developers use Java to write and develop useful software tools.
Examples of software tools are Eclipse, IntelliJ Idea, and NetBeans IDE.
12. Gaming Applications : Java proves to be one of the best platforms for
developing 2-Dimensional games.
. Android games cannot be built without Java. Java supports jMonkeyEngine which is
the most powerful open-source 3D-Engine and has the capacity to design 3-
Dimensional games.
Android games use Java as a primary language because Java supports the Dalvik
Virtual Machine (DVM) which is specially designed to run on the Android platform.

JAVA Installation (JDK and JRE) :


Download and install JAVA :
Step 1: Download JDK
(a)Goto JDK (or Java SE) download site @
https://www.oracle.com/java/technologies/javase-downloads.html.
(b)Under "Oracle JDK", click "JDK Download".
Download the "Windows x64 Installer" (e.g., "jdk-15.0.{x}_windows-x64_bin.exe" -
about 159MB), where {x} is a fast changing update number.
Step 2: Install JDK
Run the downloaded installer. Accept the defaults and follow the screen instructions
to complete the installation. By default, JDK is installed in directory " C:\Program
Files (x86)\Java”
Step 3 : Install JRE
By default installer will prompt for JRE
Repeat the same steps for step2 and it will choose the directory " C:\Program Files
(x86)\Java” for JRE installation.
Step 4 : Now you can see both JDK and JRE installations in the JAVA directory
C:\Program Files (x86)\Java\jdk1.8.0_92
C:\Program Files (x86)\Java\jre1.8.0_281
9

How to set path in Java :


Why do we need to set PATH?
The path is required to be set for using tools such as javac, java, etc.
How to set the path of JDK in Windows OS:
(i) Setting Temporary Path of JDK
(ii) Setting Permanent Path of JDK
How to set the path of JDK in WINDWOS/Linux OS
(Note: If you are saving the Java source file inside the JDK/bin directory, the path is
not required to be set because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set
the path of JDK.)
i) How to set the Temporary Path of JDK in Windows :
To set the temporary path of JDK, you need to follow the following steps:
 Open the command prompt
Copy the path of the JDK/bin as
C:\Program Files (x86)\Java\jdk1.8.0_92\bin
 Write in command prompt: set path=copied_path
For Example:
set path= C:\Program Files (x86)\Java\jdk1.8.0_92\bin
ii) How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:
Go to My Computer properties -> advanced tab -> environment variables -> new tab
of system variable -> write path in variable name -> write path of bin folder in
variable value -> ok -> ok -> ok as follows
10

Click on Environment Variables Tab will display as follows

Click on the Path under System variables

Click on new add the JDK/BIN path as C:\Program Files (x86)\Java\jdk1.8.0_92\bin


Click OK – OK – OK to close the advanced System properties TAB
11

What is CLASSPATH:- CLASSPATH: CLASSPATH is an environment variable which is


used by Application ClassLoader to locate and load the .class files. The CLASSPATH
defines the path, to find third-party and user-defined classes that are not extensions or part of
Java platform. Include all the directories which contain .class files and JAR files when setting
the CLASSPATH.

You need to set the CLASSPATH:


If You need to load a class that is not present in the current directory or any sub-directories.

How to Set CLASSPATH in Windows :


(i)In the environment variables: Similar to the PATH Settings
name=CLASSPATH
value=C:\Program Files\Java\jre1.8\rt.jar;
(ii)In the command prompt
set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;
12

JDK and JRE Environment

Sequence flow of source file to execution :

JVM ARCHITECTURE
13

More elaborated diagram of JVM


14

JVM Architecture:
JVM (Java Virtual Machine) Architecture
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).
JVM is
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
What JVM does: The JVM performs following operation:
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 Internal Architecture

1) Classloader:-
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like
java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the classfiles from classpath. By default, classpath is set to current directory. You can
change the classpath using "-cp" or "-classpath" switch. It is also known as Application
classloader.
15

2) Class(Method) Area
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(instance variables) 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 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 contains:
A virtual processor Interpreter: Read bytecode stream then execute the instructions.
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.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.

What are OOP concepts in Java?


OOP concepts allow us to create specific interactions between Java objects. They make it
possible to reuse code without creating security risks or making a Java program less readable.
Abstraction
Abstraction aims to hide complexity from the users and show them only the relevant
information. For example, if you want to drive a car, you don’t need to know about its
internal workings. The same is true of Java classes. You can hide internal implementation
details by using abstract classes or interfaces. On the abstract level, you only need to define
the method signatures (name and parameter list) and let each class implement them in their
own way.
Abstraction in Java:
 Hides the underlying complexity of data
 Helps avoid repetitive code
 Presents only the signature of internal functionality
 Gives flexibility to programmers to change the implementation of the abstract
behavior
 Partial abstraction (0-100%) can be achieved with abstract classes
 Total abstraction (100%) can be achieved with interfaces
Encapsulation
Encapsulation allows us to protect the data stored in a class from system-wide access. As its
name suggests, it safeguards the internal contents of a class like a real-life capsule. You can
implement encapsulation in Java by keeping the fields (class variables) private and providing
16

public getter and setter methods to each of them. Java Beans are examples of fully
encapsulated classes.
Encapsulation in Java:
 Restricts direct access to data members (fields) of a class.
 Fields are set to private
 Each field has a getter and setter method
 Getter methods return the field
 Setter methods let us change the value of the field
Polymorphism
Polymorphism refers to the ability to perform a certain action in different ways. In Java,
polymorphism can take two forms: method overloading and method overriding. Method
overloading happens when various methods with the same name are present in a class. When
they are called they are differentiated by the number, order, and types of their parameters.
Method overriding occurs when the child class overrides a method of its parent.

Polymorphism in Java:
 The same method name is used several times.
 Different methods of the same name can be called from the object.
 All Java objects can be considered polymorphic (at the minimum, they are of their
own type and instances of the Object class).
 Example of static polymorphism in Java is method overloading.
 Example of dynamic polymorphism in Java is method overriding.
Inheritance
Inheritance makes it possible to create a child class that inherits the fields and methods of the
parent class. The child class can override the values and methods of the parent class, however
it’s not necessary. It can also add new data and functionality to its parent. Parent classes are
also called super classes or base classes, while child classes are known as subclasses or
derived classes as well. Java uses the extends keyword to implement the principle of
inheritance in code.
Inheritance in Java:
 A class (child class) can extend another class (parent class) by inheriting its features.
 Implements the DRY (Don’t Repeat Yourself) programming principle.
 Improves code reusability.
 Multilevel inheritance is allowed in Java (a child class can have its own child class as
well).
 Multiple inheritances are not allowed in Java (a class can’t extend more than one
class).
Association
Besides the four main principles of OOP, Java also works with three further concepts
(association, aggregation, composition) you can make use of when designing your programs.
Aggregation is a special form of association, while composition is a special form of
aggregation.
Association simply means the act of establishing a relationship between two unrelated
classes. For example, when you declare two fields of different types (e.g. Car and Bicycle)
within the same class and make them interact with each other, you have performed
association.
Association in Java:
 Two separate classes are associated through their objects.
 The two classes are unrelated, each can exist without the other one.
 Can be a one-to-one, one-to-many, many-to-one, or many-to-many relationship.
17

Aggregation
Aggregation is a narrower kind of association. It occurs when there’s a one-way (HAS-A)
relationship between the two classes you associate through their objects. For example, every
Passenger has a Car but a Car doesn’t necessarily have a Passenger. When you declare the
Passenger class, you can create a field of the Car type that shows which car the passenger
belongs to. Then, when you instantiate a new Passenger object, you can access the data stored
in the related Car as well.

Aggregation in Java:
 One-directional association.
 Represents a HAS-A relationship between two classes.
 Only one class is dependent on the other.
Composition
Compositionis a stricter form of aggregation. It occurs when the two classes you associate are
mutually dependent on each other and can’t exist without each other. For example, take a Car
and an Engine class. A Car cannot run without an Engine, while an Engine also can’t function
without being built into a Car. This kind of relationship between objects is also called a
PART-OF relationship.
Composition in Java:
 A restricted form of aggregation
 Represents a PART-OF relationship between two classes
 Both classes are dependent on each other
 If one class ceases to exist, the other can’t survive alone.

Structure of java program:-


18

What is public static void main(String[] args) :

JAVA INPUT-OUTPUT STATEMENTS :-

System.in: This is the standard input stream that is used to read characters from the keyboard
or any other standard input device.
System.out: This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.
print(): This method in Java is used to display a text on the console. This text is passed as the
parameter to this method in the form of String. This method prints the text on the console and
the cursor remains at the end of the text at the console. The next printing takes place from just
here.
Syntax: System.out.print(parameter);

Simple JAVA Program


public class Cseb {
public static void main(String[] args) {
System.out.println(“welcome");
}
}
properties of Java program:
public class Cseb. All Java programs are collections of Java classes.
public static void main(String[] args). This is the standard main method, which
indicates where the execution of the program should start.System is a predefined Java
class.System.out is an object that is an instance of the predefined class PrintStream. This
object is defined in the class System and its purpose is to handle the system output of the
program (e.g., monitor output).println(...) is a method (operation) that is supported for the
objects of type PrintStream (it is a property of the class PrintStream).System.out.println("...")
is a call of the method println("...") on the invocation object System.out, and it has "..." as
parameter.
public static final PrintStream out: This is the standard output stream in Java programming.
This stream is already open and available for accepting the output data. This output stream
mainly corresponds to displaying the output or another output destination that is specified by
the host environment or a user.

JAVA OUTPUT STATEMENTS:


print(),println()
printf()
INPUT STATEMENTS/COMMANDS
Scanner(), COMMAND LINE ARGUMENTS – INPUT STATEMENTS
19

import java.util.Scanner; // Import the Scanner class


class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}

JAVA OUTPUT STATEMENTS:


printf() :

The method is part of the java.io.PrintStream class and provides String formatting similar to
the printf() function in C.
2. Syntax: We can use one of these PrintStream methods to format the output:
(i)System.out.printf(format, arguments);
(ii)System.out.printf(locale, format, arguments); //The locale() method returns this scanner's
locale.
We specify the formatting rules using the format parameter. Rules start with the % character.
System.out.printf("Hello %s!%n", "World");
This produces the following output: Hello World!
Format Rules:It consists of literals and format specifiers. Format specifiers include flags,
width, precision, and conversion characters in this sequence:
%[flags][width][.precision]conversion-character
Specifiers in the brackets are optional.
2.2. Conversion Characters:The conversion-character is required and determines how the
argument is formatted.
Conversion characters are only valid for certain data types. Here are some common ones:
s formats strings. d formats decimal integers. f formats floating-point numbers. t
formats date/time values.

What Are Objects?


An object is an entity that has states and behaviors.

For example, dog, cat, and vehicle. To illustrate, a dog has states like age, color, name, and
behaviors like eating, sleeping, and running.
State tells us how the object looks or what properties it has.
Behavior tells us what the object does.
We can actually represent a real world dog in a program as a software object by defining its
states and behaviors.

Software objects are the actual representation of real world objects. Memory is allocated in
RAM whenever creating a logical object.
An object is also referred to an instance of a class. Instantiating a class means the same thing
as creating an object.
20

(The important thing to remember when creating an object is: the reference type should be
the same type or a super type of the object type)

What Are Classes?


A class is a template or blueprint from which objects are created.
Classes define states as instance variables and behaviors as instance methods.
Instance variables are also known as member variables. Classes don't consume any space.

Java Naming Conventions:


Camel case in Java Programming : It consists of compound words or phrases such that each
word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all
with capital.

Classes and Interfaces :


Class names should be nouns, in mixed case with the first letter of each internal word
capitalised. Interfaces name should also be capitalised just like class names.
Use whole words and must avoid acronyms and abbreviations.
Examples:

interface Bicycle
class MountainBike implements Bicyle

interface Sport
class Football implements Sport
Methods :
Methods should be verbs, in mixed case with the first letter lowercase and with the first letter
of each internal word capitalised.
Examples:

void changeGear(int newValue);


void speedUp(int increment);
Variables : Variable names should be short.
Variables can also start with either underscore(‘_’) or dollar sign ‘$’ characters.
Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
One-character variable names should be avoided except for temporary variables.
Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for
characters.
Examples:

// variables for MountainBike class


int speed = 0;
int gear = 1;
Constant variables:
Should be all uppercase with words separated by underscores (“_”).
There are various constants used in predefined classes like Float, Long, String etc.
Examples:

static final int MIN_WIDTH = 4;

// Some Constant variables used in predefined Float class


21

public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

Packages:
The prefix of a unique package name is always written in all-lowercase ASCII letters and
should be one of the top-level domain names, like com, edu, gov, mil, net, org.
Subsequent components of the package name vary according to an organisation’s own
internal naming conventions.
Examples:
com.sun.eng
com.apple.quicktime.v2

// java.lang packet in JDK


java.lang

LEXICAL ISSUES:-
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Tokens: Smallest element /unit in the program. They are identifiers, literals, operators,
separators, and keywords
(1) Whitespace : Java is a free-form language. This means that you do not need to follow
any special indentation rules. For instance, the Example program could have been written all
on one line or in any other strange way you felt like typing it, as long as there was at least one
whitespace character between each token that was not already delineated by an operator or
separator. In Java, whitespace is a space, tab, or newline used to separate tokens
(2) Comments:
(i)Single-line comments start with two forward slashes (//).
(ii)Multi-line comments start with /* write any number of lines */.
(iii) Documentation Comments:
/** author Prakash
*/

(3) LITERALS : Any constant value which can be assigned to the variable is called
as literal/constant.
// Here 100 is a constant/literal. int x = 100;.
22

(4)Identifiers:
Identifiers in Java:
All Java components require names. Name used for classes, methods, interfaces, and
variables are called identifiers. It allows a programmer to refer to the item from other places
in the program. There are some reserved words in Java, which we can’t use as identifiers.
For example int age; Here, age is a variable (an identifier). You cannot use the keyword as a
variable name because keywords have predefined meanings. For example int double; This
code is wrong because double is a keyword and you cannot use it as a variable.

List of some valid identifiers in Java


MyVariable
myvariable
x
I
my_Variable
_myvariable
$myvariable
List of some invalid identifiers in Java
My Variable (it contains a space)
123gkk (it begins with numbers)
a+c (plus sign is not an alphanumeric character)
variable-2 (the hyphen is not allowed)
sum_&_difference (ampersand is not an alphanumeric character)
O’Reilly (the apostrophe is not an alphanumeric character)
Rules for defining an Identifier in Java:
The only allowed characters in java identifiers are a to z, A to Z, 0 to 9, $ and _(Underscore).
If we are using any other character then we will get a compilation error.
Identifiers can’t start with digit i.e., 123name is not valid.
Java identifiers are case sensitive of course java language itself considered as case sensitive
programming language. i.e., name, Name, NAME both are different variable names.
There is no length limit for java identifiers but it is not recommended to take too length
identifiers.
We can’t use reserved words as identifiers otherwise we will get a compilation error. i.e., int
if = 20; here we will get compilation error.
Note:- All predefined java class names and interface names we can use as identifiers. i.e., int
String = 20; here we won’t get any compilation error.
23

5.OPERATORS:-

6.SEPERATORS in JAVA: Separators help define the structure of a program. The


separators used in HelloWorld are parentheses, ( ), braces, { }, the period, ., and the
semicolon, ;. The table lists the six Java separators (nine if you count opening and closing
separators as two). Following are the some characters which are generally used as the
separators in Java.

Reserved Words in Java:


24

The Reserved Words in Java are pre-defined for some special purpose and you cannot create
a variable, class name, or method name with these names. It is used to represent functionality
in programs. They can be briefly categorized into two parts: keywords(50) and literals(3).

Data Types in JAVA:


The Data Types in Java is basically used to store the data temporarily in the computer
through a program.
Classification of Java Data Types:
The Data Types in Java specifies the size and type of values that can be stored in an
identifier. The Java language is rich in its data types. Data types in Java are classified into
two types:
Primitive Types: Examples: Integer, Character, Boolean, and Floating Point.
25

Non-primitive Types: Examples: Classes, Interfaces, and Arrays.

Type Conversion and Type Casting:

1.Typing casting : is the process of conversion of one data type to another datatype by the
programmer using the casting operator during the program design
2. Type conversion :a data type is automatically converted into another data type by a
compiler at the compiler time
26

Mainly there are two types of conversion. They are


(a)Wide Conversion
(b) Narrow Conversion.

(a)Wider Conversion
This is the type of conversion that is done implicitly by Java itself. This means assigning a
value in a variable which has a shorter range respectively, to a variable which has a larger
range respectively.
Ex: Assigning an integer value to a double.
Assigning a byte value to a short.

Note:- These kind of assignments are always legal and no need to convert explicitly.

class Demo{
public static void main(String args[]){
//wider conversion
byte b=100;

double d;
d=b;
System.out.println(b+" "+d);
}
}

Narrow Conversion
What is narrow conversion? Simply the opposite of wider conversion. This means assigning a
value in a variable which has a larger range respectively, to a variable which has a shorter
range respectively.
Ex: Assigning a double value to a integer.
Assigning a short value to a byte.
class Demo{
public static void main(String args[]){
int x=30;
float y;
y=x; // y==30.000000 Not recommended/executed
}
}
27

Type Casting example –


In typing casting, a data type is converted into another data type by the programmer using the
casting operator during the program design. In typing casting, the destination data type may
be smaller than the source data type when converting the data type to another data type, that’s
why it is also called narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;

(): is a casting operator.


target_datatype: is a data type in which we want to convert the source data type.
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data type into byte(target) data
type.
28

CLASS and OBJECT :


Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.
public class Dog {
String breed;
int age;
String color;
void barking() { }
void hungry() { }
void sleeping() { }
}
A class can contain any of the following variable types.

Local variables − Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
29

Instance variables − Instance variables are variables within a class but outside any method.
These variables are initialized when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.

Class variables − Class variables are variables declared within a class, outside any method,
with the static keyword.

Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

Declaration − A variable declaration with a variable name with an object type.

Instantiation − The 'new' keyword is used to create the object.


Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.
Following is an example of creating an object −
Example
Live Demo
public class Puppy {
public Puppy(String name) {
System.out.println("Passed Name is :" + name );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it will produce the following result −
Output
Passed Name is :tommy
30

Java Packages :-

Wrapper Classes :-
wrapper classes are objects encapsulating primitive Java types.
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
31

Wrapper class Example: Primitive to Wrapper

Autoboxing :-

The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20; //Primitive int
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}
Output:
20 20 20

Unboxing :-
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive

//Java program to convert object into primitives


//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to Primitive int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}
Output:
333
32

Instance of :-
An instanceof in Java is a comparison operator which, given an object instance, checks
whether that instance is of a specified type (class/sub-class/interface) or not. Just like other
comparison operators, it returns true or false.

Comparing any object instance with a null type through instanceof operator returns a false.

class Simple{
public static void main(String args[]){
String str1 = "Educative!";

if (str1 instanceof String)


System.out.println("str1 is instance of String");
else
System.out.println("str1 is NOT instance of String");
}
}

Java Command Line Arguments:-


The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be
used as an input.
class Test{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
c:\>javac Test.java
c:\>java Test LENDI
33

Control structures in Java


A program is a list of instructions or blocks of instructions. Java provides Control structures
that can change the path of execution and control the execution of instructions.
Here is the table content of the article will we will cover this topic.
1. Three kinds of control structures in Java?
i) if statement
ii) nested if statement
iii) if-else statement
iv) if-else if statement/ ladder if statements
v)switch statement
2. Control statements/Conditional Branches?
3. Loops in Java?
4. Branching Statements in Java?

Three kinds of control structures in Java


1. Control statements/Conditional Branches
These are used to choose the path for execution. There are some types of control statements:

if statement: It is a simple decision-making statement. It is used to decide whether the


statement or block of statements will be executed or not. Block of statements will be executed
if the given condition is true otherwise the block of the statement will be skipped. For more
details.
nested if statement: Nested if statements mean an if statement inside an if statement. The
inner block of if statement will be executed only if the outer block condition is true. For more
details.
if-else statement: In if statement the block of statements will be executed if the given
condition is true otherwise block of the statement will be skipped. But we also want to
execute the same block of code if the condition is false. Here we come on the if-else
statement. An if-else statement, there are two blocks one is if block and another is else
blocked. If a certain condition is true, then if block will be executed otherwise else block will
be executed.
if..else
if (condition)
{ // codes in if block}
else {
// codes in else block
}

if-else if statement/ ladder if statements: If we want to execute the different codes based on
different conditions then we can use if-else-if. It is also known as if-else if ladder. This
statement is always be executed from the top down. During the execution of conditions if any
condition founds true, then the statement associated with that if it is executed, and the rest of
the code will be skipped. If none of the conditions is true, then the final else statement will be
executed.
if..else ladder
if (condition1) {
// codes
}
else if(condition2) {
34

// codes
}
else if (condition3) {
// codes}
..
else {
// codes
}

Switch statement: The switch statement is like the if-else-if ladder statement. To reduce the
code complexity of the if-else-if ladder switch statement comes.
In a switch, the statement executes one statement from multiple statements based on
condition. In the switch statements, we have a number of choices and we can perform a
different task for each choice
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
2. Loops in Java
These are used to iterate the instruction for multiple times.

for loop: If a user wants to execute the block of code several times. It means the number of
iterations is fixed. JAVA provides a concise way of writing the loop structure. For more
details.
Simple for loop:
1. for(initialization;condition;incr/decr){
2. //statement or code to be executed
3. }
For each :
For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than
using an indexed array element.

 It’s commonly used to iterate over an array or a Collections class (eg,


ArrayList)
35

Syntax:
for (type var : array)
{
statements using var;
}

while loop: A while loop allows code to be executed repeatedly until a condition is satisfied.
If the number of iterations is not fixed, it is recommended to use a while loop. It is also
known as an entry control loop.
while (condition) {
// code block to be executed
}
do-while loop: It is like while loop with the only difference that it checks for the condition
after the execution of the body of the loop. It is also known as Exit Control Loop.
do{
//code to be executed
}while(condition);

3. Branching Statements in Java


These are used to alter the flow of control in loops.

break: If a break statement is encountered inside a loop, the loop is immediately terminated,
and the control of the program goes to the next statement following the loop. It is used along
with if statement in loops. If the condition is true, then the break statement terminates the
loop immediately.
36

Labelled break:
Labeled break used to terminate loops according to the specified labels

continue: The continue statement is used in a loop control structure. If you want to skip some
code and need to jump to the next iteration of the loop immediately. Then you can use a
continue statement. It can be used for loop or while loop.
Syntax: continue;

Return :A return statement causes the program control to transfer back to the caller of a
method. Every method in Java is declared with a return type and it is mandatory for
all java methods. A return type may be a primitive type like int, float, double, a reference
type or void type(returns nothing)
37

Arrays:- An Array is a collection of similar data types.

Here are the unique qualities of arrays in Java that differ from other languages you may use,
like C or C++.

 Arrays are dynamically allocated


 Arrays are objects in Java
 A Java array variable is declared like other variables
 The variables are ordered, with the index beginning at 0
 The superclass of the array type is Object
 The size of an array is specified with an int value

Types of Arrays
One-dimensional Array. Also known as a linear array, the elements are stored in a single row.
Multi-dimensional Array. This is a combination of two or more arrays or nested arrays.
One Dimensional Array:
• int intArray[]; //declaring array
• Array = new int[20]; // allocating memory to array
• OR
• int[] intArray = new int[20]; // combining both statements in one
• int[] intArray = { 1,2,3,4,5,6,7,8,9,10 };

Multi-dimensional Array:
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column


38

2 Dimensional Arrays :

Multi Dimensional Arrays

You might also like