0% found this document useful (0 votes)
3 views47 pages

V1 Java Standard Edition

Uploaded by

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

V1 Java Standard Edition

Uploaded by

John Smith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Java Standard Edition

Content
 Features of java
 Java Environment and JDK, JRE, JVM.
 Java Syntax and class.
 Data types , Variables, Methods, access modifiers.
 Control statements (if, switch, loops), break, continue
 Arrays.
 OOP principle
 Collections, Generics.
 Exceptions handling.
 GUI.
Features of Java

 Pure object oriented programming.


 Simple learning curve.
 Platform independent.
 High performance.
 Multithread
 Secure.
JDK and setting environment.

 JDK  The Java Development Kit (JDK) is a software development


environment that allows Developer to developing Java applications,
and it’s contains other tools like:
1. JRE  Java Runtime Environments
2. Java loader (java)
3. Java compiler (javac)
4. archiver (jar)
5. documentation generator (javadoc)..
 downloading JDK with desired version like (1.8), and install this in PC.
 We need to set java as a system variable to let all the JDK tools to be
accessed from everywhere in PC.
 Right click on PC icon  properties  advance system variable.
 Then click on Environments variables, popup will appear
 Click in new, popup will appear to define user variable
 Variable name will be  JAVA_HOME, and refer the path where you
installed JDK in the variable value.
 Then search for variable called Path in system variable

 Click on edit, and add the JDK bin path


Java Code Convention.
 Coding conventions should be used as a guide.
 There is Convention for names in java its called camel case convention for
the following :
 Class and interface name  should be nouns, in mixed case with
the first letter of each internal word capitalized (MountainBike, Sport,
Human).
 Methods  Methods should be verbs, in mixed case with the first letter
lowercase and with the first letter of each internal word capitalized.
 Variables 
 Variable names should be short yet meaningful
 Should not start with underscore(‘_’) or dollar sign ‘$’ characters.
 Packages 
 The prefix of a unique package name is always written in all-lowercase ASCII
letters and should be one of the top-level domain names, like com, edu, gov,
mil, net, org.
 Subsequent components of the package name vary according to an
organization’s own internal naming conventions. (com.sun.eng,
com.apple.quick)
First Program
Package name

Class name

Method
argument
s

Access Return Method


modifier Static keyword
mean it’s data type name
belong to class
Data Type

 There is two categories of data


Object data
Primitive data (programmer created
types)
Type Description Size
True, false 1 bits String
Boolea Arrays
n Custom objects
Byte two's 8 bits
complement
integer
Char Character 16
bits
short two's 16
complement bits
integer
Int two's 32
complement bits
integer
Variables in Java

 A variable is the name given to a memory location. It is the basic unit


of storage in a program.
 The value stored in a variable can be changed during program
execution.
 A variable is only a name given to a memory location, all the
operations done on the variable effects that memory location.
 In Java, all the variables must be declared before use.
Types of variables
 Local Variables : A variable defined within a block or method or
constructor is called local variable.
 These variable are created when the block in entered or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
 The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access these variable only within that
block.
Example :
 Instance Variables: Instance variables are non-static variables and
are declared in a class outside any method, constructor or block.
 As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when
the object is destroyed.
 Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier then the default
access specifier will be used.
 Static Variables: Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static keyword
within a class outside any method constructor or block.
 Unlike instance variables, we can only have one copy of a static
variable per class irrespective of how many objects we create.
 Static variables are created at start of program execution and
destroyed automatically when execution ends.
 To access static variables, we need not to create any object of that
class, we can simply access the variable as:
class_name.variable_name.
Java Operator
 The Arithmetic Operators (+ , - , * , / , % , ++ , --)
 The Relational Operators (== (equal to) , != (not equal to) , > , < ,
>= , <=)
 The Logical Operators (&& (logical and) , || (logical or) , ! (logical not))
 The Assignment Operators (= , += , -= , *= , /= , %=)
 ternary operator (variable x = (expression) ? value if true : value if
false)
Methods in Java
 A Java method is a collection of statements that are grouped together to
