0% found this document useful (0 votes)
5 views162 pages

Java Unit 1 Notes

This document provides an overview of Java programming, covering its history, features, and applications across various domains such as desktop, mobile, enterprise, and scientific applications. It explains fundamental concepts of object-oriented programming (OOP) including classes, objects, inheritance, encapsulation, and polymorphism, along with the structure of a Java program and the Java Virtual Machine (JVM) architecture. Additionally, it compares Java with C and C++, highlighting key differences in programming paradigms and features.

Uploaded by

suhasgowda05603
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views162 pages

Java Unit 1 Notes

This document provides an overview of Java programming, covering its history, features, and applications across various domains such as desktop, mobile, enterprise, and scientific applications. It explains fundamental concepts of object-oriented programming (OOP) including classes, objects, inheritance, encapsulation, and polymorphism, along with the structure of a Java program and the Java Virtual Machine (JVM) architecture. Additionally, it compares Java with C and C++, highlighting key differences in programming paradigms and features.

Uploaded by

suhasgowda05603
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA UNIT-1

UNIT-1
Introduction: Basics of object-oriented programming, comparison of procedure-oriented and object
oriented programming paradigms; Difference between C and Java Programming languages; Features of
Java; Objects and classes in Java, Structure of a Java program; Data Types, variables and operators in java;
Control structures- Branching and looping; Methods & Constructors in java; Java Development Kit (JDK);
Built-in classes in Java; Math, Character, String, String Buffer and Scanner; Wrapper classes; The abstract,
static and final classes; Casting objects; The instance of operator; Usage of this keyword; Arrays in Java.
History of java
JAVA BASICS
Java is a general purpose, object oriented programming language developed by Sun MicroSystems in
1991. Originally called OAK by James gosling , Father of java programming language. But was renamed as
java in 1995
Below is the Java applications list:

Desktop GUI Applications


Mobile Applications
Enterprise Applications
Scientific Applications
Web-based Applications
Embedded Systems
Big Data Technologies
Distributed Applications
Cloud-based Applications
Web servers and Application servers
Software Tools
Gaming Applications

1. Desktop GUI Applications


Desktop applications can be easily developed using Java. We use APIs like AWT, Swing, JavaFX to build these
applications.
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 C weRM (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, aeronautfeature MATLAB 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 [Link], online forms, shopping carts, Gmail, Google Sheets, Google
Slides and many more.
6. 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. It is one of the most popular topics in the world of the latest technology. Java is the
perspective of big data. Today, many developers are switching their careers to Big Data Technology.
Eg Handbook, Apache handoop
8. Distributed Applications
A distributed application is an application or software that executes or runs on multiple computers within a
network.
9. Cloud-based Applications
Cloud computing means on-demand delivery of IT resources via the Internet, including storage, servers,
databases, networking, Java has long been the programming language that provides a structure for web
applications, and now it has reached cloud applications, because of its distributed nature.
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). A web server is a
system that runs websites and delivers web pages to users. Java ecosystem contains multiple Java web
servers and application servers.
Java provides web servers including Apache Tomcat, Simple, Jo!, Rimfaxe Web Server (RWS) Apache HTTP
server, Resin, Adobe JRun, and Project Jigsaw.
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. Today almost every person
has an Android phone that has Android games in it. 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.
Basic concepts of OOPS programming
Class is a template or blueprint used to create objects and to define
object data types and methods.
A class is a group of objects which have common properties.
A class — in the context of Java — is a
template used to create objects and to
define object data types and methods.
Classes are categories, and objects are items
within each category. All class objects should
have the basic class properties.

Syntax of Class in Java


class <class_name>

fields or data members or attributes;


method;

}
Objec
t object is a real world entity.
An
An object is an instance of a class.

Objects have states and behaviors. Example: A dog has


states - color, name, breed as well as behaviors –
wagging the tail, barking, eating.

• State: represents the data (value) of an object.


• Behavior: represents the behavior (functionality)
of an object such as deposit, withdraw, etc.
• Identity: An object identity is typically
implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is
used internally by the JVM to identify each object
uniquely.
Object Syntax in Java
ClassName ReferenceVariable = new ClassName();

Dog tuffy = new Dog("tuffy","papillon",5, "white");


Inheritance
• Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object
Oriented programming system).
• The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
• When you inherit from an existing class, you can
reuse methods and fields of the parent class.

• java Inheritance provides a reusability mechanism in


object-oriented programming for the users to reuse the
existing code within the new applications.
• It does this by allowing the programmer to build a
relationship between a new class and an existing class
and define a new code in terms of existing code. This
relationship is known as parent-child relationship in
java.
A car is a type of Vehicle, so inheritance hierarchy might begin from the Vehicle class as follows:
The syntax of Java Inheritance
[Link] Subclass-name extends Superclass-name
2.{
3. //methods and fields
4.}
Encapsulation
Encapsulation is one of the four fundamental OOP concepts.
Polymorphism
• Polymorphism is the ability of an object or a
function to take on many forms.
• There are 2 types of polymorphism
• Compile time polymorphism
• Runtime polymorphism
Dynamic Binding
• “Dynamic” means “run time”, and “binding”
means “association”. So the term dynamic
binding indicates run time association
of objects by java virtual machine.
• Connecting a method call to the method
body is known as binding.
• In dynamic binding, the method call is
resolved at runtime, which means the
method to be executed is determined at the
time of execution.
Data Abstraction
• Data abstraction is the process of
hiding certain details and showing
only essential information to the
user. Abstraction can be achieved
with either abstract classes or
interfaces.
Difference between C, C++ and java

Metrics C C++ Java


