JAVA PROGRAMMING
Dr. K. SANDEEP Ph.D.
Associate Professor
Department of IT
UNIT I Syllabus
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements
or Tokens in Java Programs, Java Statements, Command Line Arguments, User
Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java,
Declaration of Variables, Data Types, Type Casting, Scope of Variable Identifier,
Literal Constants, Symbolic Constants, Formatted Output with printf() Method,
Static Variables and Methods, Attribute Final, Introduction to Operators,
Precedence and Associativity of Operators, Assignment Operator ( = ), Basic
Arithmetic Operators, Increment (++) and Decrement (- -) Operators, Ternary
Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else
Expressions, Ternary Operator?:, Switch Statement, Iteration Statements, while
Expression, do–while Loop, for Loop, Nested for Loop, For–Each for Loop, Break
Statement, Continue Statement.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 2
Introduction
• Java is a high level, robust, object-oriented, concurrent, and
secure programming language.
• Java was developed by Sun Microsystems (which is now the
subsidiary of Oracle) in the year 1995.
• James Gosling is known as the father of Java.
• Difference between C++ vs JAVA
https://www.javatpoint.com/cpp-vs-java
12/15/2023 UNIT-1/kottesandeep.blogspot.com 3
Applications:
According to Sun, 3 billion devices run Java. There are many devices
where Java is currently used. Some of them are as follows:
→Desktop Applications such as acrobat reader, media player, antivirus, etc.
→Web Applications Like irctc.co.in, ebay.in
→Enterprise Applications such as banking applications.
→Mobile
→Embedded System
→Smart Card
→Robotics
→Games, etc.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 4
The Java Buzzwords:
12/15/2023 UNIT-1/kottesandeep.blogspot.com 5
1.Simple: Java language is a simple programming language because:
• Java syntax is based on C++
• Java has removed many complicated and rarely-used features like,
--pointers, goto, operator overloading etc…
• Automatic Garbage Collection: need Not to remove unreferenced objects.
2.Object-oriented: Java is a pure (True) object-oriented programming language
• Everything in Java is an object.
--i.e All program code and data reside within objects and classes.
• The object model in Java is simple and easy to extend.
• Java comes with an extensive set of classes, arranged in packages that can be
used in our programs through inheritance.
• Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 6
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation etc…
12/15/2023 UNIT-1/kottesandeep.blogspot.com 7
3.Secured:Java is best known for its security. With Java, we can develop virus-free
systems.
Java is secured because:
• No explicit pointer (it means no
pointer arithmetic and no
stack-allocated objects)
• Java Programs run inside
a virtual machine sandbox.
• https://www.javatpoint.com/difference-between-jdk-jre-and-jvm
• Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
• Security Manager: It determines what resources a class can access such as reading and
writing to the local disk
12/15/2023 UNIT-1/kottesandeep.blogspot.com 8
4.Platform Independent: Java code can be executed on multiple platforms
Like:
Windows,
Linux,
Sun Solaris,
Mac/OS, etc.
• Java code is compiled by the compiler and converted into bytecode.
• The bytecode is a platform-independent code because it can be run on multiple
platforms, i.e., Write Once and Run Anywhere (WORA).
12/15/2023 UNIT-1/kottesandeep.blogspot.com 9
5.Robust: The English meaning of Robust is strong. Java is robust because:
• Java is a strictly typed language. It checks code both at compile time and runtime.
• Java takes care of all memory management problems with garbage collection.
• Java, with the help of an exception handling, captures all types of serious errors
and eliminates any risk of crashing the system.
• There is a lack of pointers that avoids security problems.
• Can execute programs accurately in a variety of environments.
6.Portable: Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
7.Architecture-neutral: Java language and Java Virtual Machine helped in
achieving the goal of “write once; run anywhere, any time, forever.”
• Changes and upgrades in operating systems, processors and system resources will
not force any changes in Java Programs.
For Example: In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 10
8.Dynamic: It supports the dynamic loading of classes(new class libraries, methods, and objects).
9. Compiled and Interpreted: Usually, a computer language is either compiled or Interpreted.
Java combines both this approach and makes it a two-stage system.
• Compiled: Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java Bytecode.
• Interpreted: Bytecode is then interpreted, which generates machine code that can be directly
executed by the machine that provides a Java Virtual machine.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 11
10. High Performance:
• Java performance is high because of the use of bytecode.
• The bytecode was used so that it was easily translated into native machine code.
11. Multithreaded:
• Multithreaded Programs handled multiple tasks simultaneously (executing
concurrently), which was helpful in creating interactive(Web applications), multi-
media, networked programs etc...
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area.
12. Distributed:
• Java applications can access remote objects on the Internet as easily as they can do
in the local system.
• Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
• Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 12
Writing Simple Java Programs
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
} Save the above file as Simple.java
To compile: javac Simple.java
} To execute: java Simple
Output: Hello Java
12/15/2023 https://www.geeksforgeeks.org/java-main-method-
UNIT-1/kottesandeep.blogspot.com 13
Elements or Tokens in Java Programs
• In Java, the program contains classes and methods.
• Further, the methods contain the expressions and statements
required to perform a specific operation.
• These statements and expressions are made up of tokens.
• In other words, we can say that the expression and statement is
a set of tokens.
• The tokens are the small building blocks of a Java program that
are meaningful to the Java compiler.
• Further, these two components contain variables, constants, and
operators.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 14
12/15/2023 UNIT-1/kottesandeep.blogspot.com 15
Keywords
• These are the pre-defined reserved words of any programming language.
• Each keyword has a special meaning. It is always written in lower case. Java
provides the following (50) keywords:
12/15/2023 UNIT-1/kottesandeep.blogspot.com 16
Identifiers
• Identifiers are used to name things, such as classes, variables,
and methods.
• An identifier may be any descriptive sequence of uppercase and
lowercase letters, numbers, or the underscore and dollar-sign
characters.
There are some rules to declare identifiers are:
• The first letter of an identifier must be a letter, underscore or a
dollar sign.
• It cannot start with digits but may contain digits.
• The whitespace cannot be included in the identifier.
• Identifiers are case sensitive.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 17
Some valid identifiers are:
PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid
12/15/2023 UNIT-1/kottesandeep.blogspot.com 18
Literals
• literal is a notation that represents a fixed value in the source code.
There are the majorly four types of literals in Java:
12/15/2023 UNIT-1/kottesandeep.blogspot.com 19
Integral literals
• Integer literals are sequences of digits.
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-).Note that between numbers commas and non-digit characters are not permitted.
For example: 5678, +657, -89,
Java code: int decVal = 26;
Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.
For example: 045, 026,
Java code: int octVal = 067;
Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in
Java SE 7 and later). Prefix 0b represents the Binary system.
For example: 0b11010.
Java code: int binVal = 0b11010;
Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as hexadecimal integers. It may
also include a character from a to f or A to F that represents numbers from 10 to 15, respectively.
For example: 0xd, 0xf,
Java code: int hexVal = 0x1a;
12/15/2023 UNIT-1/kottesandeep.blogspot.com 20
• Real Literals: The numbers that contain fractional parts are known as real literals.
We can also represent real literals in exponent form.
• For example: 879.90, 99E-3, etc.
• Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It
is a 32-bit float literal.
• Floating-point literals for double type end with D or d. It is optional to write D or
d. For example, 6d, 8.354D, etc. It is a 64-bit double literal.
• It can also be represented in the form of the exponent.
• Java code: float length = 155.4f;
double interest = 99658.445;
12/15/2023 UNIT-1/kottesandeep.blogspot.com 21
Boolean Literals
• Boolean literals are the value that is either true or false. It may also have values 0
and 1. For example, true, 0, etc.
Java Code : boolean isEven = true;
Char literals
• A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%',
'\u000d', etc.
String Literals
• String literal is a sequence of characters that is enclosed between double quotes
("") marks. It may be alphabet, numbers, special characters, blank space, etc. For
example, "Jack", "12345", "\n", etc.
Null Literals
• Null literal is often used in programs as a marker to indicate that reference type
object is unavailable. String stuName = null;
• Student age = null;
12/15/2023 UNIT-1/kottesandeep.blogspot.com 22
Operators in Java
• Operator in Java is a symbol that is used to perform an operation between two
operands. Ex: C=A+B
Types of operators in Java:
• Unary Operator
• Arithmetic Operator
• Shift Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Ternary Operator
• Assignment Operator.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 23
12/15/2023 UNIT-1/kottesandeep.blogspot.com 24
• Separators: The separators in Java is also known as punctuators.
• Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
• Parentheses (): It is used to call the functions and parsing the parameters.
• Curly Braces {}: The curly braces denote the starting and ending of a code block.
• Comma (,): It is used to separate two values, statements, and parameters.
• Assignment Operator (=): It is used to assign a variable and constant.
• Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
• Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable
• Colons (::): Used to create a method or constructor reference.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 25
Comments
• Comments allow us to specify information about the program inside our Java
code.
• Java compiler recognizes these comments as tokens but excludes it form further
processing.
• The Java compiler treats comments as whitespaces.
• Java provides the following three types of comments:
• Line Oriented: It begins with a pair of forwarding slashes (//).
• Block-Oriented: It begins with /* and continues until it founds */.
• Documentation comment: It begins with /** and continues until it founds */.
--This type of comment is used to produce an HTML file that documents your program.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 26
Command Line Arguments
• The java command-line argument is an argument i.e. passed at the time of running
the java program.
• The arguments passed from the console can be received in the java program and it
can be used as an input.
• So, it provides a convenient way to check the behavior of the program for the
different values.
• You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
class AB{
public static void main(String args[])
{
System.out.println("My Name is:"+args[0]);
}
compile by > javac AB.java
run by >java AB Dr.K.Sandeep }
12/15/2023 UNIT-1/kottesandeep.blogspot.com 27
• Ex:2.
class AB
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac AB.java
run by >java AB Dr.K.Sandeep from DIET
Output>
Dr.k.Sandeep
from
DIET
12/15/2023 UNIT-1/kottesandeep.blogspot.com 28
Java Statements
• In Java, a statement is an executable instruction that tells the compiler
what to perform.
• It forms a complete command to be executed and can include one or
more expressions.
Types of Statements: Java statements can be broadly classified into the
following categories:
• Expression Statements
• Declaration Statements
• Control Statements
• Compound Statements
12/15/2023 UNIT-1/kottesandeep.blogspot.com 29
• Expression Statements: Expression is an essential building block of any Java
program.
• Generally, it is used to generate a new value.
• Sometimes, we can also assign a value to a variable.
• In Java, expression is the combination of values, variables, operators,
and method calls.
There are three types of expressions in Java:
1. Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2.
2. Expressions that assign a value. For example, number = 90, pi = 3.14.
3. Expression that neither produces any result nor assigns a value.
For example, increment or decrement a value by using increment or decrement operator
12/15/2023 UNIT-1/kottesandeep.blogspot.com 30
Declaration Statements
• In declaration statements, we declare variables and constants by specifying their
data type and name.
• A variable holds a value that is going to use in the Java program.
For example: int quantity;
boolean flag;
String message;
or
int quantity = 20;
boolean flag = false;
String message = "Hello";
12/15/2023 UNIT-1/kottesandeep.blogspot.com 31
Control Statement
• Control statements decide the flow (order or sequence of execution of
statements) of a Java program.
• In Java, statements are parsed from top to bottom.
• Therefore, using the control flow statements can interrupt a particular section of
a program based on a certain condition.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 32
Java User Input
• Scanner class is used to get user input, and it is found in the java.util
package.
• To use the Scanner class, create an object of the class and use any of
the available methods found in the Scanner class documentation.
import java.util.Scanner; // import the Scanner class
class A {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;
System.out.println("Enter username");
userName = myObj.nextLine();
System.out.println("Username is: " + userName);
}
12/15/2023 } UNIT-1/kottesandeep.blogspot.com 33
Input Types
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
12/15/2023 UNIT-1/kottesandeep.blogspot.com 34
BufferedReader class
• BufferedReader is another way to take the input from the user, but it’s a
bit more complex than the Scanner class. java.io.BufferedReader reads
text from the character-input stream.
• Using readLine(), it reads the data line by line. It makes the performance
fast.
import java.io.*;
public class BufferedReaderclass {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter you string here:");
String object = br.readLine();
System.out.println(object); } }
12/15/2023 UNIT-1/kottesandeep.blogspot.com 35
BufferedReader class
import java.io.*;
public class BufferedReaderclass {
public static void main(String[] args) throws IOException {
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.println("Enter you string here:");
String object = br.readLine();
System.out.println(object); } }
12/15/2023 UNIT-1/kottesandeep.blogspot.com 36
BufferedReader class
•int n=Integer.parseInt(br.readLine());
•float f= Float. parseFloat(br.readLine());
•long l=Long.parseLong(br.readLine());
•double d= Double.parse Double(br.readLine());
•String s = br.readLine();
12/15/2023 UNIT-1/kottesandeep.blogspot.com 37
Scanner class vs BufferedReader class
Scanner class BufferedReader class
The scanner class is not synchronous and The BufferedReader class is synchronous
does not support threads. and Widely used with multiple threads.
BufferedReader simply reads the sequence
Scanner breaks its input into tokens using a
of characters in a portion that depends on
Delimiter pattern.
the buffer size.
The scanner has a little buffer(1KB byte It has a significantly larger buffer memory
buffer). than Scanner.(8KB byte buffer)
Unlike Scanner, BufferedReader simply
The scanner is slow as it does the parsing of reads the sequence of characters. Hence it
input data. Moreover, It hides IOException. is faster than the Scanner Class. It throws
an IOException.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 38
Symbolic constants / Final keyword
• Symbolic constant is a named constant value defined once and used
throughout a program. Symbolic constants are declared using the
final keyword.
• Which indicates that the value cannot be changed once it is
initialized.
• The naming convention for symbolic constants is to use all capital
letters with underscores separating words.
• final double PI=3.14;
12/15/2023 UNIT-1/kottesandeep.blogspot.com 39
Symbolic constants/ Final keyword
• class HelloWorld {
• public static final double PI = 3.14159;
• public static void main(String[] args) {
• double a,r=2;
• a= PI*r*r;
• System.out.printf("Hello, World!%f",a); }}
12/15/2023 UNIT-1/kottesandeep.blogspot.com 40
Formatted Output with printf() Method
• System.out.printf("Hello \n %s!", "World");
• System.out.printf("Hello \n %s! \n %f", "World", a);
• System.out.printf("%,d \n", 10000); ---- 10,000
• System.out.printf("%f \n", 5.1473); ---- 5.147300
• System.out.printf("'%5.2f'\n", 5.1473); --- ' 5.15’
• ystem.out.printf("'%5.2e'%n", 5.1473); ----- '5.15e+00'
12/15/2023 UNIT-1/kottesandeep.blogspot.com 41
Java static method
• If you apply static keyword with any method, it is known as static
method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an
instance of a class.
• A static method can access static data member and can change the
value of it.
12/15/2023 UNIT-1/kottesandeep.blogspot.com 42
Java static method
• class Calculate{
• static int cube(int x){
• return x*x*x;
• }
•
• public static void main(String args[]){
• int result=Calculate.cube(5);
• System.out.println(result);
• }
• }
12/15/2023 UNIT-1/kottesandeep.blogspot.com 43
Thank you
12/15/2023 UNIT-1/kottesandeep.blogspot.com 44