perform an operation. When you call the System.out.println() method, for
example, the system actually executes several statements in order to display
a message on the console.
 modifier
Methods returnType nameOfMethod
Syntax
(Parameter List) {
Methods
// method body
signature
}
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value, if no value return it’s mean void.
 nameOfMethod − This is the method name. The method signature consists
of the method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
 method body − The method body defines what the method does with the
statements.
Control statements
 if: 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. Syntax :

if(condition)
statement1; if(condition) {
statement2; Statements to
Here if the condition is execute if condition
true, if block will consider is true
only statement1 to be inside }
its block.
 if-else: The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t.
But what if we want to do something else if the condition is false.
Here comes the else statement. We can use the else statement with if
statement to execute a block of code when the condition is false.
Syntax: if (condition) {
Executes this
block if condition
is true
} else {
Executes this block
if condition is
false
}
 nested-if: A nested if is an if statement that is the target of another
if or else. Nested if statements means an if statement inside an if
statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place anifif statement inside
(condition1) { another if
statement. Executes when condition1 is
Syntax: true
if (condition2) {
Executes when condition2 is
true
}
}
 if-else-if ladder: Here, a user can decide among multiple options.
The if statements are executed from the top down. As soon as one of
the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement; . .
else
statement;
 switch-case The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:

switch (expression) {
 Expression can be of type byte, short, int char or an enumeration. case value1:
Beginning with JDK7, expression can also be of type String. statement1;
 Dulplicate case values are not allowed. break;
case value2:
 The default statement is optional. statement2;
 The break statement is used inside the switch to terminate break;
a statement sequence. .

.
The break statement is optional. If omitted, execution will continue case valueN:
on into the next case. statementN;
break;
default:
statementDefault;
}
 For loop  used to repeat a set of statements until a particular condition is satisfied.
 Syntax of for loop.
for(initialization; condition ;
End of for increment/decrement) { statement(s);
loop }

 First step: In for loop, initialization happens first and only one time, which means that the
initialization part of for loop only executes once.
 Second step: Condition in for loop is evaluated on each iteration, if the condition is true
then the statements inside for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next statement in
the program after for loop.
 Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
 While loop  In while loop, condition is evaluated first and if it returns true then
the statements inside while loop execute. When condition returns false, the control
comes out of loop and jumps to the next statement after while loop.

while(condition) {
statement(s);
increment/decrement
}

 The important point to note when using while loop is that we need to use increment
or decrement statement inside while loop so that the loop variable gets
changed on each iteration, and at some point condition returns false. This way we
can end the execution of while loop otherwise the loop would execute indefinitely
 do-while  do-while loop is similar to while loop, except one thing difference
between them: In while loop, condition is evaluated before the execution
of loop’s body but in
do-while loop condition is evaluated after the execution of loop’s body.
 First, the statements inside loop execute and then the condition gets evaluated, if
the condition returns true then the control gets transferred
do to
{ the “do” else it
jumps to the next statement after do-while. statement(s);
increment/
decrement
}
while(condition);
 Continue statement  is mostly used inside loops.
 encountered inside a loop, control directly jumps to the beginning of the loop for next
iteration, skipping the execution of statements inside loop’s body for the current
iteration.
 useful when you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that particular
iteration.
continue;

 Output :

0 1 2 3 5 6
 Break statement  Use break statement to come out of the loop instantly.
 Whenever a break statement is encountered inside a loop, the control directly comes
out of loop and the loop gets terminated for rest of the iterations
 It is used along with if statement, whenever used inside loop so that the loop gets
terminated for a particular condition.
 The important point to note here is that when a break statement is used inside a
nested loop, then only the inner loop gets terminated.
 Output :
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop
Arrays
 An array is a group of like-typed variables that are referred to by a common name.
 In Java all arrays are dynamically allocated.
 A Java array variable can also be declared like other variables with [] after the data