Object-Oriented Pure Object Oriented
Programming Paradigm Procedural language
Programming (OOP) Oriented
Based on assembly
Origin Based on C language Based on C and C++
language
Bjarne Stroustrup in
Developer Dennis Ritchie in 1972 James Gosling in 1991
1979
Interpreted language
Translator Compiler only Compiler only
(Compiler + interpreter)
Platform Dependency Platform Dependent Platform Dependent Platform Independent
Executed by JVM (Java
Code execution Direct Direct
Virtual Machine)
Approach Top-down approach Bottom-up approach Bottom-up approach
Metrics C C++ Java
File generation .exe files .exe files .class files
Support header files
Pre-processor directives Supported (#header, #define) Use Packages (import)
(#include, #define)
keywords Support 32 keywords Supports 63 keywords 50 defined keywords

Datatypes (union, structure) Supported Supported Not supported

Supported except Multiple


Inheritance No inheritance Supported
inheritance

Support Function overloading Operator overloading is not


Overloading No overloading
(Polymorphism) supported

Pointers Supported Supported Not supported


Allocation Use malloc, calloc Use new, delete Garbage collector
Exception Handling Not supported Supported Supported
Templates Not supported Supported Not supported
No constructor neither
Destructors Supported Not supported
destructor

Multithreading/ Interfaces Not supported Not supported Supported

Database connectivity Not supported Not supported Supported

Storage Classes Supported ( auto, extern ) Supported ( auto, extern ) Not supported
1. Java PROGRAM STRUCTURE:
A java program may contain many classes of which only one class defines a main
method. Classes contain datamembers and methods that operate on the data members of
the class.

Java program may contain one or more sections as shown below.


Documentation section:
This section comprises of a set of comment lines giving the name of program, the author & other details, which
the programmer would like to refer at later stage. It is suggested one.
package statement:
The first statement allowed in java is a ‘package’ statement.
This statement declares a package name and informs the compiler that the classes defined here belong to this
package.
Eg: package student;
It is optional section.
Import statement:e
This is similar to the #include statement in C
Eg: import [Link].*;
It is optional section.
Interface statement:
An interface is like a class but includes a group of method declarations. It is also optional section and is used
only when we wish to implement the multiple inheritance feature in jprogram.
Class Definitions:
A java program may contain multiple class definitions. Classes are the primary & essential elements of a java
program.
Main Method Class:
Since every java stand alone program requires a main method as its starting point, this class is the essential part of
a java [Link] main method creates objects of various classes and establishes communications between
them. On reaching the end of main, the program terminates and the control passes back to the operating system.

/* This is a simple Java program.


FileName : "[Link]". */
Import [Link].*;
class HelloWorld
{
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
[Link]("Hello, World");
}
}

Output:
Hello, World
[Link] definition:This line uses the keyword class to declare that a new class is being [Link]
HelloWorld HelloWorld is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace { and the closing curly
brace } .

[Link] method: In Java programming language, every application must contain a main method
whose signature is:public static void main(String[] args) public: So that JVM can execute the method
from anywhere. static: Main method is to be called without object. The modifiers public and static
can be written in either order. void: The main method doesn't return anything. main(): Name
configured in the JVM. String[]: The main method accepts a single argument: an array of elements of
type [Link] in C/C++, main method is the entry point for your application and will subsequently
invoke all the other methods required by your program.

[Link] next line of code is shown here. Notice that it occurs inside main( ).[Link]("Hello,
World"); This line outputs the string “Hello, World” followed by a new line on the screen. Output is
actually accomplished by the built-in println( ) method. System is a predefined class that provides
access to the system, and outis the variable of type output stream that is connected to the console.

[Link]: They can either be multi-line or single line comments./* This is a simple Java program.
Call this file "[Link]". */ This is a multiline comment. This type of comment must begin with
/* and end with */. For single line you may directly use // as in C/C++.
[Link] a java program:
Implementation of java application program involves a series of steps. They include
•Creating the program
•Compiling the program
•Running the program
Remember that, before we begin creating the program, JDK must be properly installed on our system.
Creating the program:
We can create a program using any text editor
class Sample
{
public static void main(String arg[])
{
[Link](“Hi friend”);
}
}
We have to save this program with a name like [Link]
A java Application have any no of classes, but only one main class. Main class is nothing but class which
contains main() method
Compiling the program:
To compile the program we must run the java compiler javac, with the name of the source file on command line as
shown below
C:\> javac [Link]
If everything is OK, java compiler(javac) creates a file called [Link] (<[Link]>) containing the
bytecodes of the program [Link]
Running the program:
We need to use the java interpreter to run stand alone applications. At the command prompt, type…
C:\> java Sample
Now, the interpreter looks for the main method in the program and begins execution from there. When executed
our program displays the following
o/p: Hi friend
[Link] Virtual Machine:
Generally all language compilers translate source code into machine code for a specific computer. In java,
architectural neutral is achieved because compiler produces an intermediate code called Byte code, for a
machine is called JVM

How JVM Works – JVM Architecture?


JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually
calls the mainmethod present in a java code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop
Java code on one system and can expect it to run on any other Java enabled system without any adjustment.
This is all possible because of JVM.

When we compile a .java file, .classfiles(contains byte-code) with the same class names present in .java file
are generated by the Java compiler. This .class file goes into various steps when we run it. These steps
together describe the whole JVM.
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

Class Loader: The class loader reads the .class file and save the byte code in the method area.
Method area :In method area, all class level information like class name, immediate parent class
name, methods and variables information etc. are stored, including static variables. There is only
one method area per JVM.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for
each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary
variables.
PC Registers: This keeps the track of which instruction has been executed and which one is going
to be executed.

Java Native Interface (JNI) :


It is an interface which interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries
Native Method Libraries :
It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.
7) Execution Engine
It 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.
What are the Java tokens?
Java tokens are the basic building
blocks of a Java program. They are
the smallest units of a program,
and they include keywords,
identifiers, operators, literals,
separators, and comments.
Separators are symbols that
separate different parts of a program.

Variables Sum,age ,rollno


Non –primitive data types
• Non-primitive data types are created by programmers. They are not
predefined in java like primitive data types. These data types are used
to store a group of values or several values.
• They are also called Reference data types because they
cannot store the value of a variable directly in memory. Non-
primitive data types do not store the value itself but they store a
reference or address (memory location) of that value.
• long modelNumber = 62548723468;
• Strings: String is a sequence of characters. But in Java,
a string is an object that represents a sequence of
characters. The [Link] class is used to create a string
object.
• Ways to create a string object:
• There are 2 ways of creating a String object:
• By using a string literal: Java String literal can be created just by
using double-quotes.

• String myLine = “Welcome to Java class”;


• By using a “new” keyword: Java String can also be created by
using a new keyword. For example:
• String myLine = new String(“Welcome to Java class”);
• public class Stringtest
• {
• public static void main(String args[])
• {
• String string1 = "Hello World"; // declaring string using string literals

• String string2 = new String("This is a Java class "); //declaring string using new
operator

• [Link](string1);
• [Link](string2);
• }
• }
• Output:
• Hello World
This is a Java Tutorial
• Arrays: Java array is an object which contains elements of a similar
data type. Arrays store one or more values of a specific data type and
provide indexed access to store the same.

The valid syntax for array The valid syntax for array initialization can be:
declaration can be: array_name = new data-type [size of array];
data-type array_name [ ]; array_name = new data-type {elements of array using
data-type [ ] array_name; using commas};
public class Arraydemo
{
public static void main(String args[])
{
int [ ] marksOfStudents = new int[ ] {65, 90, 78, 60, 84 };
[Link]("Marks of first student: " +marksOfStudents[0]);
[Link]("Marks of second student: "
+marksOfStudents[1]);
[Link]("Marks of third student: " +marksOfStudents[2]);
[Link]("Marks of fourth student: " +marksOfStudents[3]);
[Link]("Marks of fifth student: " +marksOfStudents[4]);
}
}
• Marks of first student: 65
Marks of second student: 90
Marks of third student: 78
Marks of fourth student: 60
Marks of fifth student: 84
• Classes: A class is a collection of objects of the same type. It is a
user-defined blueprint or prototype which defines the behavior or
state of objects. A class contains fields(variables) and methods to
describe the behavior of an object.
• We create a class using a class keyword.
• A class can be declared using the following components in the order-
• 1. Access modifiers: Access modifiers define the access privileges of a
class. A class can be public or it has default access.
• 2. Class name: The name of a class should represent a noun and must
start with a capital letter. These are the best practices to be kept in
mind while declaring any class.
• 3. Body: The class body contains properties and methods. The body is
always enclosed by curly braces { }.
Syntax of writing a class:
AccessModifier class class_name
{
Class body - variables and methods();
}

public class MyClass


{
int x = 5;
void display()
{
// methodBody;
}
}
Java Objects
• It is a basic unit of Object-Oriented
Programming which represents the real-
world entities. An object is an instance of a
class. It defines the state and behavior of
real-life entities.
• State: It represents the attributes and
properties of an object.
• Behavior: Methods define the behavior of an
object. It also reflects the communication of
one object with the other objects.
• Identity: It gives a unique name to an object
which allows one object to interact with
other objects.
Syntax of creating an object of a class:
To create an object of a class, specify the class name, followed by the object name, by using the new keyword-
Class name object_Name = new Class name();
Example:
MyClass object1 = new MyClass();
public class Student
{
int marks = 76;
public static void main(String[] args)
{
Student student1 = new Student(); // creating object of the class by using new operator
[Link]("Marks of student: " +[Link]); //Accessing the property “marks” of the class with the help
of an object.
}

}
Output:
Marks of student: 76
• An interface behaves like a blueprint of a class,
which specifies “what a class has to do and not how
it will do”.
• Interface: Like a class, an interface can have
methods and variables, but the methods
declared in interface are by default abstract (only
method signature, no body).

• In the real-world, one user defines an interface, but


different user provides its implementation.
Moreover, it is finally used by some other user.
• Syntax of writing interfaces:
• To declare an interface, we just write the keyword
“interface” followed by the interface name:
• interface interface_name
• To use an interface in a class, we have to append the
keyword “implements” after the class name followed
by the interface name.
• class class_name implements interface_name
• //creating an interface
• interface Runnable
• {
• public void run(); //an abstract method
• }
• // implementing the interface
• public class Person implements Runnable
• {
• public void run()
• {
• [Link]("This person can run");
• }
• public static void main(String args[])
• {
• Person person1 = new Person();
• [Link]();
• }
• }
Variables in Java

A variable is a name given to a memory location. It is the basic unit of storage in a program.
•The value stored in a variable can be changed during program execution.
•A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
•In Java, all the variables must be declared before use.
How to declare variables?
We can declare variables in java as follows:

type: Type of data that can be stored in this variable.


name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
Variable Initialization
Assigning value by taking input
How to initialize variables?
How to initialize variables?

float simpleInterest; //Declaring float variable


int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = ‘h’; // Declaring and Initializing character variable

Types of variables
There are three types of variables in Java:
Local Variables
Instance Variables
Static Variables
Let us now learn about each one of these variables in detail.
Local Variables: A variable defined within a block or method or constructor is called local variable.
These variable are created when the block in entered or the function is called and destroyed after exiting from
the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can access
these variable only within that block.
Initilisation of Local Variable is Mandatory.
public class StudentDetails {
public void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
[Link]("Student age is : " + age);
}

public static void main(String args[])


{
StudentDetails obj = new StudentDetails();
[Link]();
//Age=10; //error
[Link](age);
} Output :. Student age is : 5
}
In the above program, the variable age is a local variable to the function
StudentAge(). If we use the variable age outside StudentAge() function, the
compiler will produce an error as shown in below program.
•Instance Variables: Instance variables are non-static variables and are declared in a
class outside any method, constructor or [Link] instance variables are declared in a
class, these variables are created when an object of the class is created and destroyed
when the object is destroyed.
•Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
•Initilisation of Instance Variable is not Mandatory. Its default value is 0
•Instance Variable can be accessed only by creating objects.
import [Link].*;
class Marks {
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}

