Friday, April 23, 2010

Java Robot (‘’,)







සුභ අලුත් අවුරුද්දක් හැමෝටම ! ! !
ඉතින් ඔන්න මම මේ අලුත් අවුරුද්දෙ පොඩ්ඩක් Java Programming  වලට ආස හිතෙන විදියෙ ලිපියක් ලියන්න ඕනෙ කියල හිතුවා.
ඔක්කෝටම කලින් ඔයාල හැමෝගෙන්ම පුන්චිම පුන්චි ඉල්ලීමක් කරන්න ඕනෙ, ඒ තමයි මේකට use කරල තියෙන code කාටවත් කරදරයක් කරන්න නම් පාවිච්චි කරන්න නම් එපා කියන එක.
ඔයාලට මතක ඇති අපි මුල්ම පියවර විදියට java වලින් software එකක අතුරු මුහුනතක් එහෙමත් නැත්තන් interface එකක් හදා ගත්තා.(My First Java Program)ඉතින් අපි මේ පාරත් ඒ විදියටම අලුත්ම program එකක් හදාගන්න විදිය පොඩ්ඩක් ඉගෙන ගමු. මේ සැරේ අපි කරන්න යන්නෙ ටිකක් විතර FUN වැඩක් කියලයි මට හිතෙන්නෙ.(ඔයාලට එහෙම හිතෙන එකක් නැද්ද දන්නෙ නෑ හැබැයි.) ඉතින් කෝකටත් කියල අගේ කරන එක පැත්තකින් තියල වැඩේ කියල ඉන්නම්කෝ.ඔන්න ඔයාල හොදයි කියල හිතෙනව නම් විතරක් කරල බලන්නකෝ....
මේ වැඩේ කරන්න මම use කරල තියෙන ප්‍රධාන class එක නම් හැබැයි අපේ syllabus එකට නැහැ. ඒත් මම හිතුවා මේකෙ තියෙන for loop ටික තේරුම් ගන්න එක ඔයාලට හතරවෙනි පාඩමේ Iterative Statement කරද්දි පුන්චි හරි උදවුවක් වෙයි කියල.
ඉතින් program එක සරලයි.
1). මුලින්ම අලුත් Notepad එකක් open කරගෙන පහල තියෙන code එක type කරගන්න.


import java.awt.Robot;
import java.awt.event.*;
//@author bit-revision.blogspot.com
public class MyRobot {
public static void main(String[] args) {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_WINDOWS); r.keyRelease(KeyEvent.VK_WINDOWS);  Thread.sleep(200);
r.keyPress(KeyEvent.VK_P); r.keyRelease(KeyEvent.VK_P); Thread.sleep(200);
r.keyPress(KeyEvent.VK_RIGHT); r.keyRelease(KeyEvent.VK_RIGHT); Thread.sleep(200);
r.keyPress(KeyEvent.VK_A); r.keyRelease(KeyEvent.VK_A); Thread.sleep(200);
r.keyPress(KeyEvent.VK_RIGHT); r.keyRelease(KeyEvent.VK_RIGHT); Thread.sleep(200);
r.keyPress(KeyEvent.VK_P); r.keyRelease(KeyEvent.VK_P); Thread.sleep(200);
r.keyPress(KeyEvent.VK_ENTER); r.keyRelease(KeyEvent.VK_ENTER); Thread.sleep(200);
r.keyPress(KeyEvent.VK_ALT); r.keyPress(KeyEvent.VK_TAB); Thread.sleep(200);
r.keyRelease(KeyEvent.VK_ALT); r.keyRelease(KeyEvent.VK_TAB); Thread.sleep(200);
r.mouseMove(100, 100); Thread.sleep(500);
r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseRelease(MouseEvent.BUTTON1_MASK);
for(int i=0;i<100;i++){
r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseMove(100+i, 100); Thread.sleep(20);
}
r.mouseMove(150, 100);
for(int i=0;i<100;i++){
r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseMove(150, 100+i); Thread.sleep(20);
}
for(int i=0;i<25;i++){
r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseMove(150-i, 200+i); Thread.sleep(20);
}
for(int i=0;i<25;i++){
r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseMove(125-i, 225-i); Thread.sleep(20);
}
r.mouseRelease(MouseEvent.BUTTON1_MASK);
} catch (Exception ex) { }
}
}







