• Home

Binary To Decimal or Any Integer (Java)

Isn’t it a very tedious job to enter the values each time before the compilation in the method itself. Now if we want to enter an integer value after the compilation of a program and force the JVM to ask for an input, then we should use Integer.parseInt(string str). 

As we know that JVM reads each data type in a String format. Now consider a case where we to enter a value in  int primitive type, then we have to use int x = Integer.parseInt(“any String”) , because the value we have entered is in integer but it will be interpreted as a String so, we have to change the string into integer. Here Integer is a name of a class in java.lang package and parseInt() is a method of Integer class which converts String to integer. If we want to enter a integer in a method or class using keyboard, then we have to use a method parseInt().

In this program we are going to calculate a area of a rectangle by using two classes named Rectangle and EnterValuesFromKeyboard. In the first class we have used two methods, show(int x, int y) andcalculate(). First method show() is taking two variables as input and second method calculate()calculates the area of a rectangle. In the second class which is also our main class we declare a will declare our main method. Inside this method we will create a object of a Rectangle class. Now we ask the user to input two values and stored those values in the variables. These entered values will be changed into integer by using parseInt() method. Now these variables are passed in the method show()and the area will be calculated by calculate() method. These methods will be called by the instance of Rectangle class because it is the method of Rectangle class. 

class Rectangle{
  int length, breadth;
  void show(int x, int y){
  length = x;
  breadth = y;
  }
  int calculate(){
  return(length * breadth);
  }
}
public class EnterValuesFromKeyboard{
  public static void main(String[] args) {
  Rectangle rectangle = new Rectangle();
  int a = Integer.parseInt(args[0]);
  int b = Integer.parseInt(args[1]);
  rectangle.show(a, b);
  System.out.println(
  " you have entered these values : " +  a  + " and " +  b);
  int area = rectangle.calculate();
  System.out.println(" area of a rectange is  : " + area);
  }
}

C:\java>java EnterValuesFromKeyboard 4 5
you have entered these values : 4 and 5
area of a rectange is : 20
(daha fazla…)

A Closer Look at the “Hello World!” Application

Hello world program created in a previous article.

Now that you’ve seen the “Hello World!” application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

The “Hello World!” application consists of three primary components: source code commentsthe HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you’ve finished reading the rest of the tutorial.

Source Code Comments

The following bold text defines the comments of the “Hello World!” application:

/** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:

/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /*and */. The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the Javadoc™ tool documentation .
// text
The compiler ignores everything from // to the end of the line. (daha fazla…)

Creating Your First JAVA Application :: Hello World

Article was taken from Oracle

Your first application, HelloWorldApp, will simply display the greeting “Hello World!” To create this program, you will:

  • Create an IDE projectWhen you create an IDE project, you create an environment in which to build and run your applications. Using IDE projects eliminates configuration issues normally associated with developing on the command line. You can build or run your application by choosing a single menu item within the IDE.
  • Add code to the generated source fileA source file contains code, written in the Java programming language, that you and other programmers can understand. As part of creating an IDE project, a skeleton source file will be automatically generated. You will then modify the source file to add the “Hello World!” message.
  • Compile the source file into a .class fileThe IDE invokes the Java programming language compiler (javac), which takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.
  • Run the programThe IDE invokes the Java application launcher tool (java), which uses the Java virtual machine to run your application.

Create an IDE Project

To create an IDE project:

  1. Launch the NetBeans IDE.
    • On Microsoft Windows systems, you can use the NetBeans IDE item in the Start menu.
    • On Solaris OS and Linux systems, you execute the IDE launcher script by navigating to the IDE’s bin directory and typing ./netbeans.
    • On Mac OS X systems, click the NetBeans IDE application icon.
  2. In the NetBeans IDE, choose File | New Project.
    NetBeans IDE with the File | New Project menu item selected. 
    NetBeans IDE with the File | New Project menu item selected.  (daha fazla…)

Expressions, Statements, and Blocks

Now that you understand variables and operators, it’s time to learn about expressionsstatements, and blocks. Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks.

Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You’ve already seen examples of expressions, illustrated in bold below:

int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3
if (value1 == value2) System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here’s an example of a compound expression:

Summary of Operators in Java

The following quick reference summarizes the operators supported by the Java programming language.

Simple Assignment Operator

=       Simple assignment operator

Arithmetic Operators