class MarksDemo {
public static void main(String args[])
{
// first object
Marks obj1 = new Marks();
[Link] = 50;
[Link] = 80;
[Link] = 90;
// second object Output:
Marks obj2 = new Marks(); Marks for first object:
[Link] = 80; 50
[Link] = 60; 80
[Link] = 85; 90
Marks for second
object: 80
// displaying marks for first object 60
[Link]("Marks for first object:"); 85
[Link]([Link]);
[Link]([Link]); As you can see in the above program the
[Link]([Link]); variables, engMarks , mathsMarks , phyMa
rksare instance variables. In case we have
// displaying marks for second object multiple objects as in the above program,
[Link]("Marks for second object:");each object will have its own copies of
[Link]([Link]); instance variables. It is clear from the
[Link]([Link]); above output that each object will have its
[Link]([Link]); own copy of instance variable.
s.o.p(engmarks);
}
}
•Static Variables: Static variables are also known as Class [Link] variables are declared similarly
as instance variables, the difference is that static variables are declared using the static keyword within a
class outside any method constructor or block.

•Unlike instance variables, we can only have one copy of a static variable per class irrespective of how
many objects we create.

•Static variables are created at the start of program execution and destroyed automatically when execution
ends.

•Initialization of Static Variable is not Mandatory. Its default value is 0

•If we access the static variable like Instance variable (through an object), the compiler will show the
warning message and it won’t halt the program. The compiler will replace the object name to class name
automatically.

•If we access the static variable without the class name, Compiler will automatically append the class name.
To access static variables, we can simply access the variable as. .

class_name.variable_name;
import [Link].*;
class Emp {

// static variable salary


public static double salary;
public static String name = "Harsh";
}

public class EmpDemo {


public static void main(String args[])
{

// accessing static variable without object


[Link] = 1000;
[Link]=2000;
[Link]([Link] + "'s average salary:"
+ [Link]);
}
}
Output:
Harsh's average salary: 2000.0
Instance variable Vs Static variable

•Each object will have its own copy of instance variable whereas We can only have one copy of a static
variable per class irrespective of how many objects we create.
•Changes made in an instance variable using one object will not be reflected in other objects as each object
has its own copy of instance variable. In case of static, changes will be reflected in other objects as static
variables are common to all object of a class.

•We can access instance variables through object references and Static Variables can be accessed directly
using class name.

•Syntax for static and instance variables :