2). ඊට පස්සෙ ඒ Ctrl+S press කරල C: drive එකේ save 
කරගන්න.(MyRobot.java)


3). ඉන් පසුව start > run වෙත ගොස් CMD ලෙස type කර enter කිරීමෙන් Command Prompt එකක් ලබා ගන්න.


4). ඉන් පසු Path එක Set කර ගෙන ඇත්නම් Compile කිරීම සදහා C: වෙත ගොස් javac MyRobot.java ලෙස type කර enter කරන්න.
Path එක Set කරගෙන නැත්නම් එය කර ගැනීමට Set Java Path යන්න උදව් කරගන්න.



5). ඉන් පසු Error කිසිවක් මතු නොවූයේ නම් Run කරවීම සදහා java MyRobot ලෙස type කර enter කරන්න.


6). ඔබට දැන් ඔබගේ අනුදැනුමකින් තොරව Paint හි රූප අදිනු දැකගත හැකි වනු ඇත.
  

Run කර බැලීමට අවශ්‍ය නම් මෙතනින් Download කරගෙන Double Click කරන්න.


Friday, April 2, 2010

My First Java Program





bit-revision.blogspot.com
    fudkjo fï JAVA lshkafka@
Thdg uu lsjqfjd;a JAVA lshkafka mß.Kl jevigyka (Computer Programs) iïmdokhg Ndú;d lrk mß.Kl NdIdjla (Computer Language) lsh,d Thdg f;areï .kak mq¿jkao@ iuyr úg flfkl=g tal fkdf;afrkak;a mq¨jka' ir,j lshkjkï wms wfma woyia yqjudre lr .ekSug;a" hï ld¾hhla lrjd .ekSsug ksfhda. ksl=;a lsßug;a isxy," bx.%sis fyda fjkhï NdIdjla Ndú;d lrkjd fkao@ tfiau mß.Klh yd woyia yqjudre lr .ekSug;a" mß.Klh ,jd hï ld¾hhla bgq lr .ekSug;a C, JAVA fyda fjkhï mß.Kl NdIdjla Ndú; l, yelsh' tfia kï flfkl=f.ka fukau mß.Klhlskao hï ld¾hhla lrjd .ekSsug kï mß.Klhg f;areï .; yels NdIdjla m%.=K lsÍu l, hq;=u jk nj Tng f;areï .; yelshs fkao@ u;la lr n,kak Thd fkdokak NdIdjlska lshmq fohla f;areï .kak nerej m%;spdr olajkak nerej .sh wjia:djla .ek ' ' ' ±ka Thdg mß.Kl NdIdjla .ek f;areï .kak mq¨jka we;s' ta;a fï mß.Kl jevigyka tfyu;a ke;akï uDÿldx. lshkafka fudkjdo@ Thd lsisu mß.Kl NdIdjla ±kf.k fkdysáhd lshd is;uq' ta;a Thdg mß.Klh Ndú; lrf.k
bka ,smshla msgm;a lr.ekSu jeks hula lr.ekSug l%uhla ;sfhkjd fkao@ ta ;uhs mß.Kl NdIdjla W.;a mß.Kl bxðfkarejl= úiska bx.%Sis NdIdjg mßj¾;kh lrk ,o w;rueÈ w;=re uqyqK;la jk uDÿldx.hla Ndú;d lsÍu' th yßhg NdId mßj¾;lfhl=f.a ld¾hhg iudkhs' b;ska Tng jegfykjdo Tn fuf;la mß.Klfha w;rueÈhka
iuÕ jev lghq;= isÿ lr we;s nj'

    tfia kï wms wfma uDÿldx.h idod .ekSu wdrïN lruq' m<uqj Start > All Programs > Accessories > Notepad fj; f.dia kj Notepad window tlla open lr.kak' tys my; ±lafjk fla; fyj;a code fma,s space, symbols and case (Capital letter & Simple letter) .ek wjOdkh fhduq lrñka type lr .ekSu lrkak'(code
