SlideShare a Scribd company logo
Object Oriented Programming using JA
VA
Unit1 - Introduction to Java
1
Chapter 1- Java Fundamentals
2
The Origins of Java
3
 The Java programming language was developed in the early 1990s
by James Gosling and his team at Sun Microsystems.
 The project began in 1991 with the goal of creating a language that
would allow consumer electronics to communicate with each other.
 However, the team's focus quickly shifted to the World Wide
Web. The language was originally called Oak, but the name was
changed due to a trademark conflict and some copyright issues.
 Java was released in May 1995 as a core component of Sun's Java
platform.
 Java is a general-purpose language that's primarily used for
internet-based applications.
The Origins of Java
4
 As you can probably guess, many different types of CPUs are used
as controllers. The trouble with C and C++ (and most other
languages) is that they are designed to be compiled for a specific
target.
 Although it is possible to compile a C++ program for just about any
type of CPU, to do so requires a full C++ compiler targeted for that
CPU.
 The problem is that compilers are expensive and time consuming to
create.
The Origins of Java
5
 An easier—and more cost-efficient—solution was needed.
 In an attempt to find such a solution, Gosling and others began
work on a portable, platform independent language that could
be used to produce code that would run on a variety of CPUs
under differing environments.
 This effort ultimately led to the creation of Java.
The Origins of Java
6
 The principles for creating Java programming were "Simple,
Robust, Portable, Platform-independent, Secured, High
Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
 Java was developed by James Gosling, who is known as the father of
Java, in 1995.
 James Gosling and his team members started the project in the
early '90s.
Java’s Lineage: C and C++
7
 The two languages that form Java’s closest ancestors are C and C++.
As you may know, C and C++ are among the most important computer
languages ever invented, and are still in widespread use today.
 From C, Java inherits its syntax.
 Java’s object model is adapted from C++. Java’s relationship to C and C+
+ is important for a number of reasons.
 First, at the time of Java’s creation, many programmers were familiar with
the C/C++ syntax. Because Java uses a similar syntax, it was
relatively easy for a C/C++ programmer to learn Java.
 This made it possible for Java to be readily utilized by the pool of existing
programmers, thus facilitating Java’s acceptance by the programming
community.
Java’s Lineage: C and C++
8
 The modern age of programming began with C.
 It moved to C++, and then to Java.
 By inheriting and building upon that rich heritage, Java provides a
powerful, logically consistent programming environment that takes
the best of the past and adds new features.
Java’s Lineage: C and C++
9
 Perhaps most important, because of their similarities, C, C++, and
Java define a common, conceptual framework for the professional
programmer.
 Programmers do not face major rifts when switching from one
language to another.
 C++ and Java are related, especially in their support for object-
oriented programming, Java is not simply the ―Internet version of
C++.
 Java has significant practical and philosophical differences from
C++.
How Java Impacted the Internet
10
 Java has impacted the internet in many ways, including:
 Dynamic web applications: Java's applet technology allowed
developers to create interactive websites by running small programs
within web browsers.
 Server-side technologies: Java served as the foundation for
JavaServer Pages (JSP) and Java Servlets, which enabled the
creation of dynamic and scalable web applications.
 Portability and security: Java addressed portability and security
issues.
 Platform independence: Java's ability to run on any platform made
it possible to develop machine learning and AI applications that can
run on any operating system.
How Java Impacted the Internet
11
 Applet innovation: The applet is a special type of Java program that
is designed to be transmitted over the Internet and automatically
executed by a Java-compatible web browser.
 Simplifying web programming: Java simplified web programming.
 HotJava: The first application program written in Java was HotJava,
a browser to run the applet on Internet.
Java’s Magic: The Bytecode
12
 Byte Code can be defined as an intermediate code generated by the
compiler after the compilation of source code(JAVA Program).
 This intermediate code makes Java a platform-independent
language.
 Java bytecode is the instruction set for the Java Virtual Machine.
 Java bytecode is the machine code in the form of a .class file.
 With the help of java bytecode we achieve platform independence in
java.
Java’s Magic: The Bytecode
13
 How does it works?
 When we write a program in Java, firstly, the compiler compiles
that program and a bytecode is generated for that piece of code.
 After the first compilation, the bytecode generated is now run by
the Java Virtual Machine.
 This essentially means that we only need to have basic java
installation on any platforms that we want to run our code on.
 Resources required to run the bytecode are made available by
theJava Virtual Machine, which calls the processor to allocate the
required resources.
 JVM's are stack-based so they stack implementation to read the
codes.
Java’s Magic: The Bytecode
14
Java’s Magic: The Bytecode
15
 Translating a Java program into bytecode makes it much easier
to run a program in a wide variety of environments because
only the JVM needs to be implemented for each platform.
 Once the runtime package exists for a given system, any Java
program can run on it.
 Remember, although the details of the JVM will differ from platform
to platform, all understand the same Java bytecode.
Moving Beyond Applets
16
 In the early years of Java, applets were a crucial part of Java
programming.
 They not only added excitement to a web page, they were a
highly visible part of Java.
 However, applets rely on a Java browser plug-in. Thus, for an
applet to work, the browser must support it.
 Recently, support for the Java browser plug-in has been
waning. Simply put, without browser support, applets are not
viable.
Moving Beyond Applets
17
 Because of this, beginning with JDK 9, Java’s support for applets
has been deprecated.
 In thelanguage of Java, deprecated means that a feature is
still available but flagged as obsolete.
 A deprecated feature is subject to removal in a future release.
Thus, deprecated features should not be used for new code.
 Various alternatives to applets are in place, with arguably the
most important being Java Web Start.
Moving Beyond Applets
18
 Java Web Start enables an application to be dynamically
downloaded from a web page.
 The difference is that the application runs on its own, not inside
the browser.
 Thus, it does not rely on the Java plug-in.
 Java Web Start is a deployment mechanism that works with
many types of Java programs.
The Java Buzzwords
19
The Java Buzzwords
20
 Simple:- Java was designed to be easy for the professional
programmer to learn and use effectively.
 If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier.
 If you are an experienced C++ programmer, moving to Java
will require very little effort.
 Because Java inherits the C/C++ syntax and many of the
object-oriented features of C++, most programmers have little
trouble learning Java.
The Java Buzzwords
21
 Secure: Java provides a firewall between a networked application
and your computer.
 When a Java Compatible Web browser is used, downloading can
be done safely without fear of viral infection or malicious intent.
 Java achieves this protection by confining a Java program to the
