SlideShare a Scribd company logo
1 of 60
SKILLWISE- ELEM JAVA
Core & Advanced Java – Alpha
Batch
Unit-II
Elementary Java Programming
Topics
• Characteristics and Features of Java
Programming Language
• Understanding JVM, JRE and JIT
• Basic Primitive Data Types, Input / Output
Statements
• Conditional Constructs and Loops, (Extended
- For Loop is important), Arrays
• Writing Functions in Java
4
History of Java
• Conceived as Programming language for embedded systems like microwave
ovens, televisions etc
• One of the first projects developed using Java
• personal hand-held remote control named Star 7.
• The original language was called Oak
• Java was developed in the year 1991 at Sun Microsystems
– Java is a simple, object oriented, ,interpreted distributed, robust, secure,
architecture neutral, portable high-performance, multithreaded, and dynamic
language
5
The Architecture
• Java's architecture arises out of four distinct but interrelated technologies:
– the Java programming language
– the Java class file format
– the Java Application Programming Interface
– the Java virtual machine
Java• Java technology is:
– A programming language
– A development environment
– An application environment
– A deployment environment
– It is similar in syntax to C++.
– It is used for developing both applets and
applications.
6
Primary Goals of Java
• Provides an easy-to-use language by:
– Avoiding many pitfalls of other languages
– Being object-oriented
– Enabling users to create streamlined and clear code
• Provides an interpreted environment for:
– Improved speed of development
– Code portability
– Enables users to run more than one thread of activity
– Loads classes dynamically; that is, at the time they are actually needed
– Supports changing programs dynamically during runtime by loading
classes from disparate sources
– Furnishes better security
7
Goals of Java
• The following features fulfill these goals:
– The Java Virtual Machine (JVM)
– Garbage collection
– The Java Runtime Environment (JRE)
– JVM tool interface
8
9
The Java Virtual Machine
• Executes instructions that a Java compiler generates.
• This runtime environment, is embedded in various products, such as web browsers,
servers, and operating systems
• Its Imaginary machine that is implemented by emulating software on a real machine
• Bytecode
– a special machine language that can be understood by the JVM independent of
any particular computer hardware,
The Java Virtual Machine
• Provides hardware platform specifications
• Reads compiled byte codes that are platform-
independent
• Is implemented as software or hardware
• Is implemented in a Java technology
development tool or a Web browser
10
The Java Virtual Machine
• JVM provides definitions for the:
– Instruction set (central processing unit [CPU])
– Register set
– Class file format
– Stack
– Garbage-collected heap
– Memory area
– Fatal error reporting
– High-precision timing support
11
The Java Virtual Machine
• The majority of type checking is done when
the code is compiled.
• Implementation of the JVM approved by Sun
Microsystems must be able to run any
compliant class file.
• The JVM executes on multiple operating
environments
12
13
Garbage Collection
• Garbage collection thread is responsible for freeing any memory that can be
freed. This happens automatically during the lifetime of the Java program.
• Programmer is freed from the burden of having to deallocate that memory
themselves
Garbage Collection
• Allocated memory that is no longer needed
should be deallocated.
• In other languages, deallocation is the
programmer’s responsibility.
• The Java programming language provides a
system-level thread to track memory allocation.
• Garbage collection has the following
characteristics:
– Checks for and frees memory no longer needed
– Is done automatically
– Can vary dramatically across JVM implementations
14
JVM™ Tasks
• The JVM performs three main tasks:
• Loads code
• Verifies code
• Executes code
15
The Class Loader
• Loads all classes necessary for the execution
of a program
• Maintains classes of the local file system in
separate namespaces
• Prevents spoofing
16
The Bytecode Verifier
• Ensures that:
– The code adheres to the JVM specification.
– The code does not violate system integrity.
– The code causes no operand stack overflows or
underflows.
– The parameter types for all operational code are correct.
– No illegal data conversions (the conversion of integers to
pointers) have occurred.
17
18
Application and Runtime Environment
• The JRE of the SDK contains the complete set of class files for all the Java
technology packages, which includes basic language classes, GUI
component classes, and so on.
• The Java Application Programming Interface (API) is prewritten code,
organized into packages of similar topics.
• Applet and AWT packages include classes for creating fonts,
menus, and buttons. The full Java API is included in the Java 2
Standard Edition
19
Application and Runtime Environment
• J2SE includes the essential compiler, tools, runtimes, and APIs for writing,
deploying, and running applets and applications in the Java programming
language.
• JDK is the short-cut name for the set of Java development tools, consisting of the
API classes, a Java compiler, and the Java virtual machine interpreter, regardless of
which version.
• The JDK is used to compile Java applications and applets. The most current version
is the J2SE is 6.0
Java Run Time Environment
20
21
Compile time and Runtime
Environment
22
Phases of a Java Program
• The following figure describes the process of compiling and
executing a Java program
23
Compile (javac command)
execute (java command)
JJaavvaa ssoouurrccee
ccooddee
((..jjaavvaa))
WWiinnddoowwss OOSS OOtthheerr OOSSUUnniixx OOSS
JJVVMM JJVVMM JJVVMM
BByytteeccooddeess
((..ccllaassss))
24
Integrated Development Environments
• An IDE is the high-productivity tool
• Used to edit, compile, and test programs, manage projects, debugging, building
GUI interfaces, etc.
• IDE provides extensive programming support for editing and project management,
• The Popular IDE’s
 Eclipse
 NetBeans
 JDeveloper