i) ^1 jk rEmh&


  import javax.swing.JFrame ;
    class Y extends JFrame {
        public static void main (String args[]) {
            JFrame myFrame = new JFrame ("By SHYN");
            myFrame.setSize (300, 400) ;
            myFrame.setVisible (true) ;
        }
    }

bkamiq Notepad ys jï fl,jf¾ by,ska we;s File > Save As fj; hkak' újD; jk kj Save As window ys Save in: f,i i|yka ;ek bÈßfha we;s Drop Down fukqfjka (Combo Box tflka& Local Disk (C:) hkak Select lrkak.(fuys§ Local Disk (C:) hkak Tn rename lr we;akï ta ms<sn| fkdi,ld (C:) f,i i|yka jk Hard Disk Partition tl f;dard .kak& miqj my<ska we;s File name: bÈßmsg we;s Drop Down fukqfõ Y.java f,i type lrkak'miqj Save button tl click lr save lr .kak' ^2 jk rEmh&


    Tn ±ka m<uq mshjr jk Java Program tlg wod, fla; igyka we;=,;a file tl Tnf.a oDv ;eáfha (Hard Disk) save lrf.k wjika' ±ka tu jevigyk run lsÍu i|yd l, yels l%u lSmh w;=ßka Tng myiq hehs yefÕk .bat File tlla (BATCH File) idod .ekSssfuka run lrjk whqre n,uq'

    fï i|yd kej; fmr mßÈu Start > All Programs > Accessories > Notepad yryd kj Notepad window tlla open lr.kak' tys run lrùug wjYH jk my; commands fma,s type lr .kak'(code
ii) ^3 jk rEmh&

    C :
    CD \
    Path = C:\Program Files\java\jdk1.6.0_10\bin
    javac Y.java
    java Y
    pause

bka miq tyso File > Save As fj; f.dia fmr isÿl, whqßkau Save in: bÈßfha we;s Drop Down tflka Local Disk (C:) f;darkak' bkamiq File name: hgf;a we;s Drop Down tfla Y.bat f,i type lr Save button tl click lrkak' ^4 jk rEmh&


    ±ka Tn Tnf.a My Computer > Local Disk (C:) fj; f.dia tys we;s files w;r Tn save lr.;a Y.java iy Y.bat f,i i|yka file 2 la we;a ±hs n,kak' tfia kï Tn ±ka Tnf.a m,uq uDÿldx.h ksujd wjika' kuq;a Tn Tfí uDÿldx.h run lrùug yels jk mßÈ Tfí mß.Klh ;=< JAVA ia:dmkh (Install) lrf.k fkdue;s ksid ;ju Tnf.a uDÿldx.h run lsÍu l, fkdyel' Tn uDÿldx. bxðfkarejrefjl= ùfï§ l=uk mß.Kl NdIdjla mdúÉÑ l,o ta i|yd tu NdIdjg wod,j mß.Klh ilid .ekSu wksjd¾h jk w;r JAVA j,§ fï ;;a;ajh tfiau jqjo th lsÍu w;sYhskau myiq lghq;a;ls'

    fï i|yd Tng we;af;a JAVA Development Kit fyj;a JDK kñka y÷kajk uDÿldx.h Tfí mß.Klfha ia:dmkh (Install) lr.ekSu muKls' ta i|yd Tn JDK Setup file tlla fidhd .; hq;= fõ' wm fuysÈ th imhd .; yels wdldr bÈßm;a lrk w;r bka tla l%uhlska Setup file tl fidhd .ekSu Tnf.a JAVA f,dalhg msúiSug l, yels wju yd tlu wdfhdackh jk nj fu;kÈ i|yka l, hq;=uh'