type.
 The variables in the array are ordered and type varName[];
OR
each have an index beginning from 0.
type[] varName;
 Java array can be also be used as a static field,
a local variable or a method parameter.
 Array can contains primitives data types as well as objects of a class depending on
the definition of array.
 int intArray[]; //declaring array


intArray = new int[9]; // allocating memory to array.
 int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; // Declaring array literal
 Multidimensional Arrays  Multidimensional arrays are arrays of arrays with each
element of the array holding the reference of other array

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

 Output :
2 7 9
3 6 1
7 4 2
String Class
 string is an object that represents a sequence of characters.
 You can create a string object. String s1="Welcom
e";
String s2="Welcom
e";
String s=new String("Welcom
e");
creates two objects and o
ne
reference variable
 string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
StringBuffer VS StringBuilder
 Those classes similar to String class except that is used to create an mutable
(modifiable) string).
 The Java StringBuilder class is same as StringBuffer class except that it is non-
synchronized.
 Synchronized means thread safe.
 All methods in String class are representing in those classes with different name.
Object Oriented Programming
(OOP).
is a programming paradigm based on the concept of “objects” that
contain data and methods. The primary purpose of object-oriented
programming is to increase the flexibility and maintainability of
programs.
 What is an Object  the object is an instance of the class, that contain
a data and its behavior(often known as methods), They have states
and behaviors.
 Characteristics of Objects:
Abstraction: Abstraction is a process where you show only “relevant”
data and “hide” unnecessary details of an object from the user.

Encapsulation: Encapsulation simply means binding object


state(fields) and behavior(methods) together. If you are creating class,
you are doing encapsulation.
Message passing
A single object by itself may not be very useful. An application
contains many objects. One object interacts with another object by
invoking methods on that object. It is also referred to as Method
Invocation.
These characteristics represent a pure
approach to object-oriented programming

 Everything is an object. Think of an object as a fancy variable; it stores data, but you can “make
requests” to that object, asking it to perform operations on itself. In theory, you can take any conceptual
component in the problem you’re trying to solve (dogs, buildings, services, etc.) and represent it as an
object in your program.
 A program is a bunch of objects telling each other what to do by sending messages. To make
a request of an object, you “send a message” to that object. More concretely, you can think of a message as
a request to call a method that belongs to a particular object.

 Each object has its own memory made up of other objects. Put another way, you create a new
kind of object by making a package containing existing objects. Thus, you can build complexity into a
program while hiding it behind the simplicity of objects.

 Every object has a type. each object is an instance of a class, in which “class” is synonymous with
“type.” The most important distinguishing characteristic of a class is “What messages can you send to it?”

 All objects of a particular type can receive the same messages. This is actually a loaded
statement, as you will see later. Because an object of type “circle” is also an object of type “shape,” a circle
is guaranteed to accept shape messages. This means you can write code that talks to shapes and
automatically handle anything that fits the description of a shape.This substitutability is one of the
powerful concepts in OOP.
 Light
Light lt = new Light();
on();
lt.on();
off();
 the name of the type/class is Light. dim();
 the name of this particular Light object is lt. brighten();

 the requests that you can make of a Light object are to turn it on, turn it off,
make it brighter, or make it dimmer.
 You create a Light object by defining a “reference” (lt) for that object and
calling new to request a new object of that type.
 Every class has a Constructor.
 Constructor looks like a method but it is in fact not a method.
It’s name is same as class name and it does not return any value public class Light{
Int powerCapacity;
 Class can have more than one constructor (Parameterized constructor )

Public Light(){
}
Public Light(int
powerCa){
}

}
Encapsulation

 Make the instance variables private so that they cannot be


accessed directly from outside the class.
 Have getter and setter methods in the class to set
and get the values of the fields
 Refers to instance variable when calling the setter method