class Example {
static int a; //static variable
int b; //instance variable }

•Default values of variables

•Byte/short/int/long– will be having 0 default value


•Float/double – 0.0
•Char– ‘\u0000’ (null character)
•Boolean—false
Symbolic Constant(Final Keyword)

We can define the symbolic constant in Java, by using keyword final. This is similar to keyword const in c
and c++.
The keyword final proceeds the data type of a variable. It specifies that the value of a variable will not
change throughout the program . Any attempt to alter the value of a variable defined with this qualifier
will cause an error from the compiler. The syntax is

final <data type><variable name>= value;


Eg: final double PI=3.14;
final int MAX_Marks=100;
The final variables should be initialized at the time of declaration or in the constructor.
Eg: class Test. Class Test
{ {
final int max; final int max=100;
Test() final int min; // shows error
{ }
Max=100;.
}
}
Reading Input From keyboard

A streams required to accept input from the keyboard. A stream represents flow of data from
one place to another place. A stream can carry a data from keyboard to memory or from memory
to monitor or from memory to printer. There are two types of stream, input and output streams.
Input stream are those streams which recieve or read data from some other place. Output
streams are those streams which send or write data to some other place.

The console is represented by a field called out in System class. similarly the keyboard is
represented by a field called in in System class . We can read javas input from [Link]
console and write output to console using “[Link]”. There are two common ways to read
input from

1. InputStreamReader wrapped in a BufferedReader


2. Scanner classes in JDK1.5.

1. Using Input Stream Reader Class


To accept data from keyboard. We need to connect it to an input stream. The following steps re
required in this process
Step1: Connect the keyboard([Link]) to an inputStream object . We an use InputStreamReader class that
can read data from the keyboard.

InputStreamReader is=new InputStreamReader([Link]);


In the above statement , we have created InputStreamReader object and connecting the keyboard
([Link]) to it.

Step2: Connect InputTreamReader to BufferedReader Which is another input stream. We are using
BufferedReader as it has got methods to read data properly from the input stream.

BufferedReader br= new BufferedReader(is);


Here, we have created BufferedReader object and connected to InputStreamReader object is. We can
achieve step1 and step2 in single statement as shown below.

BuffferedReader br= new BufferedReader(new InputStreamReader([Link]));

Step3: now, we can read the data from the keyboard using read() an readLine() methods of BufferedReader
class.

Step4: to read entire line from Keyboard use the below code. The entire text entered in the keyboard is
assigned to String object str.

String str=[Link]();
Step5: to read integer from keyboard.
Int age= [Link]([Link]());
Remember that what ever we enter in the console is treated as string and hence we should convert it
to our required data tyoe. The cod [Link]() returns the string and converting this string to an
jnteger, we should use above code .
Output : enter your name
Import [Link].*; ABC
Public class Read Enter your age
{ 6
public static void main(String args[]) Are you male / female type M or F
{ F
BufferedReader b= new BufferedReader(new InputStreamReader([Link])); Name is ABC
[Link](“enter your name:”); // to read entire line Age is 6
String str=[Link](); Gnder is F
[Link](“enter your age:”); // to read integer
int age= [Link]([Link]());
[Link](“ are you male / female type M orF:”); // to read some character
char ch=(char)[Link]();
[Link](“name:”+str); In this example we have used char in in brackets. This is
[Link](“age is :”+age); called typecasting. The read() method reads single
[Link](“ gender is :”+ch); character from the keyboard and returns the ASCII Vale
} and which is integer. To convert the integer to character
} we should use type casting in the code
2. Using Scanner class

The scanner class is a class in [Link] pacakge. The scanner class is introduced in Java 1.5. it will work
only if we have Jdk 1.5 onwards. The scanner class is a class used for scanning primitive types and strings.
It can be used to get input from an InputStream ([Link]),to parse trough a string o text or to read from
a file . The usage of scanner class is easy way to read input from file or console and code is cleaner.

Step1: Import scanner class from [Link] package as shown below.


Import [Link]; or import [Link].*;

step2: Create Scanner object and attach it to ([Link]) as shown below.


Scanner sc=new Scanner([Link]);

Step3: Now, if the user has given the integer value from keyboard it is stored into the Scanner object(sc)
as a token. To recieve that token, we can use the method: sc nextInt(). To recieve string use [Link]( )
and recieve float use [Link](); methods.

String are=[Link](); boolean b= sc.n extBoolean();


int age =[Link](); char ch= [Link]().charAt(0);
float avg=[Link]();
double amount=[Link]();
long bignumber=[Link]();
byte smallnumber=[Link]();
Program [Link] the concept of scanner class
Output
Import [Link];
Public class SccanerDemo Enter your name
{ ABC
Public static void main(String args[]) Enter your age
12
{
Enter the amount
Scanner s= new Scanner([Link]); 89.678
System [Link](“enter your name”); // to read entire line
String str=[Link](); Name is ABC
[Link](“enter your Age ”); Age is 12
int age=[Link](); // to read age Amount is 89.678
[Link](“enter the amount:”);
float amount=[Link](); // To read the amount

/* To print the details to the console */


[Link](“ name is”+str);
[Link](“Age is “+age);
[Link](“ amount is”+amount);
}
}
Writing data to the console
We know that we have to use either [Link]() or [Link]() method . Let’s
see various form of using the same
● to display a value, we can write it in the parentheses of [Link](). If the value is a
character ,then include it between single [Link] is an example
class Test()
{
Public static void main(String[] args)
{
[Link](‘A’);
// If the value is a word or sentence include it between double quotes
[Link](“Acharya”);
// If the value is a number then simply type the number in parentheses
[Link](12);
// if the value is stored in a variable ,write the name of that variable in the parentheses
Int a=100;
Int b=200;
[Link](“ thevaluofa is”+a);
[Link]( “ the value of b is “+b);
[Link](‘the value of a is “+a+ “ value of b is” +b);
}
}
We have one more to print the statements I.e [Link]() statement. This allows
to format how data should appear when displayed to the user. The datatypes are didvided
in categories ,char int, floating-point numbers and strings. To display a particular type, we
type the percent operator “%” , followed by the category of data.

[Link](“ the value of a is %d and B is %d”,a,b);


The first section ends with a closing double quote followed by a comma after the
comma,we must include the name of the variable who’s value will be displayed in the %d
placeholder.

%s – formats strings
%d – formatsintegers
%f – formats the floating-point numbers
%b- boolean
\n – new line character.

The difference between [Link]() and [Link]() I SB the print() method


keeps the cursor in the same line after displaying the output an println() method moves the
cursor to next line after displaying the output.
Typecasting(CASTING OBJECTS)
Typecasting is the process of converting one variable of certain datatype into another
datatype.

Types of casting: there are two types of casting, implicit Casting and Explicit Casting .
The implicit Casting is also called as automatic conversion or widening conversion. The
explicit casting is also called as narrowing conversion.

Implicit Casting
Automatic casting done by the java compiler internally is called implicit Casting. Implicit
Casting is done to convert lower data type into a higher data type.
● when one type of data is assigned to another type of variable an automatic type
conversion with take place if,
◆the two types are compatible
◆the destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example , the
int type is always large enough to hold all valid byte values, and both int and byte ate
integer types, so an automatic conversion from byte to int can be applied .
For widening conversions the numeric types, integer and floating point types are
compatible with each other.
Eg int ¡;
float f;
¡=10;
f=¡; // assigned int to float
The implicit Casting rules are clearly understood from the below diagram

byte -> short -> char -> int -> long -> float -> double
In the above line it demonstratea that a byte can be assigned to a shorter float,but a double
cannot be assigned to float or int.
class Test
{
public static void main(String[] args)
{
int i = 100;

// automatic type conversion


long l = i;

// automatic type conversion


float f = l;
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}
}

Output
Int value 100
Long value 100
Float value 100.0
Explicit Casting

The casting done by the programmer or developer is called explicit Casting. Explicit Casting is must
when converting from a higher ata type to a lower data type.

General form. (typename)value;

In this form typename is the name of the type we are converting to and value is an expression that
results in the value we want to convert.
Example:
1. double d=6.289;
int I =(int)d; // in the above code, the value of double 6.289 is converted to int 6 and te
assigned the integer value 6 to I.
Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;

//explicit type casting


long l = (long)d;

//explicit type casting


int i = (int)l;
[Link]("Double value "+d);

//fractional part lost


[Link]("Long value "+l);

//fractional part lost


[Link]("Int value "+i);
}
}

Output
Output:
Double value 100.04
Long value 100
Int value 100
//Java program to illustrate Conversion of int and double to byte
class Test
{
Output:
public static void main(String args[])
Conversion of int to byte.
{
i = 129 b = 1
byte b;
Conversion of double to byte.
int i = 128;
D = 323.142 b = 69
double d = 323.142;
[Link]("Conversion of int to byte.");

//i%127
b = (byte) i;
[Link]("i = " + i + " b = " + b);
[Link]("\nConversion of double to byte.");

//d%127
b = (byte) d;
[Link]("d = " + d + " b= " + b);
}
}
• What are the Java Operators?
Operators in java
Arithimetic Operators:
• Arithmetic operators are used to perform
arithmetic operations on variables and data.
• 1. Addition(+): This operator is a binary
operator and is used to add two operands.

• num1 + num2

Example:
num1 = 10, num2 = 20 ;
sum = num1 + num2 ;
= 30
• 2. Subtraction(-): This operator is a binary operator and is used to subtract two operands.
• Syntax:
num1 - num2