JDK tl imhd .; yels wdldr
by; hï wdlrhlska JDK Setup file tl Tn fidhd .;af;a kï" th Double click lrkak' bkamiq tk window ys Accept button tl click lrkak' fojk window ys Next button tl click l, miq setup ùu isÿjk w;r wjika window ys Finish button tl click lrkak' ^5 jk rEmh& túg ReadMe.html file tl újD; jk w;r th lshùu ;=<ska JDK ms<sn|j jeäÿr f;dr;=re ±k .; yels fõ'


    fuys§ Tn install lr.kakd JDK version tl ms<sn|j (code
ii) ys§ ie,ls,su;a úh hq;= jk w;r JDK version tl ±k .ekSug C:\Program Files\Java hk folder tl fj; f.dia tys iE§ we;s foders w;r jdk1.6... f,i mgka .kakd folder tflys ku n,d .; hq;= fõ' Wod( tu folder tflyss ku jdk1.6.0_14 kï Tn by; i|yka (code
ii) ys 3 jk fma,sh C:\Program Files\Java\1.6.0_14\bin f,i fjkia lr File > Save fj; f.dia l, fjkig wod,j save lr .ekSu l< hq;= fõ' tfia kï Tn ±ka Tnf.a uDÿldx.h run lrùug iQodkï' ±ka Tn My Computer > Local Disk (C:) fj; f.dia tys we;s Y.bat hk file tl u; double click lrkak' Tn Tnf.a codes ksjerÈj type lr save lr .;af;a kï Tng DOS ;srhla Èia ù ta iuÕu Tfí m,uq uDÿldx.fha uqyqK; Tngu Èia fõú' ^6 jk rEmh& n,kak tys title tlys "By SHYN" f,i i|yka jkjd fkao@ ±ka Tn Y.java file tl Notepad yryd open lrf.k "By SHYN" f,i i|yka ia:dkhg Tnf.a kula fhdod save lr kej; run lr n,kak' Tfíu ku software tll olskak yelshdjla Tng ±ka ;sfnkjd' tfia kï Tn JAVA f,dalhg uq,a mshjr ;nd wjika'




iïmdokh : kÿka ,shkf.a

Second Lesson in JAVA



Theory Session

How Java Works On Computer


When programming you will be writing source code using the syntax for the java programming language. This source code is translated into byte code by the compiler and is then stored in a .class file. The byte code is the same for each computer system.

For this byte code to execute, another program, called the Java virtual machine (JVM), translates the Java byte code into instructions understood by that computer. This extra step is necessary for one of the main advantages of Java: the same program can run in any computing environment! A computer might be running Windows, MacOS, Solaris, Unix, or Linux-each computer system has its own Java virtual machine program. Having a particular Java virtual machine for each computer system also allows the same Java .class file to be transported around the internet. The following figure shows the levels of translation needed in order to get executable programs to run on most computers.







Elements of Java Programming



The essential building block of Java programs is the class. In essence, a Java class is a sequence of characters (text) stored as a file, whose name always ends with .java. Each class is comprised of several elements, such a class heading (public

class class-name) and methods—a collection of statements grouped together to provide a service. Below is the general form for a Java class that has one method: main. Any class with a main method, including those with only a main method, can be run as a program.


A simple Java program (only one class)




import package-name.class-name;



public class class-name {

public static void main(String[ ] args) {

variable declarations and initializations

messages and operations such as assignments

}

}
  



 



General forms describe the syntax necessary to write code that compiles. The general forms in this textbook use the following conventions:


  • Boldface elements must be written exactly as shown. This includes words such as public static void main and symbols such as [](, and ).
  • Italicized items are defined somewhere else or must be supplied by the programmer.
An Example of a Syntactically Correct Java Class with One Method Named main



// Read a number and display that input value squared



import java.util.Scanner;

public class ReadItAndSquareIt {         // Class heading
public static void main(String[] args) {           // Method heading
// Declare three variables
int number; // Variable declaration
int result = 0; // Variable initialization
Scanner keyboard = new Scanner(System.in);         // Class instantiation
// Prompt user for a number and get it from the keyboard
System.out.print("Enter an integer: ");            // Message
number = keyboard.nextInt();                       // Message and assignment
result = number * number;                          // Assignment
System.out.println(number + " squared = " + result);
}

}