we use the keyword this (this called shadowing the variable)
Enum
 Enum in java is a special kind of Java class contains a collections of constants.
 Example of Enum public enum Level {
 You can refer to the constants in the enum. HIGH,
MEDIUM,
 You can use this Enum type in (if statement , switch , iterate over it’s values).
LOW
 Enum methds and fields used like this. }

Level level = Level.HIGH;


Level level = Level.valueOf("HIGH");
System.out.println(level.getLevelCo
de());

for (Level level :


Level.values())
{ System.out.println(level);
}
 And use the methods like this
Inheritance (is-A relation)
 the ability in Java for one class to inherit from another class. In Java this is also called
extending a class. One class can extend another class and thereby inherit from that class.
 When one class inherits from another class in Java, the two classes take on certain roles.
 can be an effective method to share code between classes that have some traits in common,
yet allowing the classes to have some parts that are different.
 The class that extends (inherits from another class) is the subclass and the shape
class that is being extended (the class being inherited from) is the superclass.
 When a subclass extends a superclass in Java, all protected and public fields
and methods of the superclass are inherited by the subclass.
by inherited is meant that these fields and methods are part of the circle Square
subclass, as if the subclass had declared them itself.
 The Java inheritance mechanism only allows a Java class to inherit from a single superclass.
 In Java inheritance is declared using the extends keyword.
Overriding Methods & Overload Methods
 In a subclass you can override (redefine) methods defined in the superclass.
 Reimplementation of the method defined by changing only the body of the method, that’s
mean
the methods signature (access modifier , return type, methodName, (parameters..) still
the same).
 In Java you cannot override private and final methods from a superclass. If the