• Example:
num1 = 20, num2 = 10 sub =
num1 - num2 = 10

3. Multiplication(*): This operator is a binary operator and is used to multiply two operands.

num1 * num2

Example:
num1 = 20, num2 = 10 mult = num1 * num2 = 200
• 4. Division(/): This is a binary operator that is used to divide the
first operand(dividend) by the second operand(divisor) and give the
quotient as a result.
• num1 / num2
• num1 = 20, num2 = 10 div = num1 / num2 = 2
• 5. Modulus(%): This is a binary operator that is used to return the
remainder when the first operand(dividend) is divided by the
second operand(divisor).
• Syntax:
• num1 % num2
• num1 = 5, num2 = 2 mod = num1 % num2 = 1
• public class ArithmeticOperator
• {
• public static void main(String[] args) Addition num1+num2 13
• { Subtraction num1-num2 -3
• int add, Multiplication num1*num2 40
• sub, Division num1/num2 0
• mul, Modulus num2%num1 3
• div,
• mod;
• int num1 = 5,
• num2 = 8;
• add = num1 + num2;
• sub = num1 - num2;
• mul = num1 * num2;
• div = num1 / num2;
• mod = num2 % num1;
• [Link]("Addition num1+num2 " + add);
• [Link]("Subtraction num1-num2 " + sub);
• [Link]("Multiplication num1*num2 " + mul);
• [Link]("Division num1/num2 " + div);
• [Link]("Modulus num2%num1 " + mod);
• }
2. Relation Operators
• Relational operators are used to check the relationship between two
operands.
• Relational operators are used in decision making and loops.
Logical Operators
• Logical operators are used to perform logical
“AND”, “OR” and “NOT” operations.
• fi. Logical ‘AND’ Operator (&&)
• This operator returns true when both
the conditions under consideration
are satisfied or are true. If even one of the
two. yields false, the operator results false
public class Land {
public static void main(String[] args) {
int x = 5;
InSimple terms, cond1 && cond2 returns true [Link](x > 3 && x < 10); // returns true becaus
when both cond1 and cond2 are true (i.e. non- is greater than 3 AND 5 is less than 10
zero). }
}

condition1 && condition2


2. Logical ‘OR’ Operator (||)
This operator returns true when one of the two conditions under consideration is satisfied or is true.
If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.

Syntax:
condition1 || condition2

public class LOR {


public static void main(String[] args) {
int x = 5;
[Link](x > 3 || x < 4); // returns true because one of the conditions are true (5 is greater than
3, but 5 is not less than 4)
}
}
3. Logical ‘NOT’ Operator (!)
Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not
satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the
condition is true, the operation returns false.

public class Main {


public static void main(String[] args) {
int x = 5;
[Link](!(x > 3 && x < 10)); // returns false
because ! (not) is used to reverse the result
}
}
Assignment operators
Assignment operators are used to assigning the value on its right to the variable on its left.
These operators are used to assign values to a variable.

The left side operand of the assignment operator is a variable and the right side operand of the assignment
operator is a value.
variable operator value;
Increment and Decrement Operators:
 The increment (++) and decrement operator (--) are simply used to increase and decrease the
value by one.

 Increment and decrement operators are unary operators. We can only apply these operators on a single
operand,hence these operators are called as unary operators.
 Pre Increment Operator:(++x)
 If an Increment operator is used in front of an operand, then it is called as Pre Increment operator.

 Post Increment Operator:(x++)


 If an Increment operator is used after an operand, then is called Post Increment operator.
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and
byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −
Operator Description Example
Binary AND Operator copies a
(A & B) will give 12 which is
& (bitwise and) bit to the result if it exists in
0000 1100
both operands.
Binary OR Operator copies a bit (A | B) will give 61 which is
| (bitwise or)
if it exists in either operand. 0011 1101
Binary XOR Operator copies
^ (bitwise XOR) the bit if it is set in one (A ^ B) will give 49 which is 0011 0001
operand but not both.
Binary Ones Complement (~A ) will give -61 which is 1100 0011 in
~ (bitwise compliment) Operator is unary and has 2's complement form due to a signed
the effect of 'flipping' bits. binary number.
Binary Left Shift Operator.
The left operands value is
<< (left shift) moved left by the number of A << 2 will give 240 which is 1111 0000
bits specified by the right
operand.
Binary Right Shift Operator.
The left operands value is
A >> 2 will give 15 which is 1111
>> (right shift) moved right by the number
of bits specified by the right
operand.
Shift right zero fill operator.
The left operands value is A >>>2 will give 15 which is
moved right by the number 0000 1111
>>> (zero fill right shift)
of bits specified by the right
operand and shifted values
are filled up with zeros.
class BitwiseOR {
public static void main(String[] args) {
int number1 = 12, number2 = 25, result, result1,result2;
result = number1 | number2;
result1 = number1 & number2;
result2 = number1 ^ number2;
[Link](result);
[Link](result1);
[Link](result2);
}
}
Output
29
8
21
Bit Shifting
A bit shift moves each digit in a number's binary representation left or right. There are three main types of shifts:
Left Shifts
When shifting left, the most-significant bit is lost, and a 00 bit is inserted on the other end.
The left shift operator is usually written as "<<".
0010 << 1 → 0100
0010 << 2 → 1000

Logical Right Shifts


When shifting right with a logical right shift, the least-significant bit is lost and a 00 is inserted on the other end.
1011 >>> 1 → 0101
1011 >>> 3 → 0001

Arithmetic Right Shifts


When shifting right with an arithmetic right shift, the least-significant bit is lost and the most-significant bit is copied.
Languages handle arithmetic and logical right shifting in different ways. Java provides two right shift operators: >> does
an arithmetic right shift and >>> does a logical right shift.
1011 >> 1 → 1101
1011 >> 3 → 1111
0011 >> 1 → 0001
0011 >> 2 → 0000
The first two numbers had a 11 as the most significant bit, so more 11's were inserted during the shift. The last two numbers
had a 00 as the most significant bit, so the shift inserted more 00's.
instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a particular
type (class type or interface type). instanceof operator is written as −
( Object reference variable ) instanceof (class/interface type) If the object referred by the variable on the left
side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true.
Following is an example −
Example
Live
public class Test {
public static void main(String args[]) {
String name = "James"; // following will return true since name is type of String
Test ob1=new Test();
boolean result = name instanceOf String;
boolean result1 = ob1 instanceOf Test;
[Link]( result 1);

[Link]( result );
}}
This will produce the following result −

Output
true
true
New operator
The new operator is used to create objects,that is instances of classes
Eg: Animal dog=new Animal();

Dot operator
Their operator (.) is used to access the instance variables and methods of class using object
[Link];
[Link]();
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

To create a Class
Syntax

[accessModifier][classModifiers] class Classname [extends


SuperClassname][implements interfacelist]
{
[variable declarations]
[Method declarations]
}

Here elements between the pair of square brackets [] are optional . Access
modifiers are public, private, protected and class modifier is abstract which
are optional
Extends is the keyword used to create inheritance and implements is also
keyword to create interfaces(which will be studied later). Even variables
and methods are optional in class declaration.

Following is a sample of a class.

Example
public class Dog {
String breed;
int age;
String color;

void barking() {
[Link](" Dog is baarking") ;
}

void hungry() {
[Link]("dog is feeling hungry") ;
}

void sleeping() {
[Link]("dog is sleeping") ;
}
}
Adding variables inside class

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.

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.