Out Put 
Enter an integer: -12
-12 squared = 144



The first line in the program shown above is a comment indicating what the program will do.

Comments in Java are always preceded by the // symbol, and are "ignored" by the program. The next line contains the word 
import, which allows a program to use classes stored in other files. This program above has access to a class named Scanner for reading user input. If you omit the import statement, you will get this error:



Scanner keyboard = new Scanner(System.in);

Scanner cannot be resolved to a type




Java classes are organized into over seventy packages. Each package contains a set of related classes. For example, 
java.net has classes related to networking, and java.io has a

collection of classes for performing input and output. To use these classes, you could either use

the import statement or simply precede the class name with the correct package name, like this:



java.util.Scanner keyboard = new java.util.Scanner(System.in);



The next line in the sample program is a class heading. A class is a collection of methods and

variables (both discussed later) enclosed within a set of matching curly braces. You may use any valid class name after 
public class; however, the class name must match the file name.

Therefore, the preceding program must be stored in a file named 
ReadItAndSquareIt.java.

The file-naming convention

class-name.java

The next line in the program is a method heading that, for now, is best retyped exactly as shown:


public static void main(String[] args) // Method heading


The opening curly brace begins the body of the 
main method, which is a collection of executable statements and variables. This main method body above contains a variable declaration, variable initializations, and four messages, all of which are described later in this chapter. When run as a program, the first statement in main will be the first statement executed. The boy of the method ends with a closing curly brace. This Java source code represents input to the Java compiler. A compiler is a program that translates source code into a language that is closer to what the computer hardware understands. Along the way, the compiler generates error messages if it detects a violation of any Java syntax rules in your source code. Unless you are perfect, you will see the compiler generate errors as the program scans your source code.



Tokens — The Smallest Pieces of a Program

As the Java compiler reads the source code, it identifies individual tokens, which are the smallest recognizable components of a program. Tokens fall into four categories:


Token
Examples
Special symbols; () , . { }
Identifiersmain args credits courseGrade String List
Reserved identifierspublic static void class double int
Literals (constant values)"Hello World!" 0 -2.1 'C' true


Tokens make up more complex pieces of a program. Knowing the types of tokens in Java should help you to:

  • More easily write syntactically correct code.
  • Better understand how to fix syntax errors detected by the compiler.
  • Understand general forms.
  • Compete programs more quickly and easily.
Special Symbols

A special symbol is a sequence of one or two characters, with one or possibly many specific

