Chapter 2 Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

CHAPTER TWO

Introduction to
Java Programming
1
Introduction to Java programming
Java
 write once, run anywhere

 is a platform independent programming language

 similar to C++ in syntax

 pros: also ubiquitous /omnipresent to net

 Cons: interpreted, and still under development(moving target)

 Features of java program

 Automatic type checking


 Simplifies pointers: no directly accessible pointer to
memory
 Simplified network access
 Multi-threading
 Automatic garbage collection
 Java performs automatic garbage collection of memory to help
return memory back to the system.
 When an object is no longer used in the program (i.e., there are no
2
references to the object), the object is marked for garbage
collection.
 The memory for such an object can be reclaimed when the
CONT’D
 Java is independent only for one reason
 Only depends on the Java Virtual Machine(JVM)
 Code is compiled to bytecode, which is interpreted by
the resident JVM
 JIT(just in time) compilers attempt to increase speed
 An intermediate step between interpreters and
compilers is a just-in-time (JIT) compiler that, as the
interpreter runs, produces compiled code for the
programs and executes the programs in machine
language rather than reinterpreting them.
 JIT compilers do not produce machine language that is
as efficient as a full compiler
 Portable- write once, run anywhere
 Security has been well thought through
3
 Robust memory management

 making your program fault tolerant (handling


CONT’D
 Dynamic and extensible(loads of libraries)
 Classesstored in separate files
 Loaded only when needed
 A bytecode is a special machine language that
can be understood by the Java Virtual Machine
(JVM).
 The bytecode is independent of any particular

computer hardware, so any computer with a Java


interpreter can execute the compiled Java
program, no matter what type of computer the
program was compiled on.
 The JVM provides the hardware platform
4
specifications to which you compile all Java
technology code
The JVM and Byte Code

 The Java language is a high-level language


while Java bytecode is a low-level language.
 The bytecode is similar to machine
instructions but its architecture is neutral and
can run on any platform that has a Java
Virtual Machine (JVM)
 Rather than a physical machine, the virtual

machine is a program that interprets Java


bytecode.
 This is one of Java’s primary advanatages:

Java bytecode can run on a variety of


hardware platforms and operating systems.
 Java’s bytecodes are portable- platform-
5
independent instructions
JAVA API PACKAGES
 Java contains many predefined classes that are
grouped into categories of related classes called
packages.
 The packages are referred to collectively as the Java

class library or the Java applications programming


interface (Java API) or the Java class library.
 import statements specify the classes required to

compile a Java program


 One of the great strengths of Java is the large

number of classes in the packages of the Java API


that programmers can reuse rather than
“reinventing the wheel.”
 Example

import javax.swing.JApplet; 6
to tell the compiler to load the JApplet class from the
javax.swing package
CONT’D
 Java programs consist of pieces called classes.
 Classes consist of pieces called methods that perform
tasks and return information when they complete their
tasks.
 You can program each piece you may need to form a
Java program.
 However, most Java programmers take advantage of
rich collections of existing classes in Java class libraries.
 The class libraries are also known as the Java APIs.
 Thus, there are really two pieces to learning the Java
“world.”
 The first is learning the Java language itself so that you can
program your own classes;
 the second is learning how to use the classes in the
extensive Java class libraries. 7
 Ex. Math.pow(x, y) calculates the value of x raised to
the yth power
PHASES OF A JAVA PROGRAM

8
CONT’D

9
CONT’D
 Editor – To type your program into , a editor
could be used for this
 Compiler – To convert your high language

program into native machine code - bytecodes


 Loader – To load the files from your secondary

storage device like Hard Disk , Flash Drive , CD


into RAM for execution. The loading is
automatically done when your code execute your
code.
 Bytecode Verifier- To ensure that the bytecodes

for downloaded classes are valid and that they do


not violate Java’s security restrictions.
 Interpreter – To interpret the program one 10

bytecode at a time,
CONT’D

11
SIMPLE JAVA PROGRAM
Step 1 ) Copy the following code into a notepad.

class A {
public static void main(String args[])
{
System.out.println(“First Java Program”);
}
}

Step 2 ) Save the file in the directory C:workspace ,


as A.java

Step 3 ) Open the command prompt Go to


Directory C:workspace
12
Compile the code using command, javac A.java
Step 4) Run the code using command, java A
CONT’D
 When you execute the Java Virtual Machine (JVM)
with the java command, the JVM attempts to
invoke the main method of the class you specify.
 The JVM loads the class specified by Class Name
and uses that class name to invoke method
main.
 You can specify an optional list of Strings
(separated by spaces) as command-line
arguments that the JVM will pass to your
application.
 Why must main be declared static?
 When you execute the Java Virtual Machine (JVM) with
the java command, the JVM attempts to invoke the
main method of the class you specify—when no
objects of the class have been created. 13
 Declaring main as static allows the JVM to invoke
main without creating an instance of the class.
CONT’D
Coding Guidelines:
 Your Java programs should always end with

the .java extension.


 Filenames should match the name of your public

class. So for example, if the name of your public


class is Hello, you should save it in a file called
Hello.java.
 You should write comments in your code
