package com.accenture.sample;
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
----------------------------------------------------------------------------
package com.accenture.sample;
public class MyBicycle extends Bicycle {
// the MountainBike subclass has one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MyBicycle(int startHeight, int startCadence, int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass has one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
----------------------------------------------------------------------------
package com.accenture.sample;
public class ObjectSample {
public static void main(String[] args) {
Ball basketBall = new Ball();
Ball volleyBall = new Ball();
basketBall.getVolume(250);
basketBall.getRadius(200);
basketBall.printState();
volleyBall.getVolume(150);
volleyBall.getRadius(100);
volleyBall.printState();
}
}
class Ball {;
public int radius;
public int volume;
String shape = "circle";
public void getRadius(int newDiameter) {
radius = newDiameter / 2;
}
public void getVolume(int newVolume) {
volume = newVolume;
}
public void printState() {
System.out.println("Volume: " + volume + " " + "Radius: " + radius
+ " " + "Shape: " + shape);
}
}
interface BallMethods{
public void getRadius(int newDiameter);
public void getVolume(int newVolume);
public void printState();
}
---------------------------------------------------------------------------
package com.accenture.sample;
public class TestCoding {
static int ctr = 0;
public static void main(String[] args) {
disp1();
disp2();
disp3();
boolean check;
check = isGreater(200,1000);
System.out.println("Is First Number Greater Than Second Number? : " + check);
}
// Example For Loop
static void disp1() {
for (ctr = 0; ctr < 10; ctr++) {
System.out.println("DM1: Counting... " + (ctr + 1));
}
}
// Example While Loop
static void disp2() {
ctr = 0;
while (ctr < 10) {
System.out.println("DM2: Counting... " + (ctr + 1));
ctr++;
}
}
// Example Do-While Loop
static void disp3() {
ctr = 0;
do {
System.out.println("DM3: Counting... " + (ctr + 1));
ctr++;
} while (ctr < 10);
}
//Example Method Accepting Values and Returning Values
static boolean isGreater(int a, int b) {
boolean answer = (a > b) ? true : false;
return answer;
}
}
ilessthanthreegames
Linggo, Hulyo 24, 2011
Java Food For Thought
Java is a simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multi threaded, dynamic language.
Java formerly known as Oak.
Object Oriented Programming is a programming paradigm using objects.
A programming paradigm is a fundamental style of computer programming.
Object Orientation in programming involves encapsulation, inheritance, polymorphism, and abstraction, is an important approach in programming and program design.
Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones.
Encapsulation means that all data members (fields) of a class are declared private. Some methods may be private, too.
Data encapsulation is the process of hiding internal data from the outside world, and accessing it only through publicly exposed methods.
Inheritance means a class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding its own.
Inheritance allows classes to inherit commonly used state and behavior from other classes.
Polymorphism ensures that the appropriate method is called for an object of a specific type when the object is disguised as a more general type.
An object is a set of data (state) combined with methods (behavior) for manipulating that data.
An object's state is stored in fields.
An object's behavior is exposed through methods
An object is made from a class.
A class is the blueprint for the object.
Common behavior can be defined in a superclass and inherited into a subclass using the extends keyword.
Interface is an abstract type that is used to specify an interface that classes must implement.
An interface may never contain method definitions.
A collection of methods with no implementation is called an interface.
A package is a namespace that organizes a set of related classes and interfaces.
A namespace that organizes classes and interfaces by functionality is called a package.
Conceptually you can think of packages as being similar to different folders on your computer.
"Application Programming Interface", or "API" for short is an enormous class library (a set of packages) suitable for use in your own applications.
Its packages represent the tasks most commonly associated with general-purpose programming.
Instance Variables (Non-Static Fields) - Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields) - A class variable is any field declared with the static modifier; this tells the compiler that there is
exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
Local Variables - Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Parameters - Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.
An array is a container object that holds a fixed number of values of a single type.
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
Java formerly known as Oak.
Object Oriented Programming is a programming paradigm using objects.
A programming paradigm is a fundamental style of computer programming.
Object Orientation in programming involves encapsulation, inheritance, polymorphism, and abstraction, is an important approach in programming and program design.
Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones.
Encapsulation means that all data members (fields) of a class are declared private. Some methods may be private, too.
Data encapsulation is the process of hiding internal data from the outside world, and accessing it only through publicly exposed methods.
Inheritance means a class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding its own.
Inheritance allows classes to inherit commonly used state and behavior from other classes.
Polymorphism ensures that the appropriate method is called for an object of a specific type when the object is disguised as a more general type.
An object is a set of data (state) combined with methods (behavior) for manipulating that data.
An object's state is stored in fields.
An object's behavior is exposed through methods
An object is made from a class.
A class is the blueprint for the object.
Common behavior can be defined in a superclass and inherited into a subclass using the extends keyword.
Interface is an abstract type that is used to specify an interface that classes must implement.
An interface may never contain method definitions.
A collection of methods with no implementation is called an interface.
A package is a namespace that organizes a set of related classes and interfaces.
A namespace that organizes classes and interfaces by functionality is called a package.
Conceptually you can think of packages as being similar to different folders on your computer.
"Application Programming Interface", or "API" for short is an enormous class library (a set of packages) suitable for use in your own applications.
Its packages represent the tasks most commonly associated with general-purpose programming.
Instance Variables (Non-Static Fields) - Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields) - A class variable is any field declared with the static modifier; this tells the compiler that there is
exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
Local Variables - Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Parameters - Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.
An array is a container object that holds a fixed number of values of a single type.
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
Java Primitive Data Types
Primitive Data Types
int gear = 1;
int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:- byte: The
bytedata type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). Thebytedata type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place ofintwhere their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
- short: The
shortdata type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As withbyte, the same guidelines apply: you can use ashortto save memory in large arrays, in situations where the memory savings actually matters.
- int: The
intdata type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, uselonginstead.
- long: The
longdata type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided byint.
- float: The
floatdata type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations forbyteandshort, use afloat(instead ofdouble) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings coversBigDecimaland other useful classes provided by the Java platform.
- double: The
doubledata type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
- boolean: The
booleandata type has only two possible values:trueandfalse. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
- char: The
chardata type is a single 16-bit Unicode character. It has a minimum value of'\u0000'(or 0) and a maximum value of'\uffff'(or 65,535 inclusive).
String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data ObjectsDefault Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero ornull, depending on the data type. Relying on such default values, however, is generally considered bad programming style.The following chart summarizes the default values for the above data types.
| Data Type | Default Value (for fields) |
|---|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0d |
| char | '\u0000' |
| String (or any object) | null |
| boolean | false |
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Literals
You may have noticed that thenew keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
Integer Literals
An integer literal is of typelong if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.Values of the integral types
byte, short, int, and long can be created from int literals. Values of type long that exceed the range of int can be created from long literals. Integer literals can be expressed these number systems:- Decimal: Base 10, whose digits consists of the numbers 0 through 0; this is the number system you use every day
- Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F
- Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later)
0x indicates hexadecimal and 0b indicates binary:int decVal = 26; // The number 26, in decimal
int hexVal = 0x1a; // The number 26, in hexadecimal
int binVal = 0b11010; // The number 26, in binary
Floating-Point Literals
A floating-point literal is of typefloat if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.The floating point types (
float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;
Character and String Literals
Literals of typeschar and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as '\u0108' (capital C with circumflex), or "S\u00ED se\u00F1or" (Sí Señor in Spanish). Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just in char or String literals.The Java programming language also supports a few special escape sequences for
char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).There's also a special
null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending "
.class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Sabado, Hulyo 23, 2011
My Own Implementation of Array Push, Pop, Peek and Find Element
package com.accenture.sample;
import java.util.Scanner;
public class MyArray {
static int[] listnum = new int[10];
static int count = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//getNum();
//getInput();
//dispList();
//System.out.println(peekArray());
//System.out.println(findElem(peekArray()));
//System.out.println(popArray());
//boolean check;
//check = pushArray(999)? true:false;
//dispList();
//System.out.println("can i push? " + check);
dispList();
}
static void getInput(){
for (int i = 0; i < listnum.length; i++) {
listnum[i]=input.nextInt();
}
}
static int popArray(){
int element;
int elementsfound = 0;
for(int ctr = 0;ctr<listnum.length;ctr++){
if (listnum[ctr]!=0) {
elementsfound++;
}
if ((ctr==(listnum.length-1))&&(elementsfound==0)){
return -1;
}
}
count--;
element = listnum[count];
listnum[count]=0;
return element;
}
static int findElem(int element){
for (int ctr=0;ctr<listnum.length;ctr++) {
if (element==listnum[ctr]){
return ((listnum.length-ctr)-1);
}
}
return -1;
}
static boolean pushArray(int element){
if (listnum[listnum.length-1]!=0){
return false;
}
listnum[count]=element;
count++;
return true;
}
static int peekArray(){
int element;
element = listnum[(listnum.length-1)];
return element;
}
static void getNum(){
count=0;
for (int ctr=0;ctr<listnum.length;ctr++) {
listnum[ctr]=ctr+90;
count++;
}
}
static void dispList() {
for (int ctr=0;ctr<listnum.length;ctr++) {
System.out.println("Array Element in ListNum[" + ctr + "] : " + listnum[ctr]);
System.out.println("ListNum[" + ctr + "] is in Position : " + ((listnum.length-ctr)-1));
}
}
}
import java.util.Scanner;
public class MyArray {
static int[] listnum = new int[10];
static int count = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//getNum();
//getInput();
//dispList();
//System.out.println(peekArray());
//System.out.println(findElem(peekArray()));
//System.out.println(popArray());
//boolean check;
//check = pushArray(999)? true:false;
//dispList();
//System.out.println("can i push? " + check);
dispList();
}
static void getInput(){
for (int i = 0; i < listnum.length; i++) {
listnum[i]=input.nextInt();
}
}
static int popArray(){
int element;
int elementsfound = 0;
for(int ctr = 0;ctr<listnum.length;ctr++){
if (listnum[ctr]!=0) {
elementsfound++;
}
if ((ctr==(listnum.length-1))&&(elementsfound==0)){
return -1;
}
}
count--;
element = listnum[count];
listnum[count]=0;
return element;
}
static int findElem(int element){
for (int ctr=0;ctr<listnum.length;ctr++) {
if (element==listnum[ctr]){
return ((listnum.length-ctr)-1);
}
}
return -1;
}
static boolean pushArray(int element){
if (listnum[listnum.length-1]!=0){
return false;
}
listnum[count]=element;
count++;
return true;
}
static int peekArray(){
int element;
element = listnum[(listnum.length-1)];
return element;
}
static void getNum(){
count=0;
for (int ctr=0;ctr<listnum.length;ctr++) {
listnum[ctr]=ctr+90;
count++;
}
}
static void dispList() {
for (int ctr=0;ctr<listnum.length;ctr++) {
System.out.println("Array Element in ListNum[" + ctr + "] : " + listnum[ctr]);
System.out.println("ListNum[" + ctr + "] is in Position : " + ((listnum.length-ctr)-1));
}
}
}
Biyernes, Hulyo 22, 2011
Q&A Java Language 5
- The most basic control flow statement supported by the Java programming language is the ___ statement.
- The ___ statement allows for any number of possible execution paths.
- The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.
- How do you write an infinite loop using the for statement?
- How do you write an infinite loop using the while statement?
- The most basic control flow statement supported by the Java programming language is the if-then statement.
- The switch statement allows for any number of possible execution paths.
- The do-while statement is similar to the while statement, but evaluates its expression at the bottom of the loop.
- Question: How do you write an infinite loop using the for statement?
Answer:
for ( ; ; ) {
}
- Question: How do you write an infinite loop using the while statement?
Answer:
while (true) {
}
Q&A Java Language 4
- Operators may be used in building ___, which compute values.
- Expressions are the core components of ___.
- Statements may be grouped into ___.
- The following code snippet is an example of a ___ expression.
1 * 2 * 3
- Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a ___.
- A block is a group of zero or more statements between balanced ___ and can be used anywhere a single statement is allowed.
- Operators may be used in building expressions, which compute values.
- Expressions are the core components of statements.
- Statements may be grouped into blocks.
- The following code snippet is an example of a compound expression.
1 * 2 * 3
- Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a semicolon.
- A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
Q&A Java Language 3
- Consider the following code snippet.
2. arrayOfInts[j] > arrayOfInts[j+1]
Which operators does the code contain?
- Consider the following code snippet.
4. int i = 10;
5. int n = i++%5;
- What are the values of i and n after the code is executed?
- What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?
- To invert the value of a boolean, which operator would you use?
- Which operator is used to compare two values, = or == ?
- Explain the following code sample: result = someCondition ? value1 : value2;
- Consider the following code snippet:
2. arrayOfInts[j] > arrayOfInts[j+1]
Question: What operators does the code contain?
Answer: >, +
Answer: >, +
- Consider the following code snippet:
4. int i = 10;
5. int n = i++%5;
- Question: What are the values of i and n after the code is executed?
Answer: i is 11, and n is 0. - Question: What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?
Answer: i is 11, and n is 1. - Question: To invert the value of a boolean, which operator would you use?
Answer: The logical complement operator "!". - Question: Which operator is used to compare two values, = or == ?
Answer: The == operator is used for comparison, and = is used for assignment. - Question: Explain the following code sample: result = someCondition ? value1 : value2;
Answer: This code should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
Mag-subscribe sa:
Mga Post (Atom)