meanings. Some special symbols separate other tokens, for example: 
{;, and ,. Other special

symbols represent operators in expressions, such as: 
+-, and /. Here is a partial list of singlecharacter

and double-character special symbols frequently seen in Java programs:

() . + - / * =< >= // { } == ;

Identifiers

Java identifiers are words that represent a variety of things. String, for example is the name of a class for storing a string of characters. Here are some other identifiers that Java has already given meaning to:

sqrt String get println readLine System equals Double



Programmers must often create their own identifiers. For example, 
test1finalExammain,

and 
courseGrade are identifiers defined by programmers. All identifiers must follow these

rules:

  • Identifiers begin with upper- or lowercase letters through (or through Z), the dollar sign $, or the underscore character _.
  • The first character may be followed by a number of upper- and lowercase letters, digits (through 9), dollar signs, and underscore characters.
  • Identifiers are case sensitive; Identident, and iDENT are three different identifiers.
Valid Identifiers

main Vector incomeTax MAX_SIZE $Money$

Maine URL employeeName all_4_one _balance

miSpel String A1 world_in_motion balance




Invalid Identifiers

1A                 // Begins with a digit

miles/Hour         // The / is not allowed

first Name         // The blank space not allowed

pre-shrunk         // The operator - means subtraction

double             // This is reserved




Java is case sensitive. For example, to run a class as a program, you must have the identifier

mainMAIN or Main won't do. The convention employed by Java programmers is to use the

"camelBack" style for variables. The first letter is always lowercase, and each subsequent new

word begins with an uppercase letter. For example, you will see 
letterGrade rather than

lettergradeLetterGrade, or letter_grade. Class names use the same convention, except

the first letter is also in uppercase. You will see 
String rather than string.

Reserved Identifiers

Reserved identifiers in Java are identifiers that have been set aside for a specific purpose. Their

meanings are fixed by the standard language definition, such as 
double and int. They follow the

same rules as regular identifiers, but they cannot be used for any other purpose. Here is a partial list

of Java reserved identifiers, which are also known as keywords.

Java Keywords

boolean default for new

break do if private

case double import public

catch else instanceOf return

char extends int void

class float long while






The case sensitivity of Java applies to keywords. For example, there is a difference between

double (a keyword) and Double (an identifier, not a keyword). All Java keywords are written in

lowercase letters.

Literals

A literal value such as 123 or -94.02 is one that cannot be changed. Java recognizes these

numeric literals and several others, including 
String literals that have zero or more characters

enclosed within a pair of double quotation marks.



"Double quotes are used to delimit String literals."

"Hello, World!"




Integer literals are written as numbers without decimal points. Floating-point literals are written

as numbers with decimal points (or in exponential notation: 5e3 = 5 * 10= 5000.0 and 1.23e-4

= 1.23 x 10-4 = 0.0001234). Here are a few examples of integer, floating-point, string, and char5

acter literals in Java, along with both Boolean literals (
true and false) and the null literal value.

The Six Types of Java Literals

IntegerFloating PointStringCharacterBooleanNull
-2147483648-1.0"A"'a'truenull
-10.0"Hello World"'0'false
039.95"\n new line"'?'
11.234e02"1.23"       ' '
2147483647-1e6"The answer is: "'7'


Note: Other literals are possible such as 12345678901L for integers > 2,147,483,647.

Comments

Comments are portions of text that annotate a program, and fulfill any or all of the following

expectations:


  • Provide internal documentation to help one programmer read and understand another's program.
  • Explain the purpose of a method.
  • Describe what a method expects of the input arguments (n must be > 0, for example).



  • Describe a wide variety of program elements.



Comments may be added anywhere within a program. They may begin with the two-character

special symbol 
/* when closed with the corresponding symbol */.



/*

A comment may
extend over
many lines
*/




An alternate form for comments is to use 
// before a line of text. Such a comment may appear

at the beginning of a line, in which case the entire line is "ignored" by the program, or at the

end of a line, in which case all code prior to the special symbol will be executed.



// This complete Java program runs, but does nothing

public class DoNothing {
public static void main(String[] args) { // A method heading
// This program does nothing
}
}




Comments can help clarify and document the purpose of code. Using intention-revealing

identifiers and writing code that is easy to understand, however, can also do this.

Java has a third style of comments, known as javadoc comments. These begin with 
/** (note

the second asterisk) and end with 
*/ , and contain documentation and special tags that show up in Web pages (when you run the javadoc program).



/** Debit this account by withdrawalAmount if it is no greater than this

* account's current balance. withdrawalAmount must be greater than 0.

* @param withdrawalAmount The requested amount of money to withdraw.

* @return true if 0 < withdrawalAmount <= the balance.

*/

public boolean withdraw(double withdrawalAmount)




Primitive Types

Java has two types of variables: primitive types and reference types. Reference variables store

information necessary to locate complex values such as strings and arrays. On the other hand,

Primitive variables store a single value in a fixed amount of computer memory. The eight

"primitive" (simple) types are closely related to computer hardware. For example, an 
int value

is stored in 32 bits (4 bytes) of memory. Those 32 bits represent a simple positive or negative

integer value. Here is summary of all data types in Java along with the range of value for the

primitive types:


Java's Data Types


Primitive Types                                                                            Reference Types

integers:                                                                                     arrays (Later)

NameWidthRange
byte(8 bits)-128 .. 127
short(16 bits)-32,768 .. 32,767
int(32 bits)-2,147,483,648 .. 2,147,483,647
long(64 bits)-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
real numbers:                                                                            classes (Later)

NameWidthRange
float(32 bits)1.40129846432481707e-45 .. ±3.40282346638528860e+38
double(64 bits)±4.94065645841246544e-324 .. ±1.79769313486231570e+308


others:                                                                                        interfaces (Later)

NameWidthRange
char(16 bits)0-65536
booleanfalse .. true




Declaring a primitive variable provides the program with a named data value that can change

while the program is running. An initialization allows the programmer to set the original value of

a variable. This value can be accessed or changed later in the program by using the variable

name.



General Form: Initializing (declaring a primitive variable and giving it a value you want)



type identifier// Declare one variable

type identifier initial-value// For primitive types like int and double

Example: The following code declares one 
int and two double primitive variables while it

initializes grade.


int credits;
double grade = 4.0;
double GPA;




The following table summarizes the initial value of these variables:



Variable Name Value

credits ? // Unknown

grade 4.0 // This was initialized above

GPA ? // Unknown




If you do not initialize a variable, it cannot be used unless it is changed with an assignment

statement. The Java compiler would report this as an error.


Assignment

An assignment gives a value to a variable. The value of the expression to the right of the

assignment operator (
=) replaces the value in the variable to the left of the assignment operator

(
=).



General Form: Assignment

variable-name expression;

The expression must be a value that can be stored by the type of variable to the left of the

assignment operator (
=). For example, an expression that results in a floating-point value can be

stored in a 
double variable, and likewise an integer value can be stored in an int variable.



credits = 4;

grade = 3.0;

GPA = 0.0;


After the two assignments execute, the value of both variables is modified and the values can be shown like this:

Variable Value

credits 4
grade 3.0
GPA 0.0




In an assignment, the Java compiler will check to make sure you are assigning the correct type of value

to the variable. For example, a string literal cannot be assigned to a numeric variable. A

floating-point number cannot be stored in an 
int.



grade = "Noooooo, you can't do that"; // ERROR: Can't store string in a double

credits = 16.5; // ERROR: Cannot store a floating-point number in an int





Practical Session



  1. Create a class that class name should be your name. Save it in a different path (not in C:\). Compile it and Run it. 
  2. Identify given code sample's basic elements that categorized to below five categories.
  • Import statements
  • Classes
  • Methods
  • Variables
  • Comments
  1. Create your own class and it must include below elements.
  • Import statement
  • Class
  • Method
  • Variable
  • Comment
  1. Declare 8 variables in Primitive Data Types and save it as class "PDT".


  2. Try these variable declarations and check them in right syntax or not.(Save it as "Integers.java")
    Give them to a definition in given space.

  • In assume and real mark √ or ×.
DeclarationAssumeRealDefinition
byte b1=0;
Byte b2=0;
byte b3=128;
byte b4=-128;
byte b5=128;
byte b6=132;
short s1=4;
Short s2=1245;
int i1=128;
int i2=12.0;
int i3=-327682;
int i4=00;
int i5=38;
int i6=046;
int  i7=0x26;
Int i8=5000;
long l1=0;
long l2=-0;
Long l3=5;
long l4=32769;


  1. Try these variable declarations and check them in right syntax or not.(Save it as "Floatings.java")
    Give them to a definition in given space.

  • In assume and real mark √ or ×.
DeclarationAssumeRealDefinition
float f1=0.0;
float f2=0.0f;
float f3=12F;
Float f4=-128.04F;
float f5=128F;
double d1=132.0;
double d2=4.5d;
double d3=1245.123D;
double d4=128;
double d5=12.;
double d6=0.003323;
double d7=6.022e23;
double d8=3.14E-05;
Double d9=23;




  1. Try these variable declarations and check them in right syntax or not.(Save it as "Booleans.java")
    Give them to a definition in given space.

  • In assume and real mark √ or ×.
DeclarationAssumeRealDefinition
boolean b1=true;      
boolean b2=false;      
Boolean b3=true;      
boolean b4=True;      
boolean b5=tRue;      
boolean b6="true";      
boolean b7=0;      
boolean b8=null;      
boolean b9=0<5;      
        
        
        
        
        
        

SHALL WE DISCUSS