java execution environment and not allowing it to access other
parts of the computer.
The Java Buzzwords
22
 Portable :- Java is portable because it facilitates you to carry
the Java bytecode to any platform. It doesn't require any
implementation.
 Object-Oriented:- The object model in Java is simple and easy to
extend, while primitive types, such as integers, are kept as high
performance non objects.
 Java is an object oriented language.
 It supports various object oriented features like class, object,
encapsulation, polymorphism, inheritance, abstraction, etc.
The Java Buzzwords
23
 Robust:- Robust simply means reliable.
 Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 Java provides automatic garbage collection which runs on the
Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
 There are exception handling and the type checking mechanism
in Java. All these points make Java robust.
The Java Buzzwords
24
 Multithreaded:- Java was designed to meet the real-world
requirement of creating interactive, networked programs.
 To accomplish this, Java supports multithreaded programming,
which allows you to write programs that do many things
simultaneously.
 The Java run-time system comes with an elegant yet sophisticated
solution for multiprocess synchronization that enables you to
construct smoothly running interactive systems.
 Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
 Java Multithreading is mostly used in games, animation, etc.
The Java Buzzwords
25
 Advantages of Java Multithreading
1. We can perform many operations together, so it saves time.
2. Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
The Java Buzzwords
26
 Architecture neutral:- It means the java program can be run on
any processor irrespective of its vendor and architecture. so it
avoids rebuilding problem.
 In short, Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
 Question:- Why is java is considered an architecture – neutral language?
 Answer:- It can run on many different CPUs with only one compilation.
 Example:- Android Studio using Java.
The Java Buzzwords
27
 Interpreted:- Java can be considered both a compiled and an
interpreted language because its source code is first compiled into a
binary byte-code.
 This byte-code runs on the Java Virtual Machine (JVM), which
is usually a software-based interpreter.
 However, it isn't clear whether Java is compiled or interpreted. It
neither generates machine code after compiling a source file nor
interpreted the source file to execute code instructions line by line.
 The performance of Java is impressive for an interpreted language
because of its intermediate bytecode.
The Java Buzzwords
28
 High performance:- Java provides high performance with the use of
JIT – Just In Time compiler, in which the compiler compiles the
code on-demand basis, that is, it compiles only that method which is
being called.
 This saves time and makes it more efficient.
 Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code.
 Bytecodes generated by the Java compiler are highly optimized, so
Java Virtual Machine can execute them much faster.
The Java Buzzwords
29
 Distributed:- Java is distributed because it encourages users to
create distributed applications.
 In Java, we can split a program into many parts and store these
parts on different computers. A Java programmer sitting on a
machine can access another program running on the other machine.
 This feature in Java gives the advantage of distributed programming,
which is very helpful when we develop large projects. Java helps us
to achieve this by providing the concept of RMI (Remote Method
Invocation) and EJB (Enterprise JavaBeans).
 This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
The Java Buzzwords
30
 Java comes with an extensive library of classes for interacting, using
TCP/IP protocols such as HTTP and FTP, which makes creating
network connections much easier than in C/C++.
 It also enables multiple programmers at many locations to work
together on a single project.
The Java Buzzwords
31
 Dynamic:- Java is dynamic and extensible means with the help of
OOPs, we can add classes and add new methods to classes, creating
new classes through subclasses. This makes it easier for us to expand
our own classes and even modify them.
 Java gives the facility of dynamically linking new class libraries,
methods, and objects. It is highly dynamic as it can adapt to its
evolving environment.
Object-Oriented Programming
32
 As the name suggests, Object-oriented programming or OOPS refers
to languages that use objects in programming.
 Object-oriented programming aims to implement real-world
entities like inheritance, hiding, polymorphism etc. in programming.
 The main aim of OOP is to bind together the data and the
functions that operate on them, so that no other part of the code
can access this data except that function.
 To support the principles of object-oriented programming, all OOP
languages, including Java, have three traits in common:
encapsulation, polymorphism, and inheritance.
Object-Oriented Programming
33
 Object-oriented programming took the best ideas of structured
programming and combined them with several new concepts. The
result was a different way of organizing a program.
1. Encapsulation:- Encapsulation is defined as the wrapping up
of data under a single unit.
• It is the mechanism that binds together code and the data it
manipulates.
• Another way to think about encapsulation is that, it is a
protective shield that prevents the data from being accessed by the
code outside this shield.
Object-Oriented Programming
34
 As in encapsulation, the data in a class is hidden from other
classes using the data hiding concept which is achieved by
making the members or methods of a class private, and the
class is exposed to the end-user or the world without providing
any details behind implementation using the abstraction concept,
so it is also known as a combination of data-hiding and
abstraction.
 In below example all the three data members (or data fields) are
private which cannot be accessed directly.
 These fields can be accessed via public methods only. Fields
empName, ssn and empAge are made hidden data fields using
Object-Oriented Programming
35
Object-Oriented Programming
36
Object-Oriented Programming
37
2. Polymorphism:- The word polymorphism is made of two
words - poly and morph, where poly means many and morph
means forms.
 Polymorphism is one of the OOPs feature that allows us to perform
a single action in different ways.
 For example, lets say we have a class Helper that has a method
Multiply().
Object-Oriented Programming
 Now lets say we
have two methods in
same class.
 We can provide the