superclass calls a private method internally from some other method, it will continue to
call that method from the superclass, even if you create a private method in the subclass
with the same signature.
public void disp(char c)
 Method Overloading: allows us to have more than one method with same name in a
{ System.out.println(c);
class but with different in signature and multi parameter.
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
Inheritance and Type Casting
(Polymorphism)

 Known as it is possible to reference a subclass as an instance of one of its superclass's.


 In the shape previous example it is possible to reference an instance of the Circle class as
an instance of the Shape class. Because the Circle class extends (inherits from) the Shape
class, it is also said to be a Shape.
 it is possible to use an instance of some subclass as if it were an Circle c= new Circle();
instance of its superclass. That way, you don't need to know exactly Shape s= c;
what subclass the object is an instance of. You could treat e.g. both
Circle and Square instances as Shape instances.
 Upcasting and Downcasting :
 You can always cast an object of a subclass to one of its super classes. This is referred to
as upcasting (from a subclass type to a superclass type).
 also it is possible to cast an object from a superclass type to a subclass type, but only if
the object really is an instance of that subclass (or an instance of a subclass of
that subclass). This is referred to as downcasting (from a superclass type to a subclass
type)
 The instanceof Instruction:
 Java contains an instruction named instanceof. The instanceof instruction can
determine whether a given object is an instance of some class.
 The instanceof instruction can also be used determine if an object is a instance of a
superclass of its class

Circle c= new Circle();


// upcast to Shpae
Shape s= c;
// downcast to Circle again
Circle c2= (Circle)s;
boolean isCircle = c instanceof Car;??
boolean isCircle = s instanceof Car;??
Square sq= new Square();
Shape sh=sq;
boolean isCircle = sq instanceof Square;??
boolean isCircle = sh instanceof Car;??
Abstract Classes
 a class which cannot be instantiated, meaning you cannot create new instances of an
abstract class.
 The purpose of an abstract class is to function as a base for subclasses.
 declare that a class is abstract by adding the abstract keyword to the class declaration.
 An abstract class can have abstract methods. You declare a
method abstract by adding the abstract keyword in front of the method declaration
Public abstract class SampleClass{
public abstract void
abstractMethod();

}
Now we can’t
SampleClass sample= new
SampleClass();
Interface
 an interface is used for full abstraction
 Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user
 Interface looks like a class but it is not a class
 An interface can have methods and variables just like the class but the methods
declared in interface are by default abstract (only method signature, no body).
 the variables declared in an interface are public, static & final by default.
 java programming language does not allow you to extend more than one class,
However you can implement more than one interfaces in your class.
class Test implements MyInterface
{
public void method1()
{ System.out.println("implementatio
n of method1"); interface MyInterface {
} public void method1();
public void method2() public void method2();
{ System.out.println("implementatio }
n of method2");
}
Interface in Java 8
 Java 8 allows the interfaces to have default and static methods.
 The reason we have default methods in interfaces is to allow the developers to add
new methods to the interfaces without affecting the classes that implements these
interfaces.
 An interface with only single abstract method is called functional interface.
 While creating your own functional interface, mark it with @FunctionalInterface
annotation, this annotation is introduced in Java 8.
@FunctionalInterface
 We define it by using new Lambda Expression in java interface
8 MyFunctionalInterface {
public int addMethod(int a, int b);
}

MyFunctionalInterface sum = (a, b) -> a + b;


System.out.println("Result:
"+sum.addMethod(12, 100));
Java Lambda Expressions
//Syntax of lambda expression
(parameter_list)
 Lambda expression is a new feature which is introduced in Java 8. ->
 A lambda expression is an anonymous function. {function_body}
 A function that doesn’t have a name and doesn’t belong to any class.
 To create a lambda expression, we specify input parameters (if there are any) on
the left side of the lambda operator ->.
 and place the expression or block of statements on the right side of lambda
operator.
 the lambda expression (x, y) -> x + y specifies that lambda expression takes two
arguments x and y and returns the sumAoflambda
these. expression in Java has these main parts:
Lambda expression only has body and
 Lambda expression vs method in Java
parameter list.
 A method in Java has these main parts: 1. No name – function is anonymous so we don’t
1. Name care about the name
2. Parameter list 2. Parameter list
3. Body 3. Body – This is the main part of the function.
4. return type. 4. No return type – The java 8 compiler is able to
infer the return type by checking the code. you
need not to mention it explicitly.
Exception Handling
 mechanism to handle the runtime errors so that normal flow of the application can be
maintained.
 an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
 advantage of exception handling is to maintain the normal flow of the application.
 Types of Java Exceptions
1. Checked Exception :  Checked exceptions are checked at compile-time, (IOException,
SQLException)
2. Unchecked Exception :  Unchecked exceptions are not checked at compile-time, but they are
checked at runtime, (ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException)
3. Error :  Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
 Java Exception Keywords (try , catch , finally ,throw , throws).
Type of java handling Exceptions

try{ try{
// //
code that may throw exception code that may throw exception

}catch(Exception_class_Name r }finally{
ef){} }

try{
//code that may throw exception
}catch(Exception_class_Name ref){

} catch(Exception_class_Name ref){

} catch(Exception_class_Name ref){

}
throw and throws
 Java throw keyword is used to explicitly throw an exception.
 Java throws keyword is used to declare an exception.
 Throw is followed by an instance (ref object)
 Throws is followed by class.
 Throw is used within the method.
 Throws is used with the method signature. void m()throws ArithmeticException
 You cannot throw multiple exceptions. {
//method code
 You can declare multiple exceptions }

void m(){ void m()throws ArithmeticException{


throw new ArithmeticException("sorry"); throw new ArithmeticException("sorry");
} }
Java I/O
 Java uses the concept of a stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
 A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
 In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. 1) System.out: standard output stream
2. 2) System.in: standard input stream
3. 3) System.err: standard error stream
 OutputStream vs InputStream:
 Java application uses an output stream to write data to a destination; it may be a file,
an array.
 Java application uses an input stream to read data from a source.
 examples

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");

FileInputStream fin=new FileInputStream("D:\\testout.txt");


int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();

You might also like