0% found this document useful (0 votes)
24 views63 pages

Module 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 63

Java Programming

Syllabus
MODULE I: PROCEDURAL ORIENTED
PROGRAMMING
 Introduction to Java
 Identifiers
 Variables
 Assignment Statements
 Assignment Expressions
 Constants(final keyword)
 Data types and Operations
 Console Input using Scanner class
 Selections
 Looping
 Arrays.
MODULE II: OBJECT ORIENTED
PROGRAMMING
 Objects and classes
 Introduction
 Defining classes for Objects
 Constructing Objects Using Constructors
 Constructor Overloading
MODULE III: Data field
Encapsulation and Built in
classes
Visibility Modifiers
Data Field Encapsulation
Static Variables
Constants and Methods
 String class
Array class
MODULE IV: Inheritance

Inheritance introduction
Super class
Sub classes
 Types of inheritance
Using the super keyword
Overriding Methods
MODULE V: Polymorphism and Exception
handling
 Overloading Vs Overriding
 Polymorphism
 Static Vs Dynamic Binding
 Exception Handling overview
 Exception-Handling Advantages
 Exception Types
 Command-Line Arguments
Introduction
 JAVA was developed by James Gosling at Sun Microsystems Inc
in the year 1995
 It is a simple programming language.
 Java makes writing, compiling, and debugging programming
easy.
 It helps to create reusable code and modular programs.
 Java is a class-based, object-oriented programming language
and is designed to have as few implementation dependencies as
possible.
 A general-purpose programming language made for developers
to write once run anywhere that is compiled Java code can run
on all platforms that support Java
Applications of Java
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
Example Program
Parameters used in First Java Program
Let's see what is the meaning of class, public, static,
void, main, String[], System.out.println().

• class keyword is used to declare a class in Java.


• public keyword is an access modifier that represents
visibility. It means it is visible to all.
• static is a keyword ,If we declare any method as
static, it is known as the static method. The core
advantage of the static method is that there is no
need to create an object to invoke the static method.
• void is the return type of the method. It means
it doesn't return any value.
• main represents the starting point of the
program.
• String args[] is used for command line
argument. It is an argument i.e. passed at the
time of running the java program.
System.out.println() is used to print statement.
Here, System is a class, out is an object of the
class, println() is a method of the class.
Comments: Comments are used for explaining
code and are used in a similar manner in Java
or C or C++. Compilers ignore the comment
entries and do not execute them. Comments
can be of a single line or multiple lines.
Single line Comments:
Syntax:
// Single line commentMulti-line comments:
Syntax:
/* Multi line comments*/
Identifiers
• Identifiers are names that are helpful in
uniquely recognizing a class, a method, or
a variable. Certain rules are to be followed in
java while we are defining an identifier or the
compiler will throw an error.
Rules for defining Java Identifiers

• There are certain rules for defining a valid java identifier. These rules must be
followed, otherwise we get compile-time error. These rules are also valid for
other languages like C,C++.