implementation to the
same method like
this:
38
class Helper
{
static int Multiply(int a, int b)
{
return a * b;
}
static double Multiply(double a, double b)
{
return a * b;
}
}
class My
{
public static void main(String[] args)
{
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
Object-Oriented Programming
39
 Inheritance:- Inheritance is the process by which one object
can acquire the properties of another object. This is important
because it supports the concept of hierarchical classification.
 We group the "inheritance concept" into two categories:
1. subclass (child) - the class that inherits from another class
2. superclass (parent) - the class being inherited from
 To inherit from a class, use the extends keyword.
 In the example below, the Programmer class (subclass) inherits the
attributes and methods from the Employee class (superclass):
Object-Oriented Programming
40
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
Obtaining the Java Development Kit
41
 The Java Development Kit (JDK) is a cross-platform software
development environment that offers a collection of tools and
libraries necessary for developing Java-based software
applications and applets.
 It is a core package used in Java, along with the JVM(Java
Virtual Machine) and the JRE (Java Runtime Environment).
 Beginners often get confused with JRE and JDK, if you are only
interested in running Java programs on your machine then you
can easily do it using Java Runtime Environment.
 However, if you would like to develop a Java-based software
application then along with JRE, you may need some additional
necessary tools, which is called JDK.
Obtaining the Java Development Kit
 The JDK has a private Java Virtual Machine (JVM) and a few
other resources necessary for the development of a Java Application.
 JDK contains:
 Java Runtime Environment (JRE),
 An interpreter/loader (Java),
 A compiler (javac),
 An archiver (jar) and many more.
42
Obtaining the Java Development Kit
43
 Installation of JDK:
 Go to this Oracle’s official Download Page through this link
: https://www.oracle.com/in/java/technologies/
 Select the latest JDK version and click Download and add it
to your classpath.
 Just check the JDK software is installed or not on your computer at the correct
location, for example, at C:Program FilesJavajdk11.0.9.
 Compile and Run Java Code using JDK:
 You can use the JDK compiler to convert your Java text file into
an executable program. Your Java text segment is converted into
bytecode after compilation which carries the .class extension.
 First, create a Java text file and save it using a name. Here we are saving
the file as Hello.java.
The First Sample Program
 After that just simply use
the javac command,
which is used for the
compilation purpose in
Java.
 You can notice now that
the Hello.class file is
being created in the same
directory as Hello.java.
44
A First Simple Program
45
 You will follow these three steps:
1. Write the program.
2. Compile the program.
3. Run the program.
 Comment:- Java lets you enter a remark into a program’s source file.
 The contents of a comment are ignored by the compiler.
 Instead, a comment describes or explains the operation of the
program to anyone who is reading its source code.
Comments in Java
46
 Java supports three styles of comments.
1. Single-line comment:- A single-line comment begins with a // and
ends at the end of the line. As a general rule, programmers use
multiline comments for longer remarks and single-line comments for
brief, line- byline descriptions.
2. Multiline comment:- This type of comment must begin with /* and
end with */. Anything between these two comment symbols is ignored
by the compiler.
3. Documentation comments:- There is another type of multi-line comment
available in Java. For this, we use the /** and */ to enclose
documentation comments. This is used for defining formal
documentation APIs for your programs that are created by the javadoc
tool.
The First Sample Program Line by Line
47
 Class keyword is used to declare that a new class is being
defined.
 As mentioned, the class is Java’s basic unit of encapsulation.
 Hello is the name of the class in above example.
 The class definition begins with the opening curly brace ({) and
ends with the closing curly brace (}).
 The elements between the two braces are members of the class.
The First Sample Program Line by Line
48
 As mentioned earlier, in Java, a subroutine is called a method , this is the
line at which the program will begin executing. In general,
Java applications begin execution by calling main( ).
 The public keyword is an access modifier. An access modifier
determines how other parts of the program can access the members of the
class. When a class member is preceded by public, then that member
can be accessed by code outside the class in which it is declared.
 The keyword static allows main( ) to be called before an object of the
class has been created. This is necessary because main( ) is called by the
JVM before any objects are made.
 The keyword void simply tells the compiler that main( ) does not
return a value.
The First Sample Program Line by Line
49
 In main( ) there is only one parameter, String args[], which declares
a parameter named args. This is an array of objects of type
String. (Arrays are collections of similar objects.) Objects of type
String store sequences of characters. In this case, args receives
any command-line arguments present when the program is
executed.
 Output is actually accomplished by the built-in println( ) method.
In this case, println( ) displays the string that is passed to it.
 The line begins with System.out. System is a predefined class that
provides access to the system, and out is the output stream that
is connected to the console. Thus, System.out is an object
that encapsulates console output.
Handling Syntax Errors
50
 If you enter something incorrectly into your program, the compiler
will report a syntax error message when it tries to compile it.
 The Java compiler attempts to make sense out of your source code
no matter what you have written.
 For this reason, the error that is reported may not always reflect
the actual cause of the problem.
 In the preceding program, for example, an accidental omission of
the opening curly brace after the main( ) method causes the
compiler to report errors.
A Second Simple Program
51
A Second Simple Program
52
A Second Simple Program
53
 The following line of code assigns var1 the value 1024:
var1 = 1024; // this assigns 1024 to var1
 In Java, the assignment operator is the single equal sign. It copies the
value on its right side into the variable on its left.
 The next line of code outputs the value of var1 preceded by
the string "var1 contains ": System.out.println("var1 contains " +
var1);
 In this statement, the plus sign causes the value of var1 to
be displayed after the string that precedes it.
A Second Simple Program
54
 The next line of code assigns var2 the value of var1 divided by 2:
var2 = var1 / 2;
 This line divides the value in var1 by 2 and then stores that result in
var2. Thus, after the line executes, var2 will contain the value 512.
 Here are the next two lines in the program:
System.out.print("var2 contains var1 / 2:
"); System.out.println(var2);
 print( ) and println( ) can be used to output values of any of
Java’s built-in types.
Data Types
55
 In the preceding program, a variable of type int was used. However,
a variable of type int can hold only whole numbers.
 Thus, it cannot be used when a fractional component is required. For
example, an int variable can hold the value 18, but not the value
18.3. Fortunately, int is only one of several data types defined by
Java.
 To allow numbers with fractional components, Java defines two
floating-point types: float and double, which represent single- and
double-precision values, respectively.
Data Types
56
 Of the two, double is the most commonly used.
 To declare a variable of type double, use a statement similar to that
shown here: double x;
 Here, x is the name of the variable, which is of type double. Because
x has a floating-point type, it can hold values such as 122.23, 0.034,
or –19.0.
Control Statements (The if Statement)
 The Java if statement is the most simple decision-making statement.
It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.
1. Java if (if-then) Statement:-
 The syntax of an if-then statement is:
57
Control Statements (The if Statement)
 Here, condition is a boolean expression such as age >= 18.
 if condition evaluates to true, statements are executed
 if condition evaluates to false, statements are skipped
58
Control Statements (The if Statement)
 In the program, number < 0 is false. Hence, the code inside the body of the if
statement is skipped.
59
Control Statements (The if Statement)
 In the above example, we are comparing two strings in the if block.
60
Control Statements (The if-then-else
Statement)
 Java if...else (if-then-else) Statement:-
 The if statement executes a certain section of code if the test
expression is evaluated to true. However, if the test expression is
evaluated to false, it does nothing.
 In this case, we can use an optional else block. Statements inside the
body of else block are executed if the test expression is evaluated to
false. This is known as the if-...else statement in Java.
 The syntax of the if...else statement is:
61
Control Statements (The if-then-else
Statement)
 Here, the program will do one task (codes inside if block) if the
condition is true and another task (codes inside else block) if the
condition is false.
62
Control Statements (The if-then-else
Statement)
63
Control Statements (The if-then-else
Statement)
 In the above example, we have a variable named number. Here, the
test expression number > 0 checks if number is greater than 0.
 Since the value of the number is 10, the test expression evaluates to
true. Hence code inside the body of if is executed.
 Now, change the value of the number to a negative integer. Let's say
-5.
 If we run the program with the new value of number, the output will
be:
 Here, the value of number is -5. So the test expression evaluates to
false. Hence code inside the body of else is executed.
64
Control Statements (if...else...if Statement)
 In Java, we have an if...else...if ladder, that can be used to execute
one block of code among multiple other blocks.
 Here, if statements are executed from the
top towards the bottom. When the test
condition is true, codes inside the body of
that if block is executed. And, program
control jumps outside the if...else...if ladder.
 If all test expressions are false, codes inside
the body of else are executed.
65
Control Statements (if...else...if Statement)
66
Control Statements (if...else...if Statement)
67
Control Statements (if...else...if Statement)
68
 In the above example, we are checking whether number is positive,
negative, or zero. Here, we have two condition expressions:
 number > 0 - checks if number is greater than 0
 number < 0 - checks if number is less than 0
 Here, the value of number is 0. So both the conditions
evaluate to false.
 Hence the statement inside the body of else is executed.
Operators
 Java defines a full complement of relational operators that may
be used in a conditional expression. They are shown here:
69
The for Loop
 You can repeatedly execute a sequence of code by creating a loop.
Loops are used whenever you need to perform a repetitive task
because they are much simpler and easier than trying to write the
same statement sequence over and over again. Java supplies a
powerful assortment of loop constructs. The one we will look at here
is the for loop.
 Java for loop is used to run a block of code for a certain number of
times. The syntax of for loop is:
70
The for Loop
 Here,
1. The initialExpression initializes and/or
declares variables and executes only once.
2. The condition is evaluated. If the condition
is true, the body of the for loop is
executed.
3. The updateExpression updates the value of
initialExpression.
4. The condition is evaluated again. The
process continues until the condition is
false.
71
The for Loop
72
The for Loop
 Here is how this program works.

73
The for Loop
74
The for Loop
 Here is how the program works.
75
Create Blocks of Code
76
 Another key element of Java is the code block. A code block
is a grouping of two or more statements.
 This is done by enclosing the statements between opening
and closing curly braces.
 Once a block of code has been created, it becomes a logical unit that
can be used any place that a single statement can.
Create Blocks of Code
 For example,
77
Create Blocks of Code
 In the above example, we have a block if {....}.
 Here, inside the block we have two statements:
 System.out.print("Hey ");
 System.out.print("Jude!");
 However, a block may not have any statements. Consider
the following examples,
 This is a valid Java program.
 Here, we have a block if {...}.
 However, there is no any statement
inside this block.
78
Create Blocks of Code
 Here, we have block public static void main() {...}. However, similar
to the above example, this block does not have any statement.
79
Semicolons and Positioning
80
 In Java, the semicolon is a separator. It is often used to terminate a statement. In
essence, the semicolon indicates the end of one logical entity.
 As you know, a block is a set of logically connected statements that are
surrounded by opening and closing braces. A block is not terminated with a
semicolon. Instead, the end of the block is indicated by the closing brace.
 Java does not recognize the end of the line as a terminator. For this reason, it
does not matter where on a line you put a statement. For example,
 x = y;
 y = y + 1;
 System.out.println(x + " " + y);
 is the same as the following, to Java:
 x = y; y = y + 1; System.out.println(x + " " + y);
Semicolons and Positioning
 Furthermore, the individual elements of a statement can also be put
on separate lines. For example, the following is perfectly acceptable:
 Breaking long lines in this fashion is often used to make programs
more readable. It can also help prevent excessively long lines from
wrapping.
81
Indentation Practices
82
 In programming, indentation is just like formatting. It is used to
make the code readable to other users because it makes the code
easier to edit, displays how the braces match up, and shows the logic
of the program in well-organized fashion.
 It signals to the reader that he/ she is about to dive into another a new
section of a program.
 The goal of the indentation is to show the logic of the program. We
must keep indentation throughout the program because it is an
essential part of formatting.
Indentation Practices
 Remember that the function of indentation is to make the program
more readable and understandable that saves an immense amount of
time when editing or refining the code.
83
The Java Keywords
 Keywords are predefined, reserved words used in Java programming
that have special meanings to the compiler. For example:
 Here, int is a keyword. It indicates that the variable score is of
integer type (32-bit signed two's complement integer).
 You cannot use keywords like int, for, class, etc as variable name (or
identifiers) as they are part of the Java programming language
syntax. Here's the complete list of all keywords in Java
programming.
84
The Java Keywords
85
The Java Keywords
86
 The keywords const and goto are reserved but not used. In the early
days of Java, several other keywords were reserved for possible
future use.
 In addition to the keywords, Java reserves the following: true, false,
and null.
 These are values defined by Java. You may not use these words for
the names of variables, classes, and so on.
Identifiers in Java
 Identifiers are the name given to variables, classes, methods, etc.
Consider the above code;
 Here, score is a variable (an identifier). You cannot use keywords as
variable names. It's because keywords have predefined meanings.
For example,
 The above code is wrong. It's because float is a keyword and cannot
be used as a variable name.
87
Identifiers in Java
88
 Rules for Naming an Identifier:-
1. Identifiers cannot be a keyword.
2. Identifiers are case-sensitive.
3. It can have a sequence of letters and digits. However, it must begin with a
letter, $ or _. The first letter of an identifier cannot be a digit.
4. It's a convention to start an identifier with a letter rather and $ or _.
5. Whitespaces are not allowed.
6. Similarly, you cannot use symbols such as @, #, and so on.
Identifiers in Java
89
 Here are some valid identifiers:
 score
 level
 highestScore
 number1
 convertToString
 Here are some invalid identifiers:
 class
 float
 1number
 highest Score
 @pple
The Java Class Libraries
90
 The sample programs shown in this chapter make use of two of
Java’s built-in methods: println( ) and print( ).
 These methods are accessed through System.out.
 System is a class predefined by Java that is automatically included in
your programs.
 In the larger view, the Java environment relies on several built-in
class libraries that contain many built-in methods that provide
support for such things as I/O, string handling, networking, and
graphics.

More Related Content

Similar to Unit1- OOPJ Chapter-1 Object Oriented Programming JAVA.pptx (20)

PPTX
Java Lecture 1
Qualys
 
PPTX
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
PPTX
Object Oriented concept-JAVA-Module-1-PPT.pptx
ASHWINIGOWDA46
 
PPT
Core Java Slides
Vinit Vyas
 
PPTX
1 java introduction
abdullah al mahamud rosi
 
PPTX
1 java intro
abdullah al mahamud rosi
 
PPTX
Java
seenak
 
PPTX
1.Intro--Why Java.pptx
YounasKhan542109
 
PPTX
Java
Snehal Shahane
 
PPTX
Chapter-1 Introduction.pptx
SumanBhandari40
 
PPTX
UNIT 1 Programming in java Bsc program.pptx
jijinamt
 
PPT
Java-Unit-I.ppt
RameswarGprec
 
PPT
Chapter 1 introduction to java technology
sshhzap
 
PPTX
Java (1)
Samraiz Tejani
 
PDF
Java Evolution-2.pdf
kumari36
 
PPT
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
PPT
PPS Java Overview Unit I.ppt
CDSukte
 
PPT
PPS Java Overview Unit I.ppt
RajeshSukte1
 
DOCX
Srgoc java
Gaurav Singh
 
Java Lecture 1
Qualys
 
JAVA ALL 5 MODULE NOTES.pptx
DrPreethiD1
 
Object Oriented concept-JAVA-Module-1-PPT.pptx
ASHWINIGOWDA46
 
Core Java Slides
Vinit Vyas
 
1 java introduction
abdullah al mahamud rosi
 
Java
seenak
 
1.Intro--Why Java.pptx
YounasKhan542109
 
Chapter-1 Introduction.pptx
SumanBhandari40
 
UNIT 1 Programming in java Bsc program.pptx
jijinamt
 
Java-Unit-I.ppt
RameswarGprec
 
Chapter 1 introduction to java technology
sshhzap
 
Java (1)
Samraiz Tejani
 
Java Evolution-2.pdf
kumari36
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
PPS Java Overview Unit I.ppt
CDSukte
 
PPS Java Overview Unit I.ppt
RajeshSukte1
 
Srgoc java
Gaurav Singh
 

Recently uploaded (20)

PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Ad

Unit1- OOPJ Chapter-1 Object Oriented Programming JAVA.pptx

  • 1. Object Oriented Programming using JA VA Unit1 - Introduction to Java 1
  • 2. Chapter 1- Java Fundamentals 2
  • 3. The Origins of Java 3  The Java programming language was developed in the early 1990s by James Gosling and his team at Sun Microsystems.  The project began in 1991 with the goal of creating a language that would allow consumer electronics to communicate with each other.  However, the team's focus quickly shifted to the World Wide Web. The language was originally called Oak, but the name was changed due to a trademark conflict and some copyright issues.  Java was released in May 1995 as a core component of Sun's Java platform.  Java is a general-purpose language that's primarily used for internet-based applications.
  • 4. The Origins of Java 4  As you can probably guess, many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target.  Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU.  The problem is that compilers are expensive and time consuming to create.
  • 5. The Origins of Java 5  An easier—and more cost-efficient—solution was needed.  In an attempt to find such a solution, Gosling and others began work on a portable, platform independent language that could be used to produce code that would run on a variety of CPUs under differing environments.  This effort ultimately led to the creation of Java.
  • 6. The Origins of Java 6  The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object- Oriented, Interpreted, and Dynamic".  Java was developed by James Gosling, who is known as the father of Java, in 1995.  James Gosling and his team members started the project in the early '90s.
  • 7. Java’s Lineage: C and C++ 7  The two languages that form Java’s closest ancestors are C and C++. As you may know, C and C++ are among the most important computer languages ever invented, and are still in widespread use today.  From C, Java inherits its syntax.  Java’s object model is adapted from C++. Java’s relationship to C and C+ + is important for a number of reasons.  First, at the time of Java’s creation, many programmers were familiar with the C/C++ syntax. Because Java uses a similar syntax, it was relatively easy for a C/C++ programmer to learn Java.  This made it possible for Java to be readily utilized by the pool of existing programmers, thus facilitating Java’s acceptance by the programming community.
  • 8. Java’s Lineage: C and C++ 8  The modern age of programming began with C.  It moved to C++, and then to Java.  By inheriting and building upon that rich heritage, Java provides a powerful, logically consistent programming environment that takes the best of the past and adds new features.
  • 9. Java’s Lineage: C and C++ 9  Perhaps most important, because of their similarities, C, C++, and Java define a common, conceptual framework for the professional programmer.  Programmers do not face major rifts when switching from one language to another.  C++ and Java are related, especially in their support for object- oriented programming, Java is not simply the ―Internet version of C++.  Java has significant practical and philosophical differences from C++.
  • 10. How Java Impacted the Internet 10  Java has impacted the internet in many ways, including:  Dynamic web applications: Java's applet technology allowed developers to create interactive websites by running small programs within web browsers.  Server-side technologies: Java served as the foundation for JavaServer Pages (JSP) and Java Servlets, which enabled the creation of dynamic and scalable web applications.  Portability and security: Java addressed portability and security issues.  Platform independence: Java's ability to run on any platform made it possible to develop machine learning and AI applications that can run on any operating system.
  • 11. How Java Impacted the Internet 11  Applet innovation: The applet is a special type of Java program that is designed to be transmitted over the Internet and automatically executed by a Java-compatible web browser.  Simplifying web programming: Java simplified web programming.  HotJava: The first application program written in Java was HotJava, a browser to run the applet on Internet.
  • 12. Java’s Magic: The Bytecode 12  Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code(JAVA Program).  This intermediate code makes Java a platform-independent language.  Java bytecode is the instruction set for the Java Virtual Machine.  Java bytecode is the machine code in the form of a .class file.  With the help of java bytecode we achieve platform independence in java.
  • 13. Java’s Magic: The Bytecode 13  How does it works?  When we write a program in Java, firstly, the compiler compiles that program and a bytecode is generated for that piece of code.  After the first compilation, the bytecode generated is now run by the Java Virtual Machine.  This essentially means that we only need to have basic java installation on any platforms that we want to run our code on.  Resources required to run the bytecode are made available by theJava Virtual Machine, which calls the processor to allocate the required resources.  JVM's are stack-based so they stack implementation to read the codes.
  • 14. Java’s Magic: The Bytecode 14
  • 15. Java’s Magic: The Bytecode 15  Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform.  Once the runtime package exists for a given system, any Java program can run on it.  Remember, although the details of the JVM will differ from platform to platform, all understand the same Java bytecode.
  • 16. Moving Beyond Applets 16  In the early years of Java, applets were a crucial part of Java programming.  They not only added excitement to a web page, they were a highly visible part of Java.  However, applets rely on a Java browser plug-in. Thus, for an applet to work, the browser must support it.  Recently, support for the Java browser plug-in has been waning. Simply put, without browser support, applets are not viable.
  • 17. Moving Beyond Applets 17  Because of this, beginning with JDK 9, Java’s support for applets has been deprecated.  In thelanguage of Java, deprecated means that a feature is still available but flagged as obsolete.  A deprecated feature is subject to removal in a future release. Thus, deprecated features should not be used for new code.  Various alternatives to applets are in place, with arguably the most important being Java Web Start.
  • 18. Moving Beyond Applets 18  Java Web Start enables an application to be dynamically downloaded from a web page.  The difference is that the application runs on its own, not inside the browser.  Thus, it does not rely on the Java plug-in.  Java Web Start is a deployment mechanism that works with many types of Java programs.
  • 20. The Java Buzzwords 20  Simple:- Java was designed to be easy for the professional programmer to learn and use effectively.  If you already understand the basic concepts of object-oriented programming, learning Java will be even easier.  If you are an experienced C++ programmer, moving to Java will require very little effort.  Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.
  • 21. The Java Buzzwords 21  Secure: Java provides a firewall between a networked application and your computer.  When a Java Compatible Web browser is used, downloading can be done safely without fear of viral infection or malicious intent.  Java achieves this protection by confining a Java program to the java execution environment and not allowing it to access other parts of the computer.
  • 22. The Java Buzzwords 22  Portable :- Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.  Object-Oriented:- The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high performance non objects.  Java is an object oriented language.  It supports various object oriented features like class, object, encapsulation, polymorphism, inheritance, abstraction, etc.
  • 23. The Java Buzzwords 23  Robust:- Robust simply means reliable.  Java is robust because:  It uses strong memory management.  There is a lack of pointers that avoids security problems.  Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.  There are exception handling and the type checking mechanism in Java. All these points make Java robust.
  • 24. The Java Buzzwords 24  Multithreaded:- Java was designed to meet the real-world requirement of creating interactive, networked programs.  To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously.  The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems.  Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.  Java Multithreading is mostly used in games, animation, etc.
  • 25. The Java Buzzwords 25  Advantages of Java Multithreading 1. We can perform many operations together, so it saves time. 2. Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
  • 26. The Java Buzzwords 26  Architecture neutral:- It means the java program can be run on any processor irrespective of its vendor and architecture. so it avoids rebuilding problem.  In short, Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.  Question:- Why is java is considered an architecture – neutral language?  Answer:- It can run on many different CPUs with only one compilation.  Example:- Android Studio using Java.
  • 27. The Java Buzzwords 27  Interpreted:- Java can be considered both a compiled and an interpreted language because its source code is first compiled into a binary byte-code.  This byte-code runs on the Java Virtual Machine (JVM), which is usually a software-based interpreter.  However, it isn't clear whether Java is compiled or interpreted. It neither generates machine code after compiling a source file nor interpreted the source file to execute code instructions line by line.  The performance of Java is impressive for an interpreted language because of its intermediate bytecode.
  • 28. The Java Buzzwords 28  High performance:- Java provides high performance with the use of JIT – Just In Time compiler, in which the compiler compiles the code on-demand basis, that is, it compiles only that method which is being called.  This saves time and makes it more efficient.  Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code.  Bytecodes generated by the Java compiler are highly optimized, so Java Virtual Machine can execute them much faster.
  • 29. The Java Buzzwords 29  Distributed:- Java is distributed because it encourages users to create distributed applications.  In Java, we can split a program into many parts and store these parts on different computers. A Java programmer sitting on a machine can access another program running on the other machine.  This feature in Java gives the advantage of distributed programming, which is very helpful when we develop large projects. Java helps us to achieve this by providing the concept of RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans).  This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • 30. The Java Buzzwords 30  Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as HTTP and FTP, which makes creating network connections much easier than in C/C++.  It also enables multiple programmers at many locations to work together on a single project.
  • 31. The Java Buzzwords 31  Dynamic:- Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and even modify them.  Java gives the facility of dynamically linking new class libraries, methods, and objects. It is highly dynamic as it can adapt to its evolving environment.
  • 32. Object-Oriented Programming 32  As the name suggests, Object-oriented programming or OOPS refers to languages that use objects in programming.  Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc. in programming.  The main aim of OOP is to bind together the data and the functions that operate on them, so that no other part of the code can access this data except that function.  To support the principles of object-oriented programming, all OOP languages, including Java, have three traits in common: encapsulation, polymorphism, and inheritance.
  • 33. Object-Oriented Programming 33  Object-oriented programming took the best ideas of structured programming and combined them with several new concepts. The result was a different way of organizing a program. 1. Encapsulation:- Encapsulation is defined as the wrapping up of data under a single unit. • It is the mechanism that binds together code and the data it manipulates. • Another way to think about encapsulation is that, it is a protective shield that prevents the data from being accessed by the code outside this shield.
  • 34. Object-Oriented Programming 34  As in encapsulation, the data in a class is hidden from other classes using the data hiding concept which is achieved by making the members or methods of a class private, and the class is exposed to the end-user or the world without providing any details behind implementation using the abstraction concept, so it is also known as a combination of data-hiding and abstraction.  In below example all the three data members (or data fields) are private which cannot be accessed directly.  These fields can be accessed via public methods only. Fields empName, ssn and empAge are made hidden data fields using
  • 37. Object-Oriented Programming 37 2. Polymorphism:- The word polymorphism is made of two words - poly and morph, where poly means many and morph means forms.  Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways.  For example, lets say we have a class Helper that has a method Multiply().
  • 38. Object-Oriented Programming  Now lets say we have two methods in same class.  We can provide the implementation to the same method like this: 38 class Helper { static int Multiply(int a, int b) { return a * b; } static double Multiply(double a, double b) { return a * b; } } class My { public static void main(String[] args) { System.out.println(Helper.Multiply(2, 4)); System.out.println(Helper.Multiply(5.5, 6.3)); } }
  • 39. Object-Oriented Programming 39  Inheritance:- Inheritance is the process by which one object can acquire the properties of another object. This is important because it supports the concept of hierarchical classification.  We group the "inheritance concept" into two categories: 1. subclass (child) - the class that inherits from another class 2. superclass (parent) - the class being inherited from  To inherit from a class, use the extends keyword.  In the example below, the Programmer class (subclass) inherits the attributes and methods from the Employee class (superclass):
  • 40. Object-Oriented Programming 40 class Employee { float salary=40000; } class Programmer extends Employee { int bonus=10000; public static void main(String args[]) { Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Programmer salary is:40000.0 Bonus of programmer is:10000
  • 41. Obtaining the Java Development Kit 41  The Java Development Kit (JDK) is a cross-platform software development environment that offers a collection of tools and libraries necessary for developing Java-based software applications and applets.  It is a core package used in Java, along with the JVM(Java Virtual Machine) and the JRE (Java Runtime Environment).  Beginners often get confused with JRE and JDK, if you are only interested in running Java programs on your machine then you can easily do it using Java Runtime Environment.  However, if you would like to develop a Java-based software application then along with JRE, you may need some additional necessary tools, which is called JDK.
  • 42. Obtaining the Java Development Kit  The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development of a Java Application.  JDK contains:  Java Runtime Environment (JRE),  An interpreter/loader (Java),  A compiler (javac),  An archiver (jar) and many more. 42
  • 43. Obtaining the Java Development Kit 43  Installation of JDK:  Go to this Oracle’s official Download Page through this link : https://www.oracle.com/in/java/technologies/  Select the latest JDK version and click Download and add it to your classpath.  Just check the JDK software is installed or not on your computer at the correct location, for example, at C:Program FilesJavajdk11.0.9.  Compile and Run Java Code using JDK:  You can use the JDK compiler to convert your Java text file into an executable program. Your Java text segment is converted into bytecode after compilation which carries the .class extension.  First, create a Java text file and save it using a name. Here we are saving the file as Hello.java.
  • 44. The First Sample Program  After that just simply use the javac command, which is used for the compilation purpose in Java.  You can notice now that the Hello.class file is being created in the same directory as Hello.java. 44
  • 45. A First Simple Program 45  You will follow these three steps: 1. Write the program. 2. Compile the program. 3. Run the program.  Comment:- Java lets you enter a remark into a program’s source file.  The contents of a comment are ignored by the compiler.  Instead, a comment describes or explains the operation of the program to anyone who is reading its source code.
  • 46. Comments in Java 46  Java supports three styles of comments. 1. Single-line comment:- A single-line comment begins with a // and ends at the end of the line. As a general rule, programmers use multiline comments for longer remarks and single-line comments for brief, line- byline descriptions. 2. Multiline comment:- This type of comment must begin with /* and end with */. Anything between these two comment symbols is ignored by the compiler. 3. Documentation comments:- There is another type of multi-line comment available in Java. For this, we use the /** and */ to enclose documentation comments. This is used for defining formal documentation APIs for your programs that are created by the javadoc tool.
  • 47. The First Sample Program Line by Line 47  Class keyword is used to declare that a new class is being defined.  As mentioned, the class is Java’s basic unit of encapsulation.  Hello is the name of the class in above example.  The class definition begins with the opening curly brace ({) and ends with the closing curly brace (}).  The elements between the two braces are members of the class.
  • 48. The First Sample Program Line by Line 48  As mentioned earlier, in Java, a subroutine is called a method , this is the line at which the program will begin executing. In general, Java applications begin execution by calling main( ).  The public keyword is an access modifier. An access modifier determines how other parts of the program can access the members of the class. When a class member is preceded by public, then that member can be accessed by code outside the class in which it is declared.  The keyword static allows main( ) to be called before an object of the class has been created. This is necessary because main( ) is called by the JVM before any objects are made.  The keyword void simply tells the compiler that main( ) does not return a value.
  • 49. The First Sample Program Line by Line 49  In main( ) there is only one parameter, String args[], which declares a parameter named args. This is an array of objects of type String. (Arrays are collections of similar objects.) Objects of type String store sequences of characters. In this case, args receives any command-line arguments present when the program is executed.  Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string that is passed to it.  The line begins with System.out. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. Thus, System.out is an object that encapsulates console output.
  • 50. Handling Syntax Errors 50  If you enter something incorrectly into your program, the compiler will report a syntax error message when it tries to compile it.  The Java compiler attempts to make sense out of your source code no matter what you have written.  For this reason, the error that is reported may not always reflect the actual cause of the problem.  In the preceding program, for example, an accidental omission of the opening curly brace after the main( ) method causes the compiler to report errors.
  • 51. A Second Simple Program 51
  • 52. A Second Simple Program 52
  • 53. A Second Simple Program 53  The following line of code assigns var1 the value 1024: var1 = 1024; // this assigns 1024 to var1  In Java, the assignment operator is the single equal sign. It copies the value on its right side into the variable on its left.  The next line of code outputs the value of var1 preceded by the string "var1 contains ": System.out.println("var1 contains " + var1);  In this statement, the plus sign causes the value of var1 to be displayed after the string that precedes it.
  • 54. A Second Simple Program 54  The next line of code assigns var2 the value of var1 divided by 2: var2 = var1 / 2;  This line divides the value in var1 by 2 and then stores that result in var2. Thus, after the line executes, var2 will contain the value 512.  Here are the next two lines in the program: System.out.print("var2 contains var1 / 2: "); System.out.println(var2);  print( ) and println( ) can be used to output values of any of Java’s built-in types.
  • 55. Data Types 55  In the preceding program, a variable of type int was used. However, a variable of type int can hold only whole numbers.  Thus, it cannot be used when a fractional component is required. For example, an int variable can hold the value 18, but not the value 18.3. Fortunately, int is only one of several data types defined by Java.  To allow numbers with fractional components, Java defines two floating-point types: float and double, which represent single- and double-precision values, respectively.
  • 56. Data Types 56  Of the two, double is the most commonly used.  To declare a variable of type double, use a statement similar to that shown here: double x;  Here, x is the name of the variable, which is of type double. Because x has a floating-point type, it can hold values such as 122.23, 0.034, or –19.0.
  • 57. Control Statements (The if Statement)  The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. 1. Java if (if-then) Statement:-  The syntax of an if-then statement is: 57
  • 58. Control Statements (The if Statement)  Here, condition is a boolean expression such as age >= 18.  if condition evaluates to true, statements are executed  if condition evaluates to false, statements are skipped 58
  • 59. Control Statements (The if Statement)  In the program, number < 0 is false. Hence, the code inside the body of the if statement is skipped. 59
  • 60. Control Statements (The if Statement)  In the above example, we are comparing two strings in the if block. 60
  • 61. Control Statements (The if-then-else Statement)  Java if...else (if-then-else) Statement:-  The if statement executes a certain section of code if the test expression is evaluated to true. However, if the test expression is evaluated to false, it does nothing.  In this case, we can use an optional else block. Statements inside the body of else block are executed if the test expression is evaluated to false. This is known as the if-...else statement in Java.  The syntax of the if...else statement is: 61
  • 62. Control Statements (The if-then-else Statement)  Here, the program will do one task (codes inside if block) if the condition is true and another task (codes inside else block) if the condition is false. 62
  • 63. Control Statements (The if-then-else Statement) 63
  • 64. Control Statements (The if-then-else Statement)  In the above example, we have a variable named number. Here, the test expression number > 0 checks if number is greater than 0.  Since the value of the number is 10, the test expression evaluates to true. Hence code inside the body of if is executed.  Now, change the value of the number to a negative integer. Let's say -5.  If we run the program with the new value of number, the output will be:  Here, the value of number is -5. So the test expression evaluates to false. Hence code inside the body of else is executed. 64
  • 65. Control Statements (if...else...if Statement)  In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple other blocks.  Here, if statements are executed from the top towards the bottom. When the test condition is true, codes inside the body of that if block is executed. And, program control jumps outside the if...else...if ladder.  If all test expressions are false, codes inside the body of else are executed. 65
  • 68. Control Statements (if...else...if Statement) 68  In the above example, we are checking whether number is positive, negative, or zero. Here, we have two condition expressions:  number > 0 - checks if number is greater than 0  number < 0 - checks if number is less than 0  Here, the value of number is 0. So both the conditions evaluate to false.  Hence the statement inside the body of else is executed.
  • 69. Operators  Java defines a full complement of relational operators that may be used in a conditional expression. They are shown here: 69
  • 70. The for Loop  You can repeatedly execute a sequence of code by creating a loop. Loops are used whenever you need to perform a repetitive task because they are much simpler and easier than trying to write the same statement sequence over and over again. Java supplies a powerful assortment of loop constructs. The one we will look at here is the for loop.  Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is: 70
  • 71. The for Loop  Here, 1. The initialExpression initializes and/or declares variables and executes only once. 2. The condition is evaluated. If the condition is true, the body of the for loop is executed. 3. The updateExpression updates the value of initialExpression. 4. The condition is evaluated again. The process continues until the condition is false. 71
  • 73. The for Loop  Here is how this program works.  73
  • 75. The for Loop  Here is how the program works. 75
  • 76. Create Blocks of Code 76  Another key element of Java is the code block. A code block is a grouping of two or more statements.  This is done by enclosing the statements between opening and closing curly braces.  Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can.
  • 77. Create Blocks of Code  For example, 77
  • 78. Create Blocks of Code  In the above example, we have a block if {....}.  Here, inside the block we have two statements:  System.out.print("Hey ");  System.out.print("Jude!");  However, a block may not have any statements. Consider the following examples,  This is a valid Java program.  Here, we have a block if {...}.  However, there is no any statement inside this block. 78
  • 79. Create Blocks of Code  Here, we have block public static void main() {...}. However, similar to the above example, this block does not have any statement. 79
  • 80. Semicolons and Positioning 80  In Java, the semicolon is a separator. It is often used to terminate a statement. In essence, the semicolon indicates the end of one logical entity.  As you know, a block is a set of logically connected statements that are surrounded by opening and closing braces. A block is not terminated with a semicolon. Instead, the end of the block is indicated by the closing brace.  Java does not recognize the end of the line as a terminator. For this reason, it does not matter where on a line you put a statement. For example,  x = y;  y = y + 1;  System.out.println(x + " " + y);  is the same as the following, to Java:  x = y; y = y + 1; System.out.println(x + " " + y);
  • 81. Semicolons and Positioning  Furthermore, the individual elements of a statement can also be put on separate lines. For example, the following is perfectly acceptable:  Breaking long lines in this fashion is often used to make programs more readable. It can also help prevent excessively long lines from wrapping. 81
  • 82. Indentation Practices 82  In programming, indentation is just like formatting. It is used to make the code readable to other users because it makes the code easier to edit, displays how the braces match up, and shows the logic of the program in well-organized fashion.  It signals to the reader that he/ she is about to dive into another a new section of a program.  The goal of the indentation is to show the logic of the program. We must keep indentation throughout the program because it is an essential part of formatting.
  • 83. Indentation Practices  Remember that the function of indentation is to make the program more readable and understandable that saves an immense amount of time when editing or refining the code. 83
  • 84. The Java Keywords  Keywords are predefined, reserved words used in Java programming that have special meanings to the compiler. For example:  Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed two's complement integer).  You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are part of the Java programming language syntax. Here's the complete list of all keywords in Java programming. 84
  • 86. The Java Keywords 86  The keywords const and goto are reserved but not used. In the early days of Java, several other keywords were reserved for possible future use.  In addition to the keywords, Java reserves the following: true, false, and null.  These are values defined by Java. You may not use these words for the names of variables, classes, and so on.
  • 87. Identifiers in Java  Identifiers are the name given to variables, classes, methods, etc. Consider the above code;  Here, score is a variable (an identifier). You cannot use keywords as variable names. It's because keywords have predefined meanings. For example,  The above code is wrong. It's because float is a keyword and cannot be used as a variable name. 87
  • 88. Identifiers in Java 88  Rules for Naming an Identifier:- 1. Identifiers cannot be a keyword. 2. Identifiers are case-sensitive. 3. It can have a sequence of letters and digits. However, it must begin with a letter, $ or _. The first letter of an identifier cannot be a digit. 4. It's a convention to start an identifier with a letter rather and $ or _. 5. Whitespaces are not allowed. 6. Similarly, you cannot use symbols such as @, #, and so on.
  • 89. Identifiers in Java 89  Here are some valid identifiers:  score  level  highestScore  number1  convertToString  Here are some invalid identifiers:  class  float  1number  highest Score  @pple
  • 90. The Java Class Libraries 90  The sample programs shown in this chapter make use of two of Java’s built-in methods: println( ) and print( ).  These methods are accessed through System.out.  System is a class predefined by Java that is automatically included in your programs.  In the larger view, the Java environment relies on several built-in class libraries that contain many built-in methods that provide support for such things as I/O, string handling, networking, and graphics.