A class can have any number of methods to access the value of various
kinds of methods. In the above example, barking(), hungry() and sleeping()
are methods.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

To create a Class
Syntax

[accessModifier][classModifiers] class Classname [extends


SuperClassname][implements interfacelist]
{
[variable declarations]
[Method declarations]
}

Here elements between the pair of square brackets [] are optional . Access
modifiers are public, private, protected and class modifier is abstract which
are optional
Extends is the keyword used to create inheritance and implements is also
keyword to create interfaces(which will be studied later). Even variables
and methods are optional in class declaration.

Following is a sample of a class.

Example
public class Dog {
String breed;
int age;
String color;

void barking() {
[Link](" Dog is baarking") ;
}

void hungry() {
[Link]("dog is feeling hungry") ;
}

void sleeping() {
[Link]("dog is sleeping") ;
}
}
Adding variables inside class

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.

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.

A class can have any number of methods to access the value of various
kinds of methods. In the above example, barking(), hungry() and sleeping()
are methods.
Method definition consists of a method header and a method body. The same
is shown in the following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}
The syntax shown above includes −
•modifier − It defines the access type of the method and it is optional to use.
•returnType − Method may return a value.
•nameOfMethod − This is the method name. The method signature consists of
the method name and the parameter list.
•Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
•method body − The method body defines what the method does with the
statements.

•example
public static int methodName(int a, int b) {
// body
}
Method with return type and without return type
For using a method, it shld be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
Java return keyword is used to complete the execution of a method and can
be used to return a value from a method. The return followed by the
appropriate value that is returned to the caller. This value depends on the
method return type like int method always return an integer value.. A return
type may be a primitive type like int, float, double and char. The type of data
returned by a method must be compatible with the return type specified by the
method. For instance, if the return type of some method is boolean, we can not
return an integer.
EXAMPLE of function returning a value

public class MyClass {


static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
[Link](myMethod(3));
}
}
// Outputs 8
The void Keyword
The void keyword allows us to create methods which do not return a value.
Here, in the following example we're considering a void
method methodRankPoints. This method is a void method, which does not
return any value.
example:
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
[Link]("Rank:A1");
}else if (points <= 122.4) {
[Link]("Rank:A2");
}else {
[Link]("Rank:A3");
}
}
}
Output
Rank:A1
Passing Parameters to method
Information can be passed to methods as parameter. Parameters act as
variables inside the method.
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

public class MyClass {


static void myMethod(String fname) {
[Link](fname + " Abc");
}
public static void main(String[] args)
{
//Myclass obnj1=new Myclass();
//[Link](“A”); /// shows error
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}Liam Abc
}
Jenny Abc
Anja Abc
Output
CONSTRUCTORS

A constructor initializes an object when it is created. It has the same name


as its class and is syntactically similar to a method. However, constructors
have no explicit return type.

Typically, you will use a constructor to give initial values to the instance
variables defined by the class

All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your own constructor, the
default constructor is no longer used.

Syntax
Following is the syntax of a constructor −

class ClassName {
ClassName() {
}
}
Class A{
Public void main(String args[]){
A a1=new A();
}}
Here A() is a constructor, this statement virtually means, asking jvm
to create object of class A by executing the constructor A() defined
in class A. When we compile the program, we get .class file, if the
.java file consists any constructor, then the .class file also will have
the same constructor. Suppose if the .java file does not have any
constructor defined in it, then the compiler adds a default
constructor with the name of the class into the .class file and it is
this default constructor that is going to get executed whenever the
JVM encounters the new operator and create an object for the
class.

• The static keyword cannot be applied to constructor.


• TheThe constructor can be overloaded
• Constructors cannot be called by method
• We can call constructors from other constructor
Java allows two types of constructors namely −

[Link] argument Constructors


As the name specifies the no argument constructors of Java does not accept
any parameters instead, using these constructors the instance variables of a
method will be initialized with values for all objects.
Example
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
You would call constructor to initialize objects as follows
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
[Link]([Link] + " " + [Link]);
}
}
Output: 100 100
2. Parameterized Constructors
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added
to a method, just declare them inside the parentheses after the constructor's
name.
Example
Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows −
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
[Link](t1.x + " " + t2.x);
}
}
Java Environment
• The java environment contains both development tools and class libraries. The development tools are part of
Java development kit(Jdk) and class libraries are part of Java application programming interface(API).

1) Java development kit


A Java development kit is a program development environment for writing Java applets and applications.
Jdk contains. – Java runtime environment
-command line development tools, such as compilers and debuggers, those are necessary or useful for
developing applets and applications

Some of Jdk tools are

• Javac – the compiler for the java programming [Link] this tool we can compile Java programs and it
generates byte code.
• Java - the launcher or interpreter , using this tool we can execute the java byte codes.
• Javadoc- API documentation generator . Using this tool we can generate documentation for our Java programs in
html format, which describes classes,methods, constructors and fields.
• Appletviewer-- using this tool we can run and debug applets without a web browser.
• Jar-- create and manage Java archive (jar ) files.
• Jdb– the java debugger . Using this tool we can debug our Java programs to find out any errors.
• Javah– c header and stub generator .used to write native methods.
• Javap– class file disassembler. Using this tool we can convert byte codes to a program description.
2) Java application interface (API)

The application programming interface are pre written Java code that can be used by other programmers
create Java applications. The java API is the set of huge number of classes and methods grouped into
packages and it is included with the java development environment .the most commonly used packages
are:

• [Link] : are language support package . These classes support the basic language features and the
handling of arrays and strings. Classes in this package are always available directly in our programs by
default because this package is always automatically loaded with out program.
• [Link]: classes for data input and Output Operations
• [Link]:this package contains utility classes for managing data within collections groups of data
items . It contain classes for time, date and random number generator
• [Link]: to implement applet programs
• [Link]: abstract window toolkit: classes in this package provide the original GuI components as well
as some basic support necessary for swing components..
• [Link]: classes related to develop network programs
• [Link]: these classes provide easy to use and flexible components for building graphical user
interface s. The components in this package are referred to as swing components.
[Link] : classes related to database access database connectivity.
The [Link] class contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
Character class
Java provides a wrapper class Character in [Link] package. An object of type
Character contains a single field, whose type is char. The Character class offers a
number of useful class (i.e., static) methods for manipulating characters. You can
create a Character object with the Character constructor.

Creating a Character object:

