Core Java Programming
Core Java Programming
OOPs Concepts
Class & Object
Encapsulation
Inheritance
Polymorphism
Data abstraction
Data Types :
Specifies the type of data stored in the system.
int, char, string, Boolean, double, float, byteetc
In programming languages a data type is an attribute of a piece of data that explains what kind of
data is being dealt with. This involves setting constraints on the data, such as what values that
data can take on, and what operations may be performed on that data. The Java programming
language is strongly-typed, which means that all variables must first be defined or declared
before they can be used in the actual code. This is often related to the Option Explicit statement
used within Microsoft languages.
byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of
-128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving
memory in large arrays, where the memory savings actually matters. They can also be used in
place of int where 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 short data 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 with byte, the same guidelines apply:
you can use a short to save memory in large arrays, in situations where the memory savings
actually matters.
int: The int data 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, use long instead.
long: The long data 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 by int.
float: The float data 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 for byte and short, use a float (instead of double) 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 covers BigDecimal and other useful classes
provided by the Java platform.
double: The double data 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 boolean data type has only two possible values: true and false. 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 char data 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).
Variables :
Variables are identifiers to store the value in the memory, the variables are available only
during runtime of the program.
Declare variables
int x,y;
char x(10);
boolean y;
variable declaration is compulsory
To declare a variable in Java, all that is needed is the data type followed by the variable name:
int numberOfDays;
In the above example, a variable called "numberOfDays" has been declared with a data type of
int. Notice how the line ends with a semi-colon. The semi-colon tells the Java compiler that the
declaration is complete.
Now that it has been declared, numberOfDays can only ever hold values that match the
definition of the data type (i.e., for an int data type the value can only be a whole number
between -2,147,483,648 to 2,147,483,647).
byte nextInStream;
short hour;
long totalNumberOfStars;
float reactionTime;
double itemPrice;
Initializing Variables
Before a variable can be used it must be given an initial value. This is called initializing the
variable. If we try to use a variable without first giving it a value:
int numberOfDays;
//try and add 10 to the value of numberOfDays
numberOfDays = numberOfDays + 10;
int numberOfDays;
numberOfDays = 7;
In the above example, numberOfDays has been declared with a data type of int and has been
giving an initial value of 7. We can now add ten to the value of numberOfDays because it has
been initialized:
int numberOfDays;
numberOfDays = 7;
numberOfDays = numberOfDays + 10;
System.out.println(numberOfDays);
Typically, the initializing of a variable is done at the same time as its declaration:
they cannot start with a digit but digits can be used after the first character (e.g., name1,
n2ame are valid).
they can start with a letter, an underscore (i.e., "_") or a dollar sign (i.e., "$").
Always give your variables meaningful identifiers. If a variable holds the price of a book, then
call it something like "bookPrice". If each variable has a name that makes it clear what it's being
used for, it will make finding errors in your programs a lot easier.
Finally, there are naming conventions in Java that I would encourage you to use. You may have
noticed that all the examples I have given follow a certain pattern. When more than one word is
used in combination in a variable name it is given a capital letter (e.g., reactionTime,
numberOfDays.) This is known as mixed case and is the preferred choice for variable identifiers.
Class :
What is Java Class?
Java class is nothing but a template for object you are going to create or its a blue print by using
this we create an object. In simple word we can say its a specification or a pattern which we
define and every object we define will follow that pattern.
Template is:
Class (name of the class)
{
Field: field is nothing but the property of the class or object which we are going to create .for
example if we are creating a class called computer then they have property like model,
mem_size, hd_size, os_type etc
Method: method is nothing but the operation that an object can perform it define the behavior of
object how an object can interact with outside world .startMethod (), shutdownMethod ().
Access Level of members: Access level is nothing but where we can use that members of the
class.
Each field and method has an access level:
private: accessible only in this class
package or default: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available
In real world if we want to understand about the class everything of same quality can be
visualize as a class e.g. men,women,birds ,bicycles ,cars or we can say vehicle .
The entire vehicle will make one class they have the property like no_of_wheels, color, model,
brand etc.now we can think changeGear () and speedOfvehicle (), applyBreak () etc as a method
on that class. Similarly all human being also can be one class now their member will be a men
,women ,child.,isAlive() ,isDeath() can be their method or behavior of that class .again we can
make Men or women a separate class and define their property and method accordingly,
In short in java every problem we get solution can be think in terms of class and object.
}
Public boolean sale ()
{
}
}
In this example Stock is called Class and commodity, price are field and buy() and sale() are two
methods defined inside class. To access elements of Class you need to create an instance of class
Stock. You can create instance of Class using keyword new as shown below
highBetaStock.buy(1000);
highBetaStock.sell();
Summary:
In short in java everything must be thinking in terms of java class its nothing but a template they
have their own members and methods for accessing those members. The entire member has their
own visibility which is decided by the developer where they want to use those objects.
A class will have set of properties and methods and these are the building blocks in java
programming
Ex: TV----properties : color, name, price, model, methods : on, off, volume, brigtness
Window -------properties : height, width, bgcolor, forground color, title methods :
close, minimize, maximize, activate, dragetc
Ex:
public class Emp
{
string ename="james";
int sal=2000;
string dob="10-10-1980";
public void getdetails()
{
System.out.println("Emp name :"+ename);
System.out.println("Salary :"+sal);
System.out.println("DOB :"+dob);
}
public static void main(String args[])
{
Emp e=new Emp();
e.getdetails();
}
}
Access specifiers :
Public ------- the scope is we can access the methods in any class
Private--------we can access these methods only in this class
Protected------we can access these methods in this class and inherited class
import java.io.*;
\b backspace
\t Tab
\n linefeed
\f formfeed
\r carriage return
\" double quote, "
\' single quote, '
\\ backslash, \
OOPS Concepts
Abstraction - The process of abstraction in Java is used to hide certain details and only show the
essential features of the object. In other words, it deals with the outside view of an object
(interface).
Polymorphism - It describes the ability of the object in belonging to different types with specific
behavior of each type. So by using this, one object can be treated like another and in this way it
can create and define multiple level of interface. Here the programmers need not have to know
the exact type of object in advance and this is being implemented at runtime.
Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means
that an object of a subclass can be used wherever an object of the superclass can be used. Class
Inheritance in java mechanism is used to build new classes from existing classes. The
inheritance relationship is transitive: if class x extends class y, then a class z, which extends class
x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find
that the base class is the vehicle class and the subclass is the more specific car class. A subclass
must use the extends clause to derive from a super class which must be written in the header of
the subclass definition. The subclass inherits members of the superclass and hence promotes
code reuse. The subclass itself can add its own new behavior and properties. The
java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box
{
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}
double weight;
MatchBox() {
}
MatchBox(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
public static void main(String args[]) {
MatchBox mb1 = new MatchBox(10, 10, 10, 10);
mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);
}
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses
in other packages, as these members are only accessible by their simple names in subclasses
within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
4. A subclass can extend only one superclass
class Vehicle {
// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter; // No of Vehicle objects created
// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}
public void switchOff() {
accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}
Output
The this reference to the current object is useful in situations where a local variable hides, or
shadows, a field with the same name. If a method needs to pass the current object to another
method, it can do so using the this reference. Note that the this reference cannot be used in a
static context, as static code is not executed in the context of any object.
class Counter {
int i = 0;
Counter increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
}
public class CounterDemo extends Counter {
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Polymorphism
What is Polymorphism?
This concept of polymorphism in Java especially, is actually not hard to understand at all. Oh
look, different animals make different sounds, and the same method can be used to make each
distinct sound. If you've done the Java inheritance tutorial, you already know how to do this!
One powerful tool for using polymorphic behavior is to use the same method name but in the
same class, over and over again to get the desired effects you want. How can we use
polymorphism in Java to accomplish this?
Overloaded Methods
Let's use our makeSound() example again. Let's say a dog makes a woof sound, but if the dog is
injured, the dog might make a whimper noise instead. How can we use makeSound() to produce
both sounds? Take a look at this code snippet:
NOTE: At this point, if you're not sure you understand the code you see, you REALLY should
go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can
come back to learn about polymorphism in Java once you have a better understanding of
methods.
We can see here that depending on the number of parameters we pass to makeSound(), the dog
will make a different sound. But wait! Couldn't we have just used an if statement and make this
just one method? Yes, we could have done that and that's probably a better way of programming
this for this particular example. What if an outside action causes the difference in dog sound
though? Something like this:
If the dog did not have the variable to know it was hurt, you would not be able to write that if
statement as easily.
You can overload a method as much as you want as long as the number of parameters are
different or the types of parameters are different. You could not do this for example:
This is because those are the same number of parameters AND are the same types of parameters.
Overridden Methods
In Java, you can create a method in a superclass (or parent class), then in a subclass ALSO define
that method. Let's see an example of this using Animal:
Now, let's say you could actually create Animals. If you could, then calling makeSound() would
call the method defined in the superclass. If you create a specific Dog, calling makeSound() will
display woof. Now let's say you created a specific Cat. In that example, Cat does not have a
makeSound() method, so when you call makeSound() on Cat, it calls the method in the
superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because
they extend Animal.
This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes
to polymorphism in Java. Java will let you do this because its possible more specific types of
objects have more specific behaviors for actions. How does Java then know which method to
actually call? Java will always pick the object's true type for choosing which method to call, the
superclass or the subclass. We will see what true type really means in the next section.
Dynamic Method Binding
Do not let the long name confuse you. This is not that scary of a term! We won't discuss why this
is dynamic, but let's just say that Java decides what method to call during runtime, or once the
program is running. Dynamic method binding is how Java decides what method to call when it
has to decide between the superclass and the subclass. So, how exactly does it decide? To
illustrate this point, we must first illustrate the concept of true type versus referenced type.
Look, we just made a Dog but declared it as an Animal! Normally you would see this:
However, you can also declare a variable by its supertype or abstract type to make it more
generic. Let's say you don't know what kind of animal you want:
Notice how the variable is not assigned to anything! We have an animal that has not been
instantiate, and it does not equal anything. We can't create just Animals because they are abstract,
so we must make a specific kind of animal, which is what we did with the example above by
making the Animal be a new Dog.
So, which version of makeSound() would you use if you saw Animal animal = new Dog() ?
Would you choose the Animal's version or the Dog's version? The answer is that Java will choose
the true type, and the true type is the object that actually gets created. In this example, what we
are really creating is a Dog, even though we are referencing the variable as an Animal.
Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using
abstraction, you can actually group many different types of objects together. Let's see how we
can use this concept for storing objects:
We could not do the above if the Cat objects and Dog objects were made the traditional way and
not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this:
First of all, in our example, you cannot create Animal objects because they are abstract. Let's
assume you could though. This is still illegal because a specific type cannot be the reference of a
more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a
dog. The above example is basically saying that an Animal is a Dog, and this is not always true.
Polymorphism in Java allows you to fully control how you group objects together and gives you
the power to make them as specific as you want. It is also the crucial part of object-oriented
programming that allows you to build hierarchies of objects, objects that have a logical structure
that makes sense in the real world. Because of polymorphism, you can create highly
sophisticated programs in Java that are easy to read and are well organized. It does not guarantee
an awesome organization of your code, but if you're careful it can help you immensely in doing
so.
Conditional Statments
The if-then and if-then-else Statements
The if Statement
The if statement is basic conditional statement of all control flow statements. If the condition
matches only the specified statements are executed. That is if the condition is true.
For example, the Emp class could allow to increase salary if he is permanent emp
class Emp
{
public void Salarycal()
{
if(empstatus= = permanent)
{
//code to cal salary
}
}
If this test evaluates to false (meaning that the emp is not permanent emp), control jumps to the
end of the if statement.
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code
more brittle. If a second statement is later added to the "then" clause, a common mistake would
be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll
just get the wrong results.
class Emp
{
public void Salarycal()
{
if(empstatus= = permanent)
{
//code to cal salary
}
else
{
// code to cal salary for not permanent emp
}
}
The following program, Sample, assigns a grade based on the value of a test score: an A for a
score of 90% or above, a B for a score of 80% or above, and so on.
class sample {
public static void main(String args[])
{
Grade = C
You may have noticed that the value of score can satisfy more than one expression in the
compound statement: 72 >= 70 and 72 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.
Examples :
class Example1
{
public static void main(String args[])
{
int n=5;
if(n % 2 = = 0)
{
system.out.println("It is even number");
}
else
{
system.out.println("It is odd number");
}
}
}
Display the biggest of 2 numbers
class Example2
{
public static void main(String args[])
{
int x=5;
int y=8;
if(x > y)
{
system.out.println("x is biggest");
}
else
{
system.out.println("y is biggest");
}
}
}
The Switch case statement can be used sometimes as an alternative to multiple if else
conditions
The switch statement can have a number of possible execution paths. A switch works with the
byte, short, char, and int primitive data types. It also works with enumerated types (discussed in
Enum Types), the String class, and a few special classes that wrap certain primitive types:
Character, Byte, Short, and Integer (discussed in Numbers and Strings).
class Volcheck
{
char str;
str='a';
Switch (str)
{
case 'a'
case 'e'
case 'i'
case 'o'
case 'u'
system.out.println("It is vowel");
break;
default:
system.out.println("It is not vowel");
}
int month = 8;
String strmonth;
switch (month)
{
case 1: strmonth = "January";
break;
case 2: strmonth = "February";
break;
case 3: strmonth = "March";
break;
case 4: strmonth = "April";
break;
case 5: strmonth = "May";
break;
case 6: strmonth = "June";
break;
case 7: strmonth = "July";
break;
case 8: strmonth = "August";
break;
case 9: strmonth = "September";
break;
case 10: strmonth = "October";
break;
case 11: strmonth = "November";
break;
case 12: strmonth = "December";
break;
default: strmonth = "Invalid month";
break;
}
System.out.println(strmonth);
}
}
Loop Statements
The Loop statements are used to run the statements for multiple Iterations
Different Loop statements in java
while
do while
for..loop
The while statement continually executes group of statements while a particular condition is true.
Its syntax can be expressed as:
while (condition)
{
statement(s)
}
The while statement evaluates condition, which returns a Boolean value. If the condition
evaluates to true, the while statement executes the statement(s) in the while block
class Sample
{
public static void main(String args[])
{
int i;
i=1;
while(i<=10)
{
system.out.println("The value is "+i);
i=i+1;
}
}
dowhile
The do loop also executes the program while the condition is statisfied but like while,,
here the block of statements are executed and then check the condition
class Sample
{
public static void main(String args[])
{
int i;
i=1;
do
{
system.out.println("The value is "+i);
i=i+1;
}while(i<=10);
}
class Sample
{
public static void main(String args[])
{
int i;
i=12;
do
{
system.out.println("The value is "+i);
i=i+1;
}while(i<=10);
}
In the above code, first execute the block and then check the condition, as the block is executed 1
time then check the condition, as condition not satisfied it will stop, but already one time
executed
The initialization expression initializes the loop; it's executed once, as the loop begins.
class Sample
{
public static void main(String args[])
{
for(int i=1;i<=20;i++)
{
system.out.println("The value is "+i);
}
}
int a,b,c;
a=1;
b=1;
c=a+b;
system.out.println(a);
system.out.println(b);
while(c<=100)
{
system.out.println(c);
a=b;
b=c;
c=a+b;
}
}
}
Print Sum of Even number from 1 to 100
class Evensum
{
public static void main(String args[])
{
int sum=0;
for(int i=1;i<=100;i++)
{
if(i %2= = 0)
{
sum=sum+i
}
}
System.out.println(Sum of all even numbers from 1-100 is +sum);
}
}
Array
An array is a variable to store multiple values of same data type
Once defined , the size of an array is fixed and cannot increase to accommodate more
elements.
Int x[6]
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
how this helps is that the index (the number in the bracket[]) can be referenced by a
variable for easy looping.
<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];
Example:
int intArray[]; // Defines that intArray is an ARRAY variable of which will store integer values
int []intArray;
Constructing an Array
Example:
intarr = new int[10]; // Defines that intArray will store 10 integer values
Initializing an Array
intarr[0]=1; // Assigns an integer value 1 to the first element 0 of the array
intarr[1]=2; // Assigns an integer value 2 to the second element 1 of the array
Example:
int intarr[] = {1, 2, 3, 4}; // Initilializes an integer array of length 4 where the first element is 1 ,
second element is 2 and so on.
Assignment: First Array Program
Example
class ArrayDemo
{
public static void main(String args[])
{
int arr[ ] = new int[7];
for (int count=0;count<7;count++)
{
arr[count]=count+1;
}
for (int count=0;count<7;count++)
{
System.out.println("arr["+count+"] = "+arr[count]);
}
System.out.println("Length of Array = "+arr.length);
}
}
class ArrayDemo
{
public static void passByReference(String a[]);
{
a[1] = "Changed";
}
public static void main(String args[])
{
String []b={"Apple","Mango","Orange"};
System.out.println("Before Function Call "+b[0]);
ArrayDemo.passByReference(b);
System.out.println("After Function Call "+b[0]);
}
}
Save , Compile & Run the code. Observe the Output
multidimensional arrays
Multidimensional arrays, are arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another set of
square brackets.
When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension.
In Java the length of each array in a multidimensional array is under your control.
Ex:
int twoD[][] = new int[4][];
Package
Definition:
A package is a grouping of related types providing access protection and name space
management. Note that types refers to classes, interfaces, enumerations, and annotation types.
Enumerations and annotation types are special kinds of classes and interfaces, respectively, so
types are often referred to in this lesson simply as classes and interfaces.
The types that are part of the Java platform are members of various packages that bundle classes
by function: fundamental classes are in java.lang, classes for reading and writing (input and
output) are in java.io, and so on. You can put your types in packages too.
Suppose you write a group of classes that represent graphic objects, such as circles, rectangles,
lines, and points. You also write an interface, Draggable, that classes implement if they can be
dragged with the mouse.
You and other programmers can easily determine that these types are related.
You and other programmers know where to find types that can provide graphics-related
functions.
The names of your types won't conflict with the type names in other packages because
the package creates a new namespace.
You can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the package.
To use a public package member from outside its package, you must do one of the following:
Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Its Qualified Name
So far, most of the examples in this tutorial have referred to types by their simple names, such as
Rectangle and StackOfInts. You can use a package member's simple name if the code you are
writing is in the same package as that member or if that member has been imported.
However, if you are trying to use a member from a different package and that package has not
been imported, you must use the member's fully qualified name, which includes the package
name. Here is the fully qualified name for the Rectangle class declared in the graphics
package in the previous example.
graphics.Rectangle
You could use this qualified name to create an instance of graphics.Rectangle:
import graphics.Rectangle;
Now you can refer to the Rectangle class by its simple name.
import graphics.*;
Now you can refer to any class or interface in the graphics package by its simple name.
Note:
Another, less common form of import allows you to import the public nested classes of an
enclosing class. For example, if the graphics.Rectangle class contained useful nested classes,
such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its
nested classes by using the following two statements.
import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.
Another less common form of import, the static import statement, will be discussed at the end of
this section.
For convenience, the Java compiler automatically imports three entire packages for each source
file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the
package for the current file).
Importing java.awt.* imports all of the types in the java.awt package, but it does not import
java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the
classes and other types in java.awt.color as well as those in java.awt, you must import both
packages with all their files:
import java.awt.*;
import java.awt.color.*;
Name Ambiguities
If a member in one package shares its name with a member in another package and both
packages are imported, you must refer to each member by its qualified name. For example, the
graphics package defined a class named Rectangle. The java.awt package also contains a
Rectangle class. If both graphics and java.awt have been imported, the following is
ambiguous.
Rectangle rect;
In such a situation, you have to use the member's fully qualified name to indicate exactly which
Rectangle class you want. For example,
graphics.Rectangle rect;
The Static Import Statement
There are situations where you need frequent access to static final fields (constants) and static
methods from one or two classes. Prefixing the name of these classes over and over can result in
cluttered code. The static import statement gives you a way to import the constants and static
methods that you want to use so that you do not need to prefix the name of their class.
The java.lang.Math class defines the PI constant and many static methods, including methods
for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many
more. For example,
String Methods
Method Summary
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing
the result into a new byte array.
Deprecated. This method does not properly convert characters into bytes. As of JDK 1.1,
the preferred way to do this is via the the getBytes() method, which uses the platform's default
charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result
into a new byte array.
int hashCode()
Returns a hash code for this string.
String intern()
Returns a canonical representation for the string object.
int length()
Returns the length of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default
locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given
Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Integer Methods
byte byteValue()
Returns the value of this Integer as a byte.
double doubleValue()
Returns the value of this Integer as a double.
float floatValue()
Returns the value of this Integer as a float.
int hashCode()
Returns a hash code for this Integer.
int intValue()
Returns the value of this Integer as an int.
long longValue()
Returns the value of this Integer as a long.
short shortValue()
Returns the value of this Integer as a short.
static String toBinaryString(int i)
Returns a string representation of the integer argument as an unsigned integer in base 2.
String toString()
Returns a String object representing this Integer's value.
File menu-? new class? Enter Class name Emp?Select public static void main method OK
import java.io.*;
import java.io.*;
System.out.println("Enter a number");
x=Integer.parseInt(br.readLine());
System.out.println("Enter another number");
y=Integer.parseInt(br.readLine());
if (x>y)
{
System.out.println("x is biggest");
}
else
{
System.out.println("y is biggest");
}
}
}
import java.io.*;
public class sample
{
public static void main(String[] args) throws IOException
{
System.out.println("Please enter a grade character: A, B, C, or D:");
char grade;
grade=(char)System.in.read();
System.out.println ("\t Grade \t Mark Range");
if (grade=='A')
{
System.out.println ("\t A \t 80 - 100");
}
else if (grade=='B')
{
System.out.println ("\t B \t 70 - 79");
}
else if (grade=='C')
{
System.out.println ("\t C \t 55 -69");
}else if (grade=='D'){
System.out.println ("\t D \t 45 - 54");
}
else
{
System.out.println ("Wrong character inputted!!!");
}
}
}