You are on page 1of 41

JAVA

What Is Java?
• Java is an object-oriented programming language
developed by Sun Microsystems. the Java language was
designed to be small, simple, and portable across
platforms and operating systems.
Applets and Applications
• Java applications fall into two main groups: applets and
applications.
Applets, are Java programs that are downloaded and
executed by a Web browser on the reader‟s machine.
Applets depend on a Java-capable
browser in order to run (although they can also be viewed
using a tool called the applet viewer.
Java applications are more general programs written in
the Java language. Java applications don‟t
require a browser to run, and in fact, Java can be used to
create most other kinds of applications
that you would normally use a more conventional
programming language to create.
Creating a Java Application
• your Java source files are created in a plain text editor, or
in an editor that can save files in plain ASCII without any
formatting characters.

• class HelloWorld {
public static void main (String args[]) {
System.out.println(“Hello World!”);
}
}

• Once you finish typing the program, save the file.


Conventionally, Java source files are named
the same name as the class they define, with an
extension of .java. This file should therefore be
called HelloWorld.java.
• Now, let‟s compile the source file using the Java compiler.
In Sun‟s JDK, the Java compiler is
called javac.
To compile your Java program, Make sure the javac
program is in your execution path and type
javac followed by the name of your source file:
javac HelloWorld.java
• When the program compiles without errors, you end up
with a file called HelloWorld.class, in
the same directory as your source file. This is your Java
bytecode file. You can then run that
bytecode file using the Java interpreter. In the JDK, the
Java interpreter is called simply java.
Make sure the java program is in your path and type java
followed by the name of the file without the .class
extension:
java HelloWorld
• If your program was typed and compiled correctly, you
should get the string “Hello World!”
printed to your screen as a response.
Creating a Java Applet
• Creating applets is different from creating a simple
application, because Java applets run and are
displayed inside a Web page with other page elements
and as such have special rules for how they
behave. Because of these special rules for applets in
many cases (particularly the simple ones),
creating an applet may be more complex than creating an
application.
For example, to do a simple Hello World applet, instead of
merely being able to print a message,
you have to create an applet to make space for your
message and then use graphics operations
to paint the message to the screen.
Creating the simple Hello World applet
• First, you set up an environment so that your Java-
capable browser can find your HTML files
and your applets. Much of the time, you‟ll keep your
HTML files and your applet code in the same directory.
Although this isn‟t required, it makes it easier to keep
track of each element. In this example, you use a
directory called HTML that contains all the files you‟ll
need.
The Hello World applet.

import java.awt.Graphics;

class HelloWorldApplet extends java.applet.Applet {

public void paint(Graphics g) {


g.drawString(“Hello world!”, 5, 25);
}
}
• The import line at the top of the file is somewhat
analogous to an #include statement in C; it enables this
applet to interact with the JDK classes for creating applets
and for drawing graphics on the screen.

■ The paint() method displays the content of the applet


onto the screen. Here, the
string Hello World gets drawn. Applets use several
standard methods to take the place
of main(), which include init() to initialize the applet, start()
to start it running,
and paint() to display it to the screen.
• Now, compile the applet just as you did the application,
using javac, the Java compiler.
javac HelloWorldApplet.java Again, just as for
applications, you should now have a file called
HelloWorldApplet.class in your HTML directory.
To include an applet in a Web page, you refer to that
applet in the HTML code for that Web
page.
<HTML>
<HEAD>
<TITLE>Hello to Everyone!</TITLE>
</HEAD><BODY>
<P>My Java applet says:
<APPLET CODE=”HelloWorldApplet.class” WIDTH=150
HEIGHT=25></APPLET>
</BODY>
</HTML>
Java Basics
• Variables and Data Types
Variables are locations in memory in which values can be
stored. They have a name, a type, and a value.
• Declaring Variables
• int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;
Variable Names
• Variable names in Java can start with a letter, an
underscore (_), or a dollar sign ($). They cannot start with
a number. After the first character, your variable names
can include any letter or number. Symbols, such as %, *,
@, and so on, are often reserved for operators in Java, so
be careful when using symbols in variable names.
Variable Types
Integer types
byte 8 bits –128 to 127
short 16 bits –-32,768 to 32,767
int 32 bits –2,147,483,648 to 2,147,483,647
long 64 bits –9223372036854775808 to 9223372036854775807

Floating numbers
float (32 bits, single-precision)
double(64 bits, double-precision).

The char type is used for individual characters., the


char type has 16 bits of precision, unsigned.
the boolean type can have one of two values, true or false.
Assigning Values to Variables
• Once a variable has been declared, you can assign a
value to that variable by using the assignment

size = 14;
tooMuchCaffiene = true;
• Each of these variables can then hold only instances of
the given class. As you create new classes,you can
declare variables to hold instances of those classes (and
their subclasses) as well.
• Java does not have a typedef statement (as in C and
C++). To
declare new types in Java, you declare a new class; then
variables can be declared to
be of that class‟s type.
Comments
• /* Multi Lines Comment*/
• // single line comment

Character escape codes


\n Newline
\t Tab
\b Backspace
\f This is called form feed, is used to indicate to a printer
that it should start a new page.
\\ Backslash
\‟ Single quote
\” Double quote
String function
• Example
• String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " +
txt.length());
• -------------------------