explaining what a certain class does, or what a
certain method do.

14
CONT’D…
 Writing my second example
 let’s look at a simple problem for computing the area
of a circle. How do we write a program for solving this
problem?
public class ComputeArea
{
public static void main(String[] args)
{
// The main method is the entry point where the program starts
when it is executed
double radius; // Declare radius
double area; // Declare area
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;
System.out.println("The area for the circle of radius " 15 +
radius + " is " + area);
}
CONT’D
 Class
 It is keyword which is used to declare a class
 Public:
 It is called access modifier or spacifier
 It is used to define accessibility of data members (variable and
member function(methods)).
 Static
 Used for memory management
 Can be used is variable function and block.
 Static members are belongs to class rather than object(can be
called directly by the class name).
 Static variable function and block will be in the following section.
 Void:
 there is no value to be returned by the function.
 Main():
 The execution of any program starts from the main function.
 String[] args:
 It is command line argument that you can write anything in place 16
of args.
 System.out: stands output object
JAVA PROGRAM PRIMITIVES/ BASICS
 Java Comments
 Java Statements and blocks
 Java Identifiers
 Java Keywords
 Variables
 System.out.println() vs. System.out.print()
 Reference Variables vs. Primitive Variables
Primitive variables
 are variables with primitive data types. They store data in
the actual memory location of where the variable is.
Reference variables
 are variables that stores the address in the memory
location.
 It points to another memory location of where the
actual data is
17
 When you declare a variable of a certain class, you
are actually declaring a reference variable to the
JAVA COMMENT
 It is additional expression about which you are doing.
 Two kinds of comment
 Single line comment (//)
 Multiline comment
/*
---
------
-----
*/
 Java statement and block
{
double radius;
double area;
radius = 20;
18
}
IDENTIFIERS
 the names of things that appear in the program..
 All identifiers must obey the following rules:
 An identifier is a sequence of characters that
consists of letters, digits, underscores (_), and
dollar signs ($).
 An identifier must start with a letter, an
underscore (_), or a dollar sign ($).
 It cannot start with a digit.
 An identifier cannot be a reserved word.
19
 An identifier cannot be true, false, or null.
 An identifier can be of any length.
JAVA KEYWORD
 The word which is pre-defined in the library
 Its functionality also pre-defined.

 Keywords can not be used as a variable,

function, and class name.


 Examples:
 int
 float
 char
 void
 main

20
VARIABLES
 variables are used to store values to be used later in a
program.
 They are called variables because their values can be
changed.
 In the program radius and area are variables of
double-precision.
 Variables are for representing data of a certain type.
 To use a variable, you declare it by telling the compiler
its name as well as what type of data it can store.
 The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on
its data type.
 The syntax for declaring a variable is 21
datatype variable Name;
SYSTEM.OUT.PRINTLN()
VS.
SYSTEM.OUT.PRINT()

 System.out.print()
 Print the output with the same line
System.out.print("hellow world ");
System.out.print(“this is my first java program");
 System.out.println()
 Print the output with different line.
System.out.println("hellow world ");
System.out.println(“this is my first java program");
22
JAVA SCANNER

 Scanner class in Java is found in the java.util


package.
 Java provides various ways to read input from the
keyboard, the java.util.Scanner class is one of
them.
 To get the instance of Java Scanner which reads
input from the user, we need to pass the input
stream (System.in) in the constructor of Scanner
class. 23

 For Example:
24
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);

in.close();
}
25
}
 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
 Classes
 Interfaces
 Arrays
26
CONT’D
 Operators
 Arithmetic operators

 Increment and Decrement operators

 Relational operators

 Logical operators

 Conditional Operator (?:)

 Operator Precedence

 Getting Input from the Keyboard

27
OPERATORS
 Java Arithmetic and Increment/Decrement
operators
 Java arithmetic operators are used to perform addition,
subtraction, multiplication, division Modulus, Increment,
Decrement.
 They act as basic mathematical operations.
{
int a=10;
int b=5;
System.out.println(++a+b);//16
}
Java Assignment Operators
 Assignment operators are used to assign values to variables.
 In the example below, we use the assignment operator (=) to
28
assign the value 10 to a variable called x:
{
int b=5;
OPERATORS…

 Java Comparison Operators


 Comparison operators are used to compare two
values:
 (<, >, ==, !=, <=, >= )
{

int x = 5;

int y = 3;

System.out.println(x == y);

// returns false because 5 is not equal to 3 29

}
OPERATORS…
 Java Logical Operators
 Logical operators are used to determine the logic
between variables or values:
 Logical and(&&), logical or(||) and logical not(!)
{
int x = 5;
System.out.println(x > 3 || x < 4);
/* returns true because one of the conditions
are true (5 is greater than 3, but 5 is not less
than 4)
*/
}

30
OPERATORS…
 Conditional Operator (?:)
 The Java Conditional Operator selects one of two
expressions for evaluation, which is based on the value of
the first operands.
 It is also called ternary operator because it
takes three arguments.
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
// Value of y is:90
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
// Value of y is:90
} 31
 Operator Precedence
 *, /, %, (+ or – from left to right).
OPERATORS…
 Getting Input from the Keyboard
 Java Scanner class allows the user to take input
from the console.
 It belongs to java.util package.
 It is used to read the input of primitive types like int,
double, long, short, float, and byte.
 It is the easiest way to read input in Java program.
 The java.util package should be import while using
Scanner class.
 Syntax
Scanner sc=new Scanner(System.in);
 Methods of Java Scanner Class
 Java Scanner class provides the following methods to 32
read different primitives types:
OPERATORS…
Method Description

int nextInt() It is used to scan the next


token of the input as an
integer.
float nextFloat() It is used to scan the next
token of the input as a float.

double nextDouble() It is used to scan the next


token of the input as a double.

byte nextByte() It is used to scan the next


token of the input as a byte.

String nextLine() Advances this scanner past the 33


current line.
OPERATORS…
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
34
System.out.println("Total= " +d);
}
}
CONT’D
 Control Structures
 Decision Control Structures

 Repetition Control Structures

 Branching Statements

 break statement

 continue statement

 return statement