Character ch = new Character('a’);

1. boolean isLetter(char ch): This method is used to determine whether the


specified char value(ch) is a letter or not. The method will return true if it is
letter([A-Z],[a-z]), otherwise return false. In place of character, we can also pass
ASCII value as an argument as char to int is implicitly typecasted in java.

Syntax:

boolean isLetter(char ch)

[Link]([Link]('A’)); //true

[Link]([Link](‘0’)); //false
2. boolean isDigit(char ch): This method is used to determine
whether the specified char value(ch) is a digit or not. Here also we can
pass ASCII value as an argument.

Syntax:

boolean isDigit(char ch)


[Link]([Link]('A’)); //false

[Link]([Link]('0’)); //true

3. boolean isWhitespace(char ch): It determines whether the


specified char value(ch) is white space. Whitespace includes space, tab, or
newline.

Syntax:

boolean isWhitespace(char ch)


[Link]([Link]('A’)); //false
[Link]([Link](' ‘)); //true
[Link]([Link]('\n’)); //true
4. boolean isUpperCase(char ch): It determines whether the specified char value(ch) is
uppercase or not.

Syntax:

boolean isUpperCase(char ch)


[Link]([Link]('A’)); //true
[Link]([Link]('a’)); //false

5. boolean isLowerCase(char ch): It determines whether the specified char value(ch) is


lowercase or not.

Syntax:

boolean isLowerCase(char ch)


[Link]([Link]('A’)); //false
[Link]([Link]('a’)); //true

6. char toUpperCase(char ch): It returns the uppercase of the specified char value(ch). If
an ASCII value is passed, then the ASCII value of its uppercase will be returned.

Syntax:

char toUpperCase(char ch)


[Link]([Link]('a’)); //A
[Link]([Link](97)); //65
7. char toLowerCase(char ch): It returns the lowercase of the specified char
value(ch).

Syntax:

char toLowerCase(char ch)


[Link]([Link]('A’)); //a
[Link]([Link](65)); //97
String in java
String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The [Link] class is used
to create a string object.
How to create a string object?

There are two ways to create String object:


By string literal
By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the pool,
a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be
created. Firstly, JVM will not find any string
object with the value "Welcome" in string
constant pool, that is why it will create a
new object. After that it will find the string
with the value "Welcome" in the pool, it will
not create a new object but will return the
reference to the same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one
reference variable
In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-
pool).
Strings Methods and its Description
1) Java String length(): The Java String length() method tells the length of the
string. It returns count of total number of characters present in the String. For
example:
String s1="hello";
String s2="whatsup";
[Link]("string length is: "+[Link]());
[Link]("string length is: "+[Link]());
}}
Here, String length() function will return the length 5 for s1 and 7 for s2
respectively.
2) Java String concat() : The Java String concat() method combines a
specific string at the end of another string and ultimately returns a
combined string. It is like appending another string. For example:
String s1="hello";
s1=[Link]("how are you");
[Link](s1);
}}
The above code returns “hellohow are you”.

3) Java String Trim() : The java string trim() method removes the
leading and trailing spaces. It checks the unicode value of space
character (‘u0020’) before and after the string. If it exists, then
removes the spaces and return the omitted string. For example:
String s1=" hello ";
[Link](s1+"how are you"); // without trim()
[Link]([Link]()+"how are you"); // with trim()
}}
In the above code, the first print statement will print “hello how are
you” while the second statement will print “hellohow are you” using
the trim() function.
4)Java String toLowerCase() : The java string toLowerCase() method
converts all the characters of the String to lower case. For example:

String s1="HELLO HOW Are You?”;


String s1lower=[Link]();
[Link](s1lower);}
}
The above code will return “hello how are you”.

5) Java String toUpper() : The Java String toUpperCase() method converts


all the characters of the String to upper case. For example:
String s1="hello how are you";
String s1upper=[Link]();
[Link](s1upper);
}}
The above code will return “HELLO HOW ARE YOU”.

6) Java String replace(): The Java String replace() method returns a


string, replacing all the old characters or CharSequence to new characters.
There are 2 ways to replace methods in a Java String.
String s1="hello how are you";
String replaceString=[Link]('h','t');
[Link](replaceString); }}

In the above code, it will replace all the occurrences of ‘h’ to ‘t’.
Output to the above code will be “tello tow are you”.

Java String replace(CharSequence target, CharSequence


replacement) method :

String s1="Hey, welcome to Edureka";


String replaceString=[Link]("Edureka","Brainforce");
[Link](replaceString);
}}
In the above code, it will replace all occurrences of “Edureka” to
“Brainforce”.
7) Java String equals() : The Java String equals() method compares
the two given strings on the basis of content of the string i.e Java
String representation. If all the characters are matched, it returns
true else it will return false. For example:
String s1="hello";
String s2="hello";
String s3="hi";
[Link]([Link](s2)); // returns true
[Link]([Link](s3)); // returns false

8)Java String equalsIgnoreCase(): This method compares two string


on the basis of content but it does not check the case like equals()
method. In this method, if the characters match, it returns true else
false. For example
String s1="hello";
String s2="HELLO";
String s3="hi";
[Link]([Link](s2)); // returns true
[Link]([Link](s3)); // returns false
9).chatAt() : this method returns a character located at the
specified index within a string object.
String str="Acharya"
[Link]([Link](3)) ; // prints a letter

10) The java string indexOf() method returns index of given


character value or substring. If it is not found, it returns -1. The
index counter starts from zero.
indexOf(int ch) example:
String str="Snigdha";
[Link]([Link]('g') ; // prints 3

IndexOf( inter ch, int fromindex)


String str="great java";
[Link]([Link]('a', 5)) ; // prints 7
StringBuffer Class in Java

The StringBuffer class in Java represents a sequence of characters that can be


modified, which means we can change the content of the StringBuffer without
creating a new object every time. It represents a mutable sequence of characters.

The key features of StringBuffer class are listed below:

Unlike String, we can modify the content of the StringBuffer without


creating a new object.
StringBuffer has an initial capacity, and it can also be adjusted later with
the help of the ensureCapacity() method.
With the help of the append() method, we can add characters, strings, or
objects at the end of the StringBuffer.
With the help of the insert() method, we can insert characters, strings, or
objects at a specified position in the StringBuffer.
With the help of the delete() method, we can remove characters from the
StringBuffer.
With the help of reverse() method, we can reverse the order of characters
in the StringBuffer.
Methods Action Performed
append() Used to add text at the end of the existing text.
The length of a StringBuffer can be found by the length( )
length()
method.
the total allocated capacity can be found by the capacity(
capacity()
) method.
This method returns the char value in this sequence at
charAt()
the specified index.
Deletes a sequence of characters from the invoking
delete()
object.
deleteCharAt() Deletes the character at the index specified by the loc.
ensureCapacity() Ensures capacity is at least equal to the given minimum.
insert() Inserts text at the specified index position.
length() Returns the length of the string.
reverse() Reverse the characters within a StringBuffer object.
Replace one set of characters with another set inside a
replace()
Wrapper Classes in Java

What Are Wrapper Classes in Java?


In Java, wrapper classes provide a way to use primitive data types like (int,
double, boolean, etc.) as objects. Since primitives are not objects, wrapper
classes wrap these primitives inside an object so they can be used where
objects are required, such as in collections like ArrayList.

list of Java primitive types and their corresponding wrapper classes:

int → Integer
double → Double
char → Character
boolean → Boolean
byte → Byte
short → Short
long → Long
float → Float
Autoboxing and Unboxing

Java automatically converts between primitives and their wrapper objects through a
feature called autoboxing and unboxing. Autoboxing is the automatic conversion of
a primitive to its wrapper object, while
unboxing is converting the wrapper back to a primitive.

Commonly Used Methods in Wrapper Classes


Wrapper classes come with useful methods. Here are some popular ones:

parseX(String s) — converts a string to a primitive (e.g., [Link]("123"))


valueOf(String s) — converts a string to a wrapper object (e.g.,
[Link]("true"))
toString() — converts the wrapper object to a string

Example:

String numberStr = "50";


int num = [Link](numberStr); // converts string to int

Boolean flag = [Link]("true"); // converts string to Boolean object

String str = num + ""; // converts int to string (simple concatenation)


Static method

Static method in Java is a method which belongs to the class and not
to the object. A static method can access only static data. It is a
method which belongs to the class and not to the object(instance). A
static method can access only static data. It cannot access non-
static data (instance variables).

A static method can call only other static methods and can not call a
non-static method from it.
A static method can be accessed directly by the class name and
doesn’t need any object
A static method cannot refer to "this" or "super" keywords in anyway

Syntax :
<class-name>.<method-name>
class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
[Link]("myMethod");
}