+       Additive operator (also used
        for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%       Remainder operator

Unary Operators

+       Unary plus operator; indicates
        positive value (numbers are
        positive without this, however)
-       Unary minus operator; negates
        an expression
++      Increment operator; increments
        a value by 1
--      Decrement operator; decrements
        a value by 1
!       Logical complement operator;
        inverts the value of a boolean

Equality and Relational Operators

==      Equal to
!=      Not equal to
>       Greater than
>=      Greater than or equal to
<       Less than
<=      Less than or equal to

Conditional Operators

&&      Conditional-AND
||      Conditional-OR
?:      Ternary (shorthand for
        if-then-else statement)

Type Comparison Operator

instanceof      Compares an object to
                a specified type

Bitwise and Bit Shift Operators

~       Unary bitwise complement
<<      Signed left shift
>>      Signed right shift
>>>     Unsigned right shift
&       Bitwise AND
^       Bitwise exclusive OR
|       Bitwise inclusive OR

What Is an Interface?

As you’ve already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object’s interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the “power” button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior, if specified as an interface, might appear as follows:

interface Bicycle {

    //  wheel revolutions per minute
    void changeCadence(int newValue);

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you’d use theimplements keyword in the class declaration:

class ACMEBicycle implements Bicycle {

    // remainder of this class
    // implemented as before
}

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

What Is Inheritance?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes thesuperclass of MountainBikeRoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

A diagram of classes in a hierarchy. 
A hierarchy of bicycle classes.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

    // new fields and methods defining
    // a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

What Is a Class?

Text from : http://docs.oracle.com/javase/tutorial/java/concepts/class.html

In the real world, you’ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:

class Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

    void changeCadence(int newValue) {
         cadence = newValue;
    }

    void changeGear(int newValue) {
         gear = newValue;
    }

    void speedUp(int increment) {
         speed = speed + increment;
    }

    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }

    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" +
             speed + " gear:" + gear);
    }
}

The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fieldscadencespeed, and gear represent the object’s state, and the methods (changeCadencechangeGearspeedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That’s because it’s not a complete application; it’s just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.

Here’s a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:

class BicycleDemo {
    public static void main(String[] args) {

        // Create two different
        // Bicycle objects
        Bicycle bike1 = new Bicycle();
        Bicycle bike2 = new Bicycle();

        // Invoke methods on
        // those objects
        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        bike2.printStates();
    }
}

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

What Is an Object?

Objects are key to understanding object-oriented technology. Look around right now and you’ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: “What possible states can this object be in?” and “What possible behavior can this object perform?”. Make sure to write down your observations. As you do, you’ll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.  (daha fazla…)

Android :: Konu 1 :: Merhaba Android

Öncelikle Android SDK’nın çalışma mantığı hakkında size bilgi vermek istiyorum. Android SDK büyük bölümü java ile yazılmış bir uygulama geliştirme aracı. Android SDK bize üzerinde çalışabilmemiz için sanal bir veya birden fazla cihaz (evet sanal telefon) ve kendi yazılım kütüphane dosyalarını sunuyor. Bu da şu demek; bu yazdığımız kodları denemek için illa ki android yüklü bir cep telefonu, PDA ya da herhangi bir elektronik cihaza ihtiyacınız yok. Uygulama ortamı içerisinde çalışma zamanında dahi bu sanal cihazı oluşturup istediğiniz özellikleri vermeniz mümkün. Android SDK nın içerisinde de ayrıca ingilizce olarak yazılmış dökümanlar var. Bunlardan rahatlıkla yararlanabilirsiniz. Ayrıca yazılım kütüphanelerinin ne işe yaradığını, neler yapabildiğini, sınırlarının ne olduğunu anlatan “referans dökümanı” da bu dökümanlar içerisinde mevcut. Tek bilmeniz gereken biraz ingilizce. Eğer ingilizce ile alakalı sorun yaşıyorsanız “google translate” hizmetinden ve internette yayında olan sözlüklerden yararlanın. Bu kısa bilgilerden sonra şimdi örneğimize geçelim isterseniz.

Bu arada yine bazı yazılarımda yaptığım gibi bu yazıyı da  çok zaman kaybetmemek için hazır şekilde aldım ve buraya yerleştirdim (büyük bölümünü). Nedeni ise, zaten herkesin aynı şekilde anlattığı bir konuyu farklı şekilde anlatmak tek kaynak kullanmayan arkadaşlar için kafa karışıklığının önüne geçmek.  (daha fazla…)