• The only allowed characters for identifiers are all alphanumeric characters([A-Z],
[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a
valid java identifier as it contain ‘@’ special character.
• Identifiers should not start with digits([0-9]). For example “123geeks” is a not a
valid java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier. For example “int while = 20;” is an
invalid statement as while is a reserved word. There are 53 reserved words in
Java.
Examples of valid identifiers :
 MyVariable
 MYVARIABLE
 Myvariable
 xI
 x1
 i1
 _myvariable
 $myvariable
 sum_of_array
 geeks123
Examples of invalid identifiers :
 My Variable // contains a space
 123geeks // Begins with a digit
 a+c // plus sign is not an alphanumeric
character
 variable-2 // hyphen is not an alphanumeric
character
 sum_&_difference // ampersand is not an
alphanumeric character
Java Variables

• A variable is the name of a reserved area


allocated in memory. In other words, it is a
name of the memory location. It is a
combination of "vary + able" which means its
value can be changed.
• A variable is assigned with a data type.
• There are three types of variables in java:
local, instance and static.
• int data=10;
Types of Variables

There are three types of variables in Java:


local variable
instance variable
static variable
Local Variable
• A variable declared inside the body of the method is called local
variable. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.
Instance Variable
• A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.
• It is called an instance variable because its value is instance-specific
and is not shared among instances.
Static variable
• A variable that is declared as static is called a static variable. It cannot
be local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Assignment Statements
and
Assignment Expressions
Assignment Statements and Assignment
Expressions
• An assignment statement designates a value
for a variable. An assignment statement can
be used as an expression in Java.

• An expression represents a computation


involving values, variables, and operators that,
taking them together, evaluates to a value
 After a variable is declared, we can assign a value to it by using an
assignment statement.
 In Java, the equal sign (=) is used as the assignment operator.

The syntax for assignment statements is as follows:


variable = expression;
For example, consider the following code:

 int y = 1; // Assign 1 to variable y


 double radius = 1.0; // Assign 1.0 to variable radius
 int x = 5 * (3 / 2); // Assign the value of the expression to x
 float x = y + 1.9; // Assign the addition of y and 1 to x
• In Java, an assignment statement is essentially
an expression that evaluates to the value to be
assigned to the variable on the left side of the
assignment operator.
• For this reason, an assignment statement is
also known as an assignment expression.
• If a value is assigned to multiple variables, we
can use this syntax:
i = j = k = 1;
which is equivalent to k = 1; j = k; i = j;
Constants
• A named constant is an identifier that represents a
permanent value.
• The value of a variable may change during the
execution of a program, but a named constant, or
simply constant, represents permanent data that
never changes.
• For Example pi is a constant. If you use it
frequently, we don’t want to keep typing 3.14159;
instead, we can declare a constant for pi.
Important (keyword final for constants)
• The syntax for declaring a constant:
final datatype constantname = value;
• A constant must be declared and initialized in
the same statement.
• The word final is a Java keyword for declaring
a constant.
• For example,
import java.io.*;
public class area
{
public static void main(String[] args)
{
final double PI = 3.14159;
int radius=3;
double area = PI *radius * radius;
System.out.println("The area for the circle of is
" + area);
}
There are three benefits of using constants:
(1) you don’t have to repeatedly type the same
value if it is used multiple times;
(2) if you have to change the constant value
(e.g., from 3.14 to 3.14159 for PI), you need to
change it only in a single location in the source
code;
(3) a descriptive name for a constant makes the
program easy to read.
Data Types
in
Java
Data Types in Java
Data types specify the different sizes and values that can be
stored in the variable
There are two types of data types in Java:

• Primitive data types: The primitive data types include


boolean, char, byte, short, int, long, float and double.

• Non-primitive data types: The non-primitive data types


include Interfaces, strings and arrays.
There are 8 types of primitive/basic data types:

 boolean data type


 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Boolean Data Type
• The Boolean data type is used to store only two
possible values: true and false. This data type is used
for simple flags that track true/false conditions.
• The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
Example:
Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type.
Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large
arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.

Example:
byte a = 10;
byte b = 20 ;
Short Data Type
• Its value-range lies between -32,768 to 32,767
(inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.
• The short data type can also be used to save
memory just like byte data type.
• A short data type is 2 times smaller than an
integer.
• Example:
short s = 10;
Int Data Type
• Its value-range lies between - 2,147,483,648 to
2,147,483,647 . Its minimum value is - 2,147,483,648
and maximum value is 2,147,483,647. Its default
value is 0.
• The int data type is generally used as a default data
type for integer values
Example:
int a = 1000;
Long Data Type
Its value-range lies between -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need
a range of values more than those provided by int.
Example:
long a = 100000L
Float Data Type
Its recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
Example:
float p = 234.5;
Double Data Type
Its value range is unlimited. The double data type is generally used for
decimal values just like float. The double data type also should never be used
for precise values, such as currency. Its default value is 0.0d.
Example:
double a = 12.34567;
Char Data Type
The char data type is used to store characters.
Example:
char letter = 'A'
Operators in Java
• Operator in Java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
• There are many types of operators in Java which are given
below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Operator Type Category Precedence

Unary postfix a++ ,b--

prefix ++a ,--b

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}}
Java Arithmetic Operators

• Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division. They act as basic mathematical operations.
• Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Java Ternary Operator
• Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.
• Java Ternary Operator Example

public class OperatorExample


{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output:
2
Java AND Operator Example: Logical && and Bitwise &

• The logical && operator doesn't check the


second condition if the first condition is false.
It checks the second condition only if the first
one is true.
• The bitwise & operator always checks both
conditions whether first condition is true or
false.
public class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}
Output:
false false
Java Assignment Operator
• Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.
• Java Assignment Operator Example

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Relational Operators
Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Example
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x > y); // returns true
because 5 is greater than 3
}
}
Console Input
using
Scanner class
Java User Input

• The 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. In
our example, we will us
the nextLine() method, which is used to read
Strings
Example

import java.util.Scanner;
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String n ;
System.out.println("Enter username");
userName = sc.nextLine();
System.out.println(“username is: " + n);
}
}
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:

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


import java.util.Scanner;
class UserInput
{
public static void main(String[] args)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = a.nextLine();
int age = a..nextInt();
double salary = a.nextDouble();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
 Reading input from the console enables the
program to accept input from the user.
 Java uses System.out to refer to the standard
output device and System.in to the standard
input device.
 By default, the output device is the display
monitor and the input device is the keyboard.
Console input is not directly supported in Java,
but you can use the Scanner class to create an
object to read input from System.in as follows:
Scanner input = new Scanner(System.in);
 The syntax new Scanner(System.in) creates an
object of the Scanner type.
 Scanner input declares that input is a variable
whose type is Scanner

 The whole line


Scanner input = new Scanner(System.in) creates
a Scanner object and assigns its reference to the
variable input.
The specific import specifies a single class in the import statement.

For example, the following statement imports Scanner from the


package java.util.

import java.util.Scanner;
The wildcard import imports all the classes in a package by using the
asterisk as the
wildcard.
For example, the following statement imports all the classes from the
package java.util.
import java.util.*;
The import statement simply tells the compiler where to locate the
classes.
import java.util.Scanner;
public class Compute
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();
double area = radius * radius * 3.14159;
System.out.println("The area for the circle of radius " +radius+ " is " +
area);
}
}
Enter a number for radius: 2.5
The area for the circle of radius 2.5 is 19.6349375
The program reads three numbers and displays their average.

import java.util.Scanner;
public class ComputeAverage
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();
double average = (number1 + number2 + number3) / 3;
System.out.println("The average of these 3 numbers " is " + average);
}
}

output
Enter three numbers: 10.5
11
11.5
The average of these 3 numbers is 11.0

You might also like