public static void main(String[] args)


{
/* You can see that we are calling this
* method without creating any object.
*/
myMethod(); }
}
Output
myMethod
Final Variables
-Declaring a variable with the final keyword makes that variable as
constant. Once we assign value to final variables, we cannot chnage
it again.

-We can also declare final local variables

- we can also have final object reference variable marked final can't
ever be reassigned to refer to a different object.
Eg final int a=100;
Final Methods
- the methods in the class can be declared as final. A method can be declared
final to prevent subclasses from overriding it. This the behaviour it implements
becomes unchangeble.

Eg: class A{
final void secure() {
[Link](" This is highly secure");
}
Void nonsecure{
[Link](" This is non secure superclass method") ;}
}
Class Demo extends A{
Void non secure() {
[Link](" This is non secure subclass") ;
}
}
Final Classes
- the key word final can also be used for classes. If we declare A class as final
then that class cannot be inherited. The final classes cannot be subclassed .
- if all the methods are highly secure and do not want anybody to override the
behavior then we can make entire class as final.
Typecasting
Typecasting is the process of converting one variable of certain datatype
into another datatype.

Types of casting: there are two types of casting, implicit Casting and
Explicit Casting . The implicit Casting is also called as automatic
conversion or widening conversion. The explicit casting is also called as
narrowing conversion.

Implicit Casting
Automatic casting done by the java compiler internally is called implicit
Casting. Implicit Casting is done to convert lower data type into a higher
data type.
● when one type of data is assigned to another type of variable an
automatic type conversion with take place if,
◆the two types are compatible
◆the destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For
example , the int type is always large enough to hold all valid byte values,
and both int and byte are integer types, so an automatic conversion from
byte to int can be applied .
For widening conversions the numeric types, integer and floating point
types are compatible with each other.
Eg int ¡;
float f;
¡=10;
f=¡; // assigned int to float
The implicit Casting rules are clearly understood
from the below diagram

byte -> short -> char -> int ->float-> long -


> double
In the above line it demonstratea that a byte can
be assigned to a shorter float,but a double cannot
be assigned to float or int.
class Test
{
public static void main(String[] args)
{
int i = 100;

// automatic type conversion


long l = i;

// automatic type conversion


float f = i;
[Link]("Int value "+i);
[Link]("Long value "+l);
[Link]("Float value "+f);
}
}

Output
Int value 100
Long value 100
Float value 100.0
Explicit Casting

The casting done by the programmer or developer is


called explicit Casting. Explicit Casting is must when
converting from a higher ata type to a lower data type.

General form. (datatypename)value;

In this form type name is the name of the datatype we


are converting to and value is an expression that results in
the value we want to convert.
Example:
1. double d=6.289;
int I =(int)d; // in the above code, the value of
double 6.289 is converted to int 6 and then assigned the
integer value 6 to I.
Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04; Output:
Double value 100.04
//explicit type casting Long value 100
long l = (long)d; Int value 100

//explicit type casting


int i = (int)l;
[Link]("Double value "+d);

//fractional part lost


[Link]("Long value "+l);

//fractional part lost


[Link]("Int value "+i);
}
}
This keyword
The keyword "this " refers to the current object. Whenever it is required to point an
object from functionality which is under execution then we use the "this " keyword.
It always points to an object that is executing the block in which this keyword is
present.

Uses of This Keyword.


The first use of this is to call constructor from another constructor, specifically one in
the current class. The second function is to avoid name space conflicts between a
methods parameter list and it's varibales.
Example
Class A{
int I, j;
A() {
this(100) ;
}
A(int a) {
this(a, 200) ;
}
A(int a, int b) {
I=a;
J=b;
}PSVM(string args[]){ A a1=new A(); }
}
• The process of calling the constructor from other constructors is called as
Constructor Chaining.
• The constructor call should be the first statement in the constructor. If
we are calling the constructor from other constructor using this, then this
should be the first statement in the constructor.

• One more use of this keyword is to resolve the name conflicts between
the method arguments and instance varibales. Let us assume that, we
have two instance variables called I and j. The constructor argument also
have the same name I and j. We want the constructor to set the values of
the argumnets to the instance varibales..
Class A{
int I, j;
A() {
}
A(int I, int j) {
I=I; // it is confusing which I is assigning to which i
J=J; // it is confusing, which j is assiging to which j
}
}
To avoid these conflicts, we can use this keyword as shown below.

Class A{
int i,j;
A() {
}
A(int i, int j) {
this.i=i; // it is confusing which I is assigning to which i
this.j=j; // it is confusing, which j is assiging to which j
}
}

Here this.i and this.j refers to instance variables and 'i' and 'j' refers
to method arguments
Class A{
int i, j;
Void function 1() {
int I=100;
[Link](i);
[Link](this.i) ;
}
}
Java Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.

Declaring Array Variables


To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array the
variable can reference. Here is the syntax for declaring an array
variable −
Syntax
dataType[] arrayRefVar; Eg: double[] myList;
Or or
dataType arrayRefVar[]; double myList[];
Creating Arrays
You can create an array by using the new operator with the
following syntax −
Syntax
arrayRefVar = new dataType[arraySize];

The above statement does two things −


It creates an array using new dataType[arraySize].
It assigns the reference of the newly created array to the variable
arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference
of the array to the variable can be combined in one statement, as shown
below −

dataType[] arrayRefVar = new dataType[arraySize]


int[] a = new int[3]{10,20,30};
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
int[] a ={10,20,30};

The array elements are accessed through the index. Array


indices starts from 0.
Example
Following statement declares an array variable, myList, creates an
array of 10 elements of double type and assigns its reference to
myList −

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten
double values and the indices are from 0 to 9.
Arrays can be either have all of their elements initialized at the
time of declaration or the elements can be individually initialized
after declaration.

1. Initializing array after declaration


Int[] a1=new int[5];
a1[0]=10;
a1[1]=20;
a1[2]=30;
a1[3]=40;
a1[4]=50;

2. Initializing array at the time of declaration.


Int[] numbers={10, 20,30,40,50};
Access the Elements of an Array

You access an array element by referring to the index number.


This statement accesses the value of the first element in cars:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link](cars[0]);
// Outputs Volvo

Change an Array Element


To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";

Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and use the
length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < [Link]; i++) {
[Link](cars[i]);
}

Loop Through an Array with For-Each


There is also a "for-each" loop, which is used exclusively to loop through
elements in arrays:
Syntax
for (type variable : arrayname) {
...
}

Eg : String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (String i : cars) {
[Link](i);
}
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays i.e each
element of a multi-dimensional array is another array. The representation of the
elements is in rows and columns. Thus, you can get a total number of elements in
a multidimensional array by multiplying row size with column size.

To create a two-dimensional array, add each array within its own set of curly
braces:

Data_Type[][] Array_Name = new int[Row_Size][Column_Size];Example


int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.


To access the elements of the myNumbers array, specify two indexes: one for the
array, and one for the element inside that array. This example accesses the third
element (2) in the second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
[Link](x); // Outputs 7

You might also like