Java language syntax
26
Objectives
 Identify the basic parts of a Java program
 Differentiate among Java literals, primitive data types,
 variable types ,identifiers and operators
 Develop a simple valid Java program using the concepts learned in this chapter
27
Program structure
• A program in Java consists of one or more class definitions
• One of these classes must define a method main(), which is where the
program starts running
 Java programs should always end with the .java extension.
 There can be More than one Class Definition in a class ,but only one public
class
 Source Filenames should match the name of the public class.
Source File Layout
• Basic syntax of a Java source file is:
• [<package_declaration>]
• <import_declaration>*
• <class_declaration>+
28
Software Packages
• Packages help manage large software systems.
• Packages can contain classes and sub-packages.
• Basic syntax of the package statement is:
• package <top_pkg_name>[.<sub_pkg_name>]*;
• Specify the package declaration at the beginning of the source file.
• Only one package declaration per source file.
• If no package is declared, then the class is placed into the default package.
• Package names must be hierarchical and separated by dots.
29
The import Statement
• Basic syntax of the import statement is:
• import
<pkg_name>[.<sub_pkg_name>]*.<class_name>
;
• import <pkg_name>[.<sub_pkg_name>]*.*;
• import java.util.List;
• import java.io.*;
• import shipping.gui.reportscreens.*;
• The import statement does the following:
– Precedes all class declarations
– Tells the compiler where to find classes
30
31
Example 1.1
package com.training;
public class Greetings {
public String getMessage() {
return "Welcome to Java Programming";
}
}
32
Example 1.1 (contd)
package com.training;
public class TestGreetings {
public static void main(String[] args) {
Greetings grtObj = new Greetings();
System.out.println(grtObj.getMessage());
}
}
33
The System Class
• Its part of the java.lang package
• The classes in this package are available without the need for an import statement
• This class contains several useful class fields and methods.
• It can’t be Instantiated
• It also Provides facilities for
– Standard Input
– Standard Output
– Error Output Streams
– Access to externally defined properties
34
Variables and Methods
• A variable, which corresponds to an attribute, is a named memory location that
can store a certain type of value.
• Variable is a kind of special container that can only hold objects of a certain type.
• Primitive type Variable
• Basic, built-in types that are part of the Java language
• Two basic categories
– boolean
– Numeric
» Integral - byte, short, int, long, char
» Floating point - float, double
35
Instance Variables and Methods
• Variables and methods can be associated either with objects or their classes
• An instance variable and instance method belongs to an object.
• They can have any one of the four access levels
– Three access modifies – private, public , protected
– Can be Marked final, transient
• They have a default value
• A class variable (or class method) is a variable (or method) that is associated with
the class itself.
36
Example for Variables
public class VariableTypes {
private int inst_empid;
private static String cls_empName
public void getData() { }
public static void getSalary() { }
public void showData(int a)
{
int localVariable ;
}
}
Instance
Variable
Local Variable
Parameter
Variable
Class
Variable
37
Identifiers
• Identifiers are used to name variables, methods, classes and interfaces
• Identifiers
– start with an alphabetic character
– can contain letters, digits, or “_”
– are unlimited in length
• Examples
– answer, total, last_total, relativePoint, gridElement, person, place,
stack, queue
38
Initialization
• Local variables
– must be explicitly initialized before use
• Parameter variables
– Pass by value
• Class and instance variables
– Instance variables Have a Default Value
39
Local Variable needs to Be Initialized
public class LocalVariable {
private String name;
public void display()
{
int age;
System.out.println("Age"+age);
System.out.println("Name"+name);
}
Age Should be
Initialized before
Use
40
Instance Variable have Default Values
class Values
{
private int a;
private float b;
private String c;
public void display()
{
System.out.println("integer"+a);
System.out.println("float"+b);
System.out.println("String"+c);
}
public class DefaultVales {
public static void main(String[] args) {
Values v = new Values();
v.display();
}
}
41
7
7
0x01234
0x01234
x
y
s
t
Hello
Assignment of reference variables
int x = 7;
int y = x;
String s = “Hello”;
String t = s;
42
Pass-by-Value
• The Java programming language only passes arguments by value for
primitive data types.
• When an object instance is passed as an argument to a method, the
value of the argument is a reference to the object
• The contents of the object can be changed in the called method, but the
object reference is never changed
• For primitives, you pass a copy of the actual value.
• For references to objects, you pass a copy of the reference
• You never pass the object. All objects are stored on the heap.
43
Pass By Value
44
Casting Primitive Types
• Casting creates a new value and allows it to be treated as a different type
than its source
• JVM can implicitly promote from a narrower type to a wider type
• To change to a narrow type explicit casting is required
• Byte -> short -> int -> long -> float -> double
45
Casting Primitive Types
public class PrimCasting {
public static void main (String [] args){
int x = 99;
double y = 5.77;
x = (int)y; //Casting
System.out.println("x = "+ x);
double y1 = x; //No Casting
int i =42;
byte bt;
bt= (byte)i;
System.out.println("The Short number"+ bt);
}
}
46
Control Structures
• To change the ordering of the statements in a program
• Two types of Control Structures
• decision control structures ,
– allows us to select specific sections of code to be executed
• if -- else , if – else if
• switch -- case
• repetition control structures
– allows us to execute specific sections of the code a number of times
• while
• do -- while
• for
47
Decision Control Structures
• Types:
– if-statement
– if-else-statement
– If-else if-statement
• If Specifies that a statement or block of code will be executed if and only if a
certain boolean statement is true.
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
}
• boolean_expression : can be an expression or variable.
48
if-else statement
if( boolean_exp ){
Statement(s)
}
else {
Statement(s)
}
if(boolean_exp1 )
statement1;
else if(boolean_exp2)
statement2;
else
statement3;
 For Comparison == used instead =
 = being an assignment operator
 equals Method Should Be Used for Objects comparison
49
switch-statement
• Allows branching on multiple outcomes.
• switch expression is an integer ,character expression or variable
• case_selector1, case_selector2 and unique integer or character constants.
• If none of the cases are satisfied, the optional default block if present is
executed.
switch( switch_expression ){
case case_selector1:
Statement(s);
break;
case case_selector2:
Statement(s);
break;
default:
statement1;
}
50
switch-statement
• When a switch is encountered,
– evaluates the switch_expression,
– jumps to the case whose selector matches the value of the expression.
– executes the statements in order from that point on until a break statement is
encountered
– break statement stops executing statements in the subsequent cases, it will be
last statement in a case.
– Used to make decisions based only on a single integer or character value.
– The value provided to each case statement must be unique.
51
switch-statementpublic double CalculateDiscount(int pCode)
{
double discountPercentage=0.0d;
switch(pCode)
{
case 1:
discountPercentage=0.10d;
break;
case 2:
discountPercentage=0.15d;
break;
case 3:
discountPercentage=0.20d;
break;
default:
discountPercentage=0.0;
}
return discountPercentage;
}
Switch-Case in a Method
• Can have Either Return or Break if present inside a
Method, but should provide a default Value
public String switchExample(int key) {
switch (key) {
case 1:
return "Good Morning";
case 2:
return "Good AfterNoon";
case 3:
return "Good Evening";
default:
return "Good Night";
}
52
53
Repetition Control Structures
• while-loop
– The statements inside the while loop are executed as long as the Boolean
expression evaluates to true
• do-while loop
– statements inside a do-while loop are executed several times as long as the
condition is satisfied, the statements inside a do-while loop are executed at
least once
while(boolean_expression){
statement1;
statement2;
}
do{
statement1;
statement2;
}while(boolean_expression);
Watch
this
54
for-loop
• Same code a number of times.
• for(Initialexpr;LoopCondition;StepExpr) {
statement1;
}
• InitialExpression -initializes the loop variable.
• LoopCondition - compares the loop variable to some limit value.
• StepExpr - updates the loop variable.
for( ; ; ) {
System.out.println("Inside an endless loop");
}
• Declaration parts are left out so the for loop will act like
an endless loop.
55
Enhanced For Loop
• The enhanced for loop, simplifies looping through an array or a collection.
• Instead of having three components, the enhanced for has two.
• declaration
– The newly declared block variable, of a type compatible with the elements of
the array being accessed.
• expression
– This must evaluate to the array you want to loop through. This could be an
array variable or a method call that returns an array
• int [] a = {1,2,3,4};
• for(int n : a)
• System.out.print(n);.
56
Branching Statements
• Branching statements allows to redirect the flow of program execution.
– break
– continue
– return.
• System.exit() All program execution stops; the VM shuts down.
57
Branching Statement
• continue
• Unlabeled
– skips to the end of the innermost loop's body and evaluates the Boolean
expression that controls the loop,
– skipping the remainder of this iteration of the loop.
• Labeled :
– skips the current iteration of an outer loop marked with the given label.
• return
– Used to exit from the current Method
– Control returns to the statement that follows original method call
– The value to be returned is included after the “return” statement.
– The data value returned by return must match the type of the method's declared
return value
• return ++count; or return "Hello";
Continuepublic static void main(String[] args) {
for(int i=0;i<=2;i++)
{
for(int j=0;j<=3;j++)
{
if(j % 2==0)
continue;
System.out.println("I ,"+i+",J "+j);
}
}
58
I ,0,J 1
I ,0,J 3
I ,1,J 1
I ,1,J 3
I ,2,J 1
I ,2,J 3
breakpublic static void main(String[] args) {
for(int i=0;i<=2;i++)
{
for(int j=0;j<=5;j++)
{
System.out.println(i+","+j);
if(j==3)
break;
}
}
59
0,0
0,1
0,2
0,3
1,0
1,1
1,2
1,3
2,0
2,1
2,2
2,3
Skillwise Elementary Java Programming

More Related Content

What's hot

java training in jaipur|java training|core java training|java training compa...
 java training in jaipur|java training|core java training|java training compa... java training in jaipur|java training|core java training|java training compa...
java training in jaipur|java training|core java training|java training compa...infojaipurinfo Jaipur
 
1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology dM Technologies
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.Bhautik Jethva
 
Java introduction
Java introductionJava introduction
Java introductionKuppusamy P
 
JAVA ENVIRONMENT
JAVA  ENVIRONMENTJAVA  ENVIRONMENT
JAVA ENVIRONMENTjosemachoco
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSteve Fort
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javajayc8586
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAMehak Tawakley
 
Java and internet fundamentals.
Java and internet fundamentals.Java and internet fundamentals.
Java and internet fundamentals.mali yogesh kumar
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 

What's hot (20)

Java basics notes
Java basics notesJava basics notes
Java basics notes
 
java training in jaipur|java training|core java training|java training compa...
 java training in jaipur|java training|core java training|java training compa... java training in jaipur|java training|core java training|java training compa...
java training in jaipur|java training|core java training|java training compa...
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology
 
Java introduction
Java introductionJava introduction
Java introduction
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Features of java
Features of javaFeatures of java
Features of java
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Java introduction
Java introductionJava introduction
Java introduction
 
JAVA ENVIRONMENT
JAVA  ENVIRONMENTJAVA  ENVIRONMENT
JAVA ENVIRONMENT
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
The Java Story
The Java StoryThe Java Story
The Java Story
 
Java and internet fundamentals.
Java and internet fundamentals.Java and internet fundamentals.
Java and internet fundamentals.
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 

Similar to Skillwise Elementary Java Programming

JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxMurugesh33
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxMurugesh33
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptRajeshSukte1
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptCDSukte
 
JAVA object oriented programming (oop).ppt
JAVA object oriented programming (oop).pptJAVA object oriented programming (oop).ppt
JAVA object oriented programming (oop).pptAliyaJav
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdprat0ham
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptxSmitNikumbh
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf10322210023
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.pptSmitaBorkar9
 

Similar to Skillwise Elementary Java Programming (20)

Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
1 java introduction
1 java introduction1 java introduction
1 java introduction
 
1 java intro
1 java intro1 java intro
1 java intro
 
JAVA object oriented programming (oop).ppt
JAVA object oriented programming (oop).pptJAVA object oriented programming (oop).ppt
JAVA object oriented programming (oop).ppt
 
1.Intro--Why Java.pptx
1.Intro--Why Java.pptx1.Intro--Why Java.pptx
1.Intro--Why Java.pptx
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptx
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
 
Lesson1 intro
Lesson1 introLesson1 intro
Lesson1 intro
 

More from Skillwise Group

Skillwise Consulting New updated
Skillwise Consulting New updatedSkillwise Consulting New updated
Skillwise Consulting New updatedSkillwise Group
 
Retailing & logistics profile
Retailing & logistics profileRetailing & logistics profile
Retailing & logistics profileSkillwise Group
 
Overview- Skillwise Consulting
Overview- Skillwise Consulting Overview- Skillwise Consulting
Overview- Skillwise Consulting Skillwise Group
 
Skillwise corporate presentation
Skillwise corporate presentationSkillwise corporate presentation
Skillwise corporate presentationSkillwise Group
 
Skillwise Softskill Training Workshop
Skillwise Softskill Training WorkshopSkillwise Softskill Training Workshop
Skillwise Softskill Training WorkshopSkillwise Group
 
Skillwise Insurance profile
Skillwise Insurance profileSkillwise Insurance profile
Skillwise Insurance profileSkillwise Group
 
Skillwise Train and Hire Services
Skillwise Train and Hire ServicesSkillwise Train and Hire Services
Skillwise Train and Hire ServicesSkillwise Group
 
Skillwise Digital Technology
Skillwise Digital Technology Skillwise Digital Technology
Skillwise Digital Technology Skillwise Group
 
Skillwise Boot Camp Training
Skillwise Boot Camp TrainingSkillwise Boot Camp Training
Skillwise Boot Camp TrainingSkillwise Group
 
Skillwise Academy Profile
Skillwise Academy ProfileSkillwise Academy Profile
Skillwise Academy ProfileSkillwise Group
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSkillwise Group
 
Skillwise - Business writing
Skillwise - Business writing Skillwise - Business writing
Skillwise - Business writing Skillwise Group
 

More from Skillwise Group (20)

Skillwise Consulting New updated
Skillwise Consulting New updatedSkillwise Consulting New updated
Skillwise Consulting New updated
 
Email Etiquette
Email Etiquette Email Etiquette
Email Etiquette
 
Healthcare profile
Healthcare profileHealthcare profile
Healthcare profile
 
Manufacturing courses
Manufacturing coursesManufacturing courses
Manufacturing courses
 
Retailing & logistics profile
Retailing & logistics profileRetailing & logistics profile
Retailing & logistics profile
 
Skillwise orientation
Skillwise orientationSkillwise orientation
Skillwise orientation
 
Overview- Skillwise Consulting
Overview- Skillwise Consulting Overview- Skillwise Consulting
Overview- Skillwise Consulting
 
Skillwise corporate presentation
Skillwise corporate presentationSkillwise corporate presentation
Skillwise corporate presentation
 
Skillwise Profile
Skillwise ProfileSkillwise Profile
Skillwise Profile
 
Skillwise Softskill Training Workshop
Skillwise Softskill Training WorkshopSkillwise Softskill Training Workshop
Skillwise Softskill Training Workshop
 
Skillwise Insurance profile
Skillwise Insurance profileSkillwise Insurance profile
Skillwise Insurance profile
 
Skillwise Train and Hire Services
Skillwise Train and Hire ServicesSkillwise Train and Hire Services
Skillwise Train and Hire Services
 
Skillwise Digital Technology
Skillwise Digital Technology Skillwise Digital Technology
Skillwise Digital Technology
 
Skillwise Boot Camp Training
Skillwise Boot Camp TrainingSkillwise Boot Camp Training
Skillwise Boot Camp Training
 
Skillwise Academy Profile
Skillwise Academy ProfileSkillwise Academy Profile
Skillwise Academy Profile
 
Skillwise Overview
Skillwise OverviewSkillwise Overview
Skillwise Overview
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
Skillwise - Business writing
Skillwise - Business writing Skillwise - Business writing
Skillwise - Business writing
 
Imc.ppt
Imc.pptImc.ppt
Imc.ppt
 
Skillwise cics part 1
Skillwise cics part 1Skillwise cics part 1
Skillwise cics part 1
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 

Skillwise Elementary Java Programming

  • 2. Core & Advanced Java – Alpha Batch Unit-II Elementary Java Programming
  • 3. Topics • Characteristics and Features of Java Programming Language • Understanding JVM, JRE and JIT • Basic Primitive Data Types, Input / Output Statements • Conditional Constructs and Loops, (Extended - For Loop is important), Arrays • Writing Functions in Java
  • 4. 4 History of Java • Conceived as Programming language for embedded systems like microwave ovens, televisions etc • One of the first projects developed using Java • personal hand-held remote control named Star 7. • The original language was called Oak • Java was developed in the year 1991 at Sun Microsystems – Java is a simple, object oriented, ,interpreted distributed, robust, secure, architecture neutral, portable high-performance, multithreaded, and dynamic language
  • 5. 5 The Architecture • Java's architecture arises out of four distinct but interrelated technologies: – the Java programming language – the Java class file format – the Java Application Programming Interface – the Java virtual machine
  • 6. Java• Java technology is: – A programming language – A development environment – An application environment – A deployment environment – It is similar in syntax to C++. – It is used for developing both applets and applications. 6
  • 7. Primary Goals of Java • Provides an easy-to-use language by: – Avoiding many pitfalls of other languages – Being object-oriented – Enabling users to create streamlined and clear code • Provides an interpreted environment for: – Improved speed of development – Code portability – Enables users to run more than one thread of activity – Loads classes dynamically; that is, at the time they are actually needed – Supports changing programs dynamically during runtime by loading classes from disparate sources – Furnishes better security 7
  • 8. Goals of Java • The following features fulfill these goals: – The Java Virtual Machine (JVM) – Garbage collection – The Java Runtime Environment (JRE) – JVM tool interface 8
  • 9. 9 The Java Virtual Machine • Executes instructions that a Java compiler generates. • This runtime environment, is embedded in various products, such as web browsers, servers, and operating systems • Its Imaginary machine that is implemented by emulating software on a real machine • Bytecode – a special machine language that can be understood by the JVM independent of any particular computer hardware,
  • 10. The Java Virtual Machine • Provides hardware platform specifications • Reads compiled byte codes that are platform- independent • Is implemented as software or hardware • Is implemented in a Java technology development tool or a Web browser 10
  • 11. The Java Virtual Machine • JVM provides definitions for the: – Instruction set (central processing unit [CPU]) – Register set – Class file format – Stack – Garbage-collected heap – Memory area – Fatal error reporting – High-precision timing support 11
  • 12. The Java Virtual Machine • The majority of type checking is done when the code is compiled. • Implementation of the JVM approved by Sun Microsystems must be able to run any compliant class file. • The JVM executes on multiple operating environments 12
  • 13. 13 Garbage Collection • Garbage collection thread is responsible for freeing any memory that can be freed. This happens automatically during the lifetime of the Java program. • Programmer is freed from the burden of having to deallocate that memory themselves
  • 14. Garbage Collection • Allocated memory that is no longer needed should be deallocated. • In other languages, deallocation is the programmer’s responsibility. • The Java programming language provides a system-level thread to track memory allocation. • Garbage collection has the following characteristics: – Checks for and frees memory no longer needed – Is done automatically – Can vary dramatically across JVM implementations 14
  • 15. JVM™ Tasks • The JVM performs three main tasks: • Loads code • Verifies code • Executes code 15
  • 16. The Class Loader • Loads all classes necessary for the execution of a program • Maintains classes of the local file system in separate namespaces • Prevents spoofing 16
  • 17. The Bytecode Verifier • Ensures that: – The code adheres to the JVM specification. – The code does not violate system integrity. – The code causes no operand stack overflows or underflows. – The parameter types for all operational code are correct. – No illegal data conversions (the conversion of integers to pointers) have occurred. 17
  • 18. 18 Application and Runtime Environment • The JRE of the SDK contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on. • The Java Application Programming Interface (API) is prewritten code, organized into packages of similar topics. • Applet and AWT packages include classes for creating fonts, menus, and buttons. The full Java API is included in the Java 2 Standard Edition
  • 19. 19 Application and Runtime Environment • J2SE includes the essential compiler, tools, runtimes, and APIs for writing, deploying, and running applets and applications in the Java programming language. • JDK is the short-cut name for the set of Java development tools, consisting of the API classes, a Java compiler, and the Java virtual machine interpreter, regardless of which version. • The JDK is used to compile Java applications and applets. The most current version is the J2SE is 6.0
  • 20. Java Run Time Environment 20
  • 21. 21 Compile time and Runtime Environment
  • 22. 22 Phases of a Java Program • The following figure describes the process of compiling and executing a Java program
  • 23. 23 Compile (javac command) execute (java command) JJaavvaa ssoouurrccee ccooddee ((..jjaavvaa)) WWiinnddoowwss OOSS OOtthheerr OOSSUUnniixx OOSS JJVVMM JJVVMM JJVVMM BByytteeccooddeess ((..ccllaassss))
  • 24. 24 Integrated Development Environments • An IDE is the high-productivity tool • Used to edit, compile, and test programs, manage projects, debugging, building GUI interfaces, etc. • IDE provides extensive programming support for editing and project management, • The Popular IDE’s  Eclipse  NetBeans  JDeveloper
  • 26. 26 Objectives  Identify the basic parts of a Java program  Differentiate among Java literals, primitive data types,  variable types ,identifiers and operators  Develop a simple valid Java program using the concepts learned in this chapter
  • 27. 27 Program structure • A program in Java consists of one or more class definitions • One of these classes must define a method main(), which is where the program starts running  Java programs should always end with the .java extension.  There can be More than one Class Definition in a class ,but only one public class  Source Filenames should match the name of the public class.
  • 28. Source File Layout • Basic syntax of a Java source file is: • [<package_declaration>] • <import_declaration>* • <class_declaration>+ 28
  • 29. Software Packages • Packages help manage large software systems. • Packages can contain classes and sub-packages. • Basic syntax of the package statement is: • package <top_pkg_name>[.<sub_pkg_name>]*; • Specify the package declaration at the beginning of the source file. • Only one package declaration per source file. • If no package is declared, then the class is placed into the default package. • Package names must be hierarchical and separated by dots. 29
  • 30. The import Statement • Basic syntax of the import statement is: • import <pkg_name>[.<sub_pkg_name>]*.<class_name> ; • import <pkg_name>[.<sub_pkg_name>]*.*; • import java.util.List; • import java.io.*; • import shipping.gui.reportscreens.*; • The import statement does the following: – Precedes all class declarations – Tells the compiler where to find classes 30
  • 31. 31 Example 1.1 package com.training; public class Greetings { public String getMessage() { return "Welcome to Java Programming"; } }
  • 32. 32 Example 1.1 (contd) package com.training; public class TestGreetings { public static void main(String[] args) { Greetings grtObj = new Greetings(); System.out.println(grtObj.getMessage()); } }
  • 33. 33 The System Class • Its part of the java.lang package • The classes in this package are available without the need for an import statement • This class contains several useful class fields and methods. • It can’t be Instantiated • It also Provides facilities for – Standard Input – Standard Output – Error Output Streams – Access to externally defined properties
  • 34. 34 Variables and Methods • A variable, which corresponds to an attribute, is a named memory location that can store a certain type of value. • Variable is a kind of special container that can only hold objects of a certain type. • Primitive type Variable • Basic, built-in types that are part of the Java language • Two basic categories – boolean – Numeric » Integral - byte, short, int, long, char » Floating point - float, double
  • 35. 35 Instance Variables and Methods • Variables and methods can be associated either with objects or their classes • An instance variable and instance method belongs to an object. • They can have any one of the four access levels – Three access modifies – private, public , protected – Can be Marked final, transient • They have a default value • A class variable (or class method) is a variable (or method) that is associated with the class itself.
  • 36. 36 Example for Variables public class VariableTypes { private int inst_empid; private static String cls_empName public void getData() { } public static void getSalary() { } public void showData(int a) { int localVariable ; } } Instance Variable Local Variable Parameter Variable Class Variable
  • 37. 37 Identifiers • Identifiers are used to name variables, methods, classes and interfaces • Identifiers – start with an alphabetic character – can contain letters, digits, or “_” – are unlimited in length • Examples – answer, total, last_total, relativePoint, gridElement, person, place, stack, queue
  • 38. 38 Initialization • Local variables – must be explicitly initialized before use • Parameter variables – Pass by value • Class and instance variables – Instance variables Have a Default Value
  • 39. 39 Local Variable needs to Be Initialized public class LocalVariable { private String name; public void display() { int age; System.out.println("Age"+age); System.out.println("Name"+name); } Age Should be Initialized before Use
  • 40. 40 Instance Variable have Default Values class Values { private int a; private float b; private String c; public void display() { System.out.println("integer"+a); System.out.println("float"+b); System.out.println("String"+c); } public class DefaultVales { public static void main(String[] args) { Values v = new Values(); v.display(); } }
  • 41. 41 7 7 0x01234 0x01234 x y s t Hello Assignment of reference variables int x = 7; int y = x; String s = “Hello”; String t = s;
  • 42. 42 Pass-by-Value • The Java programming language only passes arguments by value for primitive data types. • When an object instance is passed as an argument to a method, the value of the argument is a reference to the object • The contents of the object can be changed in the called method, but the object reference is never changed • For primitives, you pass a copy of the actual value. • For references to objects, you pass a copy of the reference • You never pass the object. All objects are stored on the heap.
  • 44. 44 Casting Primitive Types • Casting creates a new value and allows it to be treated as a different type than its source • JVM can implicitly promote from a narrower type to a wider type • To change to a narrow type explicit casting is required • Byte -> short -> int -> long -> float -> double
  • 45. 45 Casting Primitive Types public class PrimCasting { public static void main (String [] args){ int x = 99; double y = 5.77; x = (int)y; //Casting System.out.println("x = "+ x); double y1 = x; //No Casting int i =42; byte bt; bt= (byte)i; System.out.println("The Short number"+ bt); } }
  • 46. 46 Control Structures • To change the ordering of the statements in a program • Two types of Control Structures • decision control structures , – allows us to select specific sections of code to be executed • if -- else , if – else if • switch -- case • repetition control structures – allows us to execute specific sections of the code a number of times • while • do -- while • for
  • 47. 47 Decision Control Structures • Types: – if-statement – if-else-statement – If-else if-statement • If Specifies that a statement or block of code will be executed if and only if a certain boolean statement is true. if( boolean_expression ) statement; or if( boolean_expression ){ statement1; statement2; } • boolean_expression : can be an expression or variable.
  • 48. 48 if-else statement if( boolean_exp ){ Statement(s) } else { Statement(s) } if(boolean_exp1 ) statement1; else if(boolean_exp2) statement2; else statement3;  For Comparison == used instead =  = being an assignment operator  equals Method Should Be Used for Objects comparison
  • 49. 49 switch-statement • Allows branching on multiple outcomes. • switch expression is an integer ,character expression or variable • case_selector1, case_selector2 and unique integer or character constants. • If none of the cases are satisfied, the optional default block if present is executed. switch( switch_expression ){ case case_selector1: Statement(s); break; case case_selector2: Statement(s); break; default: statement1; }
  • 50. 50 switch-statement • When a switch is encountered, – evaluates the switch_expression, – jumps to the case whose selector matches the value of the expression. – executes the statements in order from that point on until a break statement is encountered – break statement stops executing statements in the subsequent cases, it will be last statement in a case. – Used to make decisions based only on a single integer or character value. – The value provided to each case statement must be unique.
  • 51. 51 switch-statementpublic double CalculateDiscount(int pCode) { double discountPercentage=0.0d; switch(pCode) { case 1: discountPercentage=0.10d; break; case 2: discountPercentage=0.15d; break; case 3: discountPercentage=0.20d; break; default: discountPercentage=0.0; } return discountPercentage; }
  • 52. Switch-Case in a Method • Can have Either Return or Break if present inside a Method, but should provide a default Value public String switchExample(int key) { switch (key) { case 1: return "Good Morning"; case 2: return "Good AfterNoon"; case 3: return "Good Evening"; default: return "Good Night"; } 52
  • 53. 53 Repetition Control Structures • while-loop – The statements inside the while loop are executed as long as the Boolean expression evaluates to true • do-while loop – statements inside a do-while loop are executed several times as long as the condition is satisfied, the statements inside a do-while loop are executed at least once while(boolean_expression){ statement1; statement2; } do{ statement1; statement2; }while(boolean_expression); Watch this
  • 54. 54 for-loop • Same code a number of times. • for(Initialexpr;LoopCondition;StepExpr) { statement1; } • InitialExpression -initializes the loop variable. • LoopCondition - compares the loop variable to some limit value. • StepExpr - updates the loop variable. for( ; ; ) { System.out.println("Inside an endless loop"); } • Declaration parts are left out so the for loop will act like an endless loop.
  • 55. 55 Enhanced For Loop • The enhanced for loop, simplifies looping through an array or a collection. • Instead of having three components, the enhanced for has two. • declaration – The newly declared block variable, of a type compatible with the elements of the array being accessed. • expression – This must evaluate to the array you want to loop through. This could be an array variable or a method call that returns an array • int [] a = {1,2,3,4}; • for(int n : a) • System.out.print(n);.
  • 56. 56 Branching Statements • Branching statements allows to redirect the flow of program execution. – break – continue – return. • System.exit() All program execution stops; the VM shuts down.
  • 57. 57 Branching Statement • continue • Unlabeled – skips to the end of the innermost loop's body and evaluates the Boolean expression that controls the loop, – skipping the remainder of this iteration of the loop. • Labeled : – skips the current iteration of an outer loop marked with the given label. • return – Used to exit from the current Method – Control returns to the statement that follows original method call – The value to be returned is included after the “return” statement. – The data value returned by return must match the type of the method's declared return value • return ++count; or return "Hello";
  • 58. Continuepublic static void main(String[] args) { for(int i=0;i<=2;i++) { for(int j=0;j<=3;j++) { if(j % 2==0) continue; System.out.println("I ,"+i+",J "+j); } } 58 I ,0,J 1 I ,0,J 3 I ,1,J 1 I ,1,J 3 I ,2,J 1 I ,2,J 3
  • 59. breakpublic static void main(String[] args) { for(int i=0;i<=2;i++) { for(int j=0;j<=5;j++) { System.out.println(i+","+j); if(j==3) break; } } 59 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2 2,3