35
.

CONTROL STRUCTURES/IF/
 Use the if statement to specify a bloc of Java code to be
executed if a condition is true
 Syntax:
if (condition)
{ // block of code to be executed if the condition is true
}
 Example:
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
 Self test
 Write a java program that will display “young” if your age is less
36

than 20.
}

CONTROL STRUCTURES/IF ELSE/


 Use the else statement to specify a block of code to be
executed if the condition is false.
 Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
Else
{
// block of code to be executed if the condition is false
 Example
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
37
} else {
System.out.println("Good evening.");
CONTROL STRUCTURES/ELSE IF/
 Use the else if statement to specify a new condition if the
first condition is false and so on.
 Syntax:
if (condition1)
{ // block of code to be executed if condition1 is true
}
else if (condition2)
{
executed if the condition1 is false and condition2 is true
}
else {
// executed if the condition1 is false and condition2 is false
}
Example:
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
} else if (time < 20)
{
System.out.println("Good day."); 38
}
else {
System.out.println("Good evening.");
CONTROL STRUCTURES/SWITCH/
 Use the switch statement to select one of many
code blocks to be executed.
 The switch expression is evaluated once.
 The value of the expression is compared with the values of
each case.
 If there is a match, the associated block of code is executed.
 Syntax:

switch(expression)
{
case x: // code block
break;
case y: // code block
break;
39
default: // code block }
CONT’D
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
40
default:
System.out.println("Sunday");
REPETITION CONTROL STRUCTURES/WHILE LOOP/
 Loops can execute a block of code as long as a specified condition
is reached.
 Loops are handy because they save time, reduce errors, and they
make code more readable.
 The while loop loops through a block of code as long as a
specified condition is true:

Syntax
while (condition)
{ // code block to be executed

}
 Example:

int i = 0;
while (i < 5)
{
System.out.println(i); 41

i++;
}
REPETITION CONTROL
STRUCTURES/FOR LOOP/
 When you know exactly how many times you want to
loop through a block of code, use the for loop instead of
a while loop
 Syntax
for (statement 1; statement 2; statement3)
{
// code block to be executed
}
 Statement 1 is executed (one time) before the execution of
the code block.
 Statement 2 defines the condition for executing the code
block.
 Statement 3 is executed (every time) after the code block
has been executed.
 Example: 42
for (int i = 0; i < 5; i++)
{ System.out.println(i);
}
JAVA APPLICATION
 Is a computer program that executes when
you use the java command to launch the Java
Virtual Machine (JVM)
 The application program interface (API)
contains predefined classes and interfaces
for developing Java programs.
 Java is a full-fledged and powerful language

that can be used in many ways.


 Java comes in three editions: Java Standard

Edition (Java SE), Java Enterprise Edition


(Java EE), and Java Micro Edition (Java ME).
43
CONT’D
 Java SE can be used to develop client-side
standalone applications or applets.
 Java EE can be used to develop server-side
applications, such as Java servlets and JavaServer
Pages.
 Java ME can be used to develop applications for
mobile devices, such as cell phones.
 There are many versions of Java SE -JDK
 JDK consists of a set of separate programs, each
invoked from a command line, for developing and
testing Java programs.
 Besides JDK, you can use a Java development tool
(e.g., NetBeans, Eclipse, and TextPad)—software
44
that provides an integrated development
environment (IDE) for rapidly developing Java
EXERCISES
 Write a Java application that calculates and prints the

sum of the integers from 10 to 50


 Write a program that inputs five numbers and
determines and prints the number of negative numbers
input, the number of positive numbers input and the
number of zeros input.
 Write a Java application that uses looping to print the
following table of values:

 Write a Java application that can compute the letter


grade of a student after accepting the student’s mid
and final mark. The program should only accept mid
result [0-40] and final [0- 60]. If the data entered
violates this rule, the program should display that the 45
user should enter the mark in the specified range. The
program is also expected to run until the user refuses
CONT’D
 Write an application that prints the following
diamond shape.

46

You might also like