• Example
• String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO
WORLD"
• System.out.println(txt.toLowerCase()); // Outputs "hello
world"
String function
• Finding a Character in a String
• The indexOf() method returns the index (the position) of
the first occurrence of a specified text in a string (including
whitespace):
• Example
• String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
Operators
• Arithmetic operators
+ Addition 3 + 4
– Subtraction 5 – 7
* Multiplication 5 * 5
/ Division 14 ÷ 7
% Modulus 20 % 7

Example
class ArithmeticTest {
public static void main (String[] args) {
short x = 6;
int y = 4;
float a = 12.5f;
float b = 7f;

System.out.println(“x is “ + x + “, y is “ + y);
System.out.println(“x + y = “ + (x + y));
System.out.println(“x % y = “ + (x % y));
}
}
Assignment operators
x += y  x = x + y
x –= y  x = x – y
x *= y  x = x * y
x /= y  x = x / y

++x; // x += 1
−−x; // x -= 1

++x; // pre-increment
−−x; // pre-decrement
x++; // post-increment
x−−; // post-decrement
Comparisons operators
Comparison operators are used to compare two values:

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Logical Operators

Returns true if both


x < 5 && x < 10
&& and statements are true

Returns true if one of


|| or x < 5 || x < 4
the statements is true

Reverse the result,


! not returns false if the !(x < 5 && x < 10)
result is true
Bitwise operators
• Bitwise operators is a comparison operator between
binary system.

• int x = 5 & 4; // 101 & 100 = 100 (4) // and


x = 5 | 4; // 101 | 100 = 101 (5) // or
x = 5 ^ 4; // 101 ^ 100 = 001 (1) // xor
x = ~4; // ~00000100 = 11111011 (-5) // invert
if Conditionals
• if ()
{
true condition code
}
else
{
false condition code
}
if Conditionals
• Example
• int time = 22;
• if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
} // Outputs "Good evening."
• -------------------------------------------------
if Conditionals
• Short Hand If...Else

• Syntaxe
• variable = (condition) ? expressionTrue : expressionFalse;

Example
• int time = 20;
• String result = (time < 18) ? "Good day." : "Good evening.";
• System.out.println(result);
Switch Conditionals
• Syntax
• switch(expression) {
• case x:
• // code block break;
• case y:
• // code block break;
• default:
• // code block
}
Switch Conditionals
• int day = 4;
• switch (day) {
• case 6:
• System.out.println("Today is Saturday"); break;
• case 7:
• System.out.println("Today is Sunday");
• break;
• default:
• System.out.println("Looking forward to the Weekend");
} // Outputs "Looking forward to the Weekend"
Switch Conditionals
• String oper = “*”;
• switch (oper) {
case „+‟: addargs(arg1,arg2); break;
case „*‟: multargs (arg1,arg2); break;
case „-‟: subargs (arg1,arg2); break;
case „/‟: divargs(arg1,arg2); break;

default: System.out.println(“You must enter an operator.”);


}
While Loop
• Syntax
• while (condition) {
bodyOfLoop;
}

• Example
• int i = 0;
• while (i < 5) {
• System.out.println(i);
• i++;
}
do-while Loop
• do
{
Code
}while (Condition);

Example
• int x = 1;
do {
System.out.println(“Looping, round “ + x);
x++;
} while (x <= 10);
for Loops
• Example
for (i = 0; i < 10; i++);
System.out.println(“Number is”+i);

• Example
for (int i=1 ; i <= 10; i++ )
{
for (int j=1 ; j <= 10; j++ ) // loop prints multiplication
table
System.out.print (" i*j =" + i*j);
System.out.println (); //print empty line
}
Arrays, Conditionals, and Loops
• Arrays

Declaring Array Variables
int array1[ ] = new int[9];
int [ ] array1 = new int[9];

• Example
• int b[ ][ ];
b = new int[3][4];
int b[ ][ ] = { { 1, 2 }, { 3, 4 } };

• Example
String[] chiles = { “jalapeno”, “anaheim”,“serrano,”,
“habanero,” “thai” };
Accessing Array Elements
• Example
• int ages[ ]= {20, 18, 34, 42, 28};

• Example
• String arr[] = new String[10];
int len = arr.length // returns 10

• Changing Array Elements


Example
• myarray[1] = 15;
sentence[0] = “The”;
sentence[10] = sentence[0];
Multidimensional Arrays
• Example
• int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;
Loop Through an Array with For-Each
• Example
• String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• for (String i : cars) {
• System.out.println(i);
•}
Math Function

Math.abs(6.2)  6.2
• Math.abs(-4.2)  4.2

Math.ceil(5.1)  6
Math.ceil(-5.1)  -5

Math.floor(5.1)  5
Math.floor(-5.1)  -6
Math.max(7,6)  7
• Math.min(-7,-8)  -8
• Math.pow(6,2)  36
Math.sqrt(9)  3
Math.random()  0.24421
Example
• Example (receive two numbers and print sum)
• import java.util.Scanner;
public class Addition
{
public static void main( string args[] )
{
Scanner input = new Scanner( System.in );
int number1;
int number2;
int sum;
System.out.print( "Enter first integer: " );
number1 = input.nextInt();
System.out.print( "Enter second integer: ");
number2 = input.nextInt();
sum = number1 + number2;
System.out.printf( "Sum is %d\n", sum );
}
}

You might also like