Java class example : Using classes in java


The objects are data and methods bundled together into a single logical software unit. The next question that arises in our mind is how objects get into our software system and how objects get created. At this point we get introduced to the most fundamental structure in object oriented programming, the classes.

A java class is a template or prototype which defines the outline of state and behavior for all the objects belonging to that class. An instance of a class is called as object and all the objects of a class will have common state and behavior.

A java class is to an object is like a blue print is to a house. Any number of houses can be constructed from a single blue print. In a similar way many objects can be created from a single class. A class outlines the properties of an object. Objects created from the same class show similar characteristics.

The attributes and actions can be assigned only after an object is created. When an object is created then the actual instance of the entity come into existence. Hence, a java class can be called as a conceptual model of an entity which is universal and non-specific.

Java class syntax:

class identifier
{
class body
}

Here identifier specifies the name of the class. Class body consists of data members and method definitions. Curly braces surround the class body.

A class is static, whereas the data contained in an object can be dynamic. In a class, attributes are set throughout the execution of the program.

Example:

class ExampleClass
{
//Data member declaration
char ch;
int num;
double decimalnum;

void exampleMethod1()
{
System.out.println(“Hello Java”);
}
void exampleMethod2()
{
System.out.println(“Javaeschool.com”);
}
}

In the above example, ExampleClass is the class name. The class body contains 3 data members and 2 member method implementations.

Java loops : Types of loops in java


Very often we need to execute a group of statements repeatedly. Java loop statements are used to repeat the java statements number of times. Each repeated execution of statements is called as iteration. During each iteration, the value of some variable is altered and some condition is tested. This allows us to come out of the loop ultimately. If proper conditions and variable alteration is not used, you may end up in an infinite loop.

There are three types of java loops,
  1. for loop
  2. while loop
  3. do-while loop
  4. for-each

Along with loops you can use the java break and java continue statement.

Java break statement is used the break the execution of a java loop. The java break statement causes the control to pass out of the loop. Control will be transfer to the first statement after the closing curly brackets of the loop.

Java continue statement is used to skip a single iteration. When a continue statement is executed, it causes the flow of the control to the next iteration of the loop, skipping the current execution.

We can also use the nested loops and also can use the hybrid loop means like we can have a “while loop” inside “for loop” and so on.

Further to “for loop”, a new construct called for-each loop is available. This enhanced construct allows user to automatically work through the elements of a collection or an array.

Also see java for loop example, java for-each loop example, java while loop example and java do-while loop example.

Java switch example : Using switch statement in java


Switch branching is used to conditionally switch among multiple programs segments. The switch statement can be used as an alternative for if-else-if statement. It is used in situations where an expression being evaluated can have any one of multiple values. The use of switch statement improves the performance. We can have one switch case in another switch case known as nested switch statement.

Syntax:
switch (expression)
{
case constant1 : set of statements1;
break;
case constant2 : set of statements2;
break;
………
case constant(n) : set of statements(n);
break;
}

The expression is evaluated first. If the expression result matches any case constant, then set of statements belonging to that constant are executed.

A simple java switch example.

public class SwitchCaseExample {
public static void main(String args[])
{
System.out.println("Enter an alphabet : ");
char ch=(char)-1;
try
{
ch=(char)System.in.read();
}
catch(Exception e)
{
e.getStackTrace();
}
switch(ch)
{
case 'a' :System.out.println("You typed 'a'.");
break;
case 'b' :System.out.println("You typed 'b'.");
break;
case 'c' :System.out.println("You typed 'c'.");
break;
case 'd' :System.out.println("You typed 'd'.");
break;
default :System.out.println("Type alphabet between a-d");
break;
}
}
}

In the above example we have used a default case, the default case will execute if the switch cannot find any matching case constant.

Features of switch statement:

  1. The switch statement id different from the “if” statement. The “if” statement can test for any type of Boolean expression, whereas the switch statement only test for equality.
  2. No two case constants in the same switch can have same value, but in the nested switch the inner switch can have case constant similar to the outer switch.
  3. A switch statement is more efficient and easy to understand then a nested “if” statement.

Java if example : Using if statement in java


“if” statement, is the simplest form of conditional branching in java. The” if” statement consist of a condition and block of statements. If the condition returns true the statement block is executed or if condition return false the statement block is ignored.

Syntax :
If(condition)
{
Statement 1;
Statement 2;
……….
}

Example :
public class SimpleIfExample
{
public static void main(String args[])
{
char ch=(char)-1;
System.out.println("Enter a alphabet : ");
try
{
ch=(char)System.in.read();
}
catch(Exception e)
{
e.getStackTrace();
}
if(ch=='a')
{
System.out.println("Hello World");
}
System.out.println("Learn java with examples.");
}
}
When you will run the above program you will be prompt to enter an alphabet.

Enter an alphabet :

At this point if you type “a” you will get the following output,

Hello World
Learn java with examples.

Instead of typing “a”, if you type any other character you will get the following output,

Learn java with examples.

The java if statement is one of most commonly used type of conditional branching.

Java type casting example : Using type casting in java


The process of converting one data type to another is called as type casting. Type casting becomes unavoidable on many occasions. Type casting is done to take advantage of certain features of type hierarchies.

Type casting is of types,
  1. Implicit type casting
  2. Explicit type casting

The term used for implicit type casting is coercion. The most common form of explicit type casting is called as casting. Explicit type casting can also be achieved with independently defined conversion routines for example overloading object constructor.

Implicit type casting

Implicit type casting, also known as coercion is an automatic type casting by the compiler. Some languages allow, or even require, compliers to provide implicit type casting. In a mixed-type expression, the program will execute properly if the data of one or more subtype can be converted to a super type.

Example:
short num1=1000;
int num2;
num2=num1;

In the above example, the value of “a” i.e. short has been promoted to type int without using any type casting operator. This is called as standard type casting. Standard type casting affects fundamental data types. When working with floating point numbers, sometime these conversions may imply a loss of precision, where the complier will show a warning. This can be avoided with an explicit type casting.

Explicit type casting

A lot of conversions, especially those that imply a different interpretation of the value, require explicit type casting.

Example:
short num1=1000;
int num2;
num2= (int) num1; //cast notation
num2=int(a); //functional notation

Explicit conversion of several kinds like checked, unchecked or bit pattern.

Java data types example : Using data types in java


Java has eight basic data types to store numeric, floating point numbers, characters and Boolean values. These data types are often called as primitive data types. These data types are built in parts of java programming language. This makes them more efficient and useful.

No matter what operating system or platform you are using, these data types have same characteristics and size. This is one of the reasons that makes java platform independent.

Integer data types

Integer data types are of four types, short, byte, long and int. They are whole-valued signed numbers.

Byte: It is used to store small amount of data. This is a 8bit type and ranges from -128 to 127. It is useful when working with stream of data from a network or file. Byte is also useful when working with raw binary data that may not be compatible with other data types in java.

Short: Short is least used data type. It is a signed 16 bit type and ranges from -32,768 to 32,767. Short data type is more compatible with 16-bit computers.

Int: Int is most commonly used data type. It is a signed 32 bit and ranges from -2,147,483,648 to 2,147,483,647. The int data type is more efficient and versatile.

Long: long is a signed 64-bit type and ranges from -9,223,372,036,854 to 9,223,372,036,854,775,807. It is used when an int type is not large enough to hold the given value.

Example :
int num1;
byte num2;
short num3;
long num4;

Floating point data types

Floating point data types are used to present numbers with a fractional part. There are 2 types of floating point data types.

  1. Float
  2. Double

32 bit floating point numbers are called float numbers. 64 bit floating point numbers are called double number.

Example :
float weight;
double atomic_weight;

Boolean data type

A Boolean data type is used to store values, which is either “true” of “false”.

Example :
boolean isalive;

Character data type

Character data type is used to store a single Unicode character. Unicode code character sets are 16 bit values. Therefore the space required to store a single character is 16 bit.

Example :
char ch;

Java comments example : Using comments in java


Java comments are used in a program for documentation purpose. Comments give clarity to the source code and make it more understandable. Java comments are not programming statements are ignored by the java compiler. This is to help the programmers or users to communicate and understand the program.

Java supports the following type of comments,
  1. /*Some comment*/
  2. //Some other comment
  3. /** Documentation comment */


/*Some comment*/

This type of comment is used to place more than one sentence of statements in comment. Everything between the two delimiters is ignored by the compiler.

//Some comment

This is a single line comment. Any statement of sentence inline with “//” is considered as comment by the complier.

/**Documentations comment*/

This is used to indicate some special documentation comments. These comments are used to document the working of a class and its member functions works.

Java operator : Using operators in java


In any programming language, real life scenario involves the manipulation of variables. Operators specify the evaluation to be carried on data objects. Operators combine simple value or expression into complex new expression that return values.

Type of java operator,

  1. Arithmetic operators
  2. Relational operators
  3. Logical operators
  4. Bitwise operators
  5. instanceOf operator
  6. Conditional operators

Arithmetic Operators

Arithmetic operators are used in mathematical expressions. Operands of arithmetic operators must be of numeric type. While using arithmetic operators, Boolean operands cannot be used. Character operands are allowed.

Relational Operators

Relational operators are used to test the relation between to operands. Expressions using relation operators always return Boolean values, i.e. either true or false.

Logical Operators

Logical operator’s works with Boolean operands.

Assignment operator

Assignment operator is used to assign values. The assignment operator is a single equal sign “-” and assigns a value to a variable. Assigning values to more than one variable can be done. It can be also said as the chain of assignments.

Bitwise Operators

Bitwise operators are used to manipulate individual bits in an integral primitive data type. Bitwise operators act upon the individual bits of their operands. Bitwise operators perform Boolean algebra on the corresponding bits in the two arguments to produce result. When bitwise operators are used with numbers the “&” operation performs the bitwise “AND” function, and the “|” operations performs the bitwise “OR” function on each pair of bits.

instanceOf operator

The “instanceOf” operator is used for object reference variables only. It can also be used to check weather an object is of a particular type.

Example:
Scanner user_input=new Scanner(System.in);
Boolean value=input_user instanceOf Scanner;
System.out.println(value);

Conditional Operator

Conditional operator is used to evaluate Boolean expressions. The ternary operator is a conditional operator. Conditional operator can replace certain type of if-else statements.

Syntax:
expression1 ? expression2 : expression3

The “expression1” can be any expression that evaluates to a Boolean value. If it returns a true value “expression2” is evaluated and if it returns a false value “expression3” is evaluated. We can even nest the conditional operators.

Java literals : Using literals in java


Java literals are the elements that are used in an invariant manner in a program. A literal signifies a fixed value and is represented directly in the code without requiring computation.

Example:
int num1=90;
float num2=35.7F;
char ch=’s’;

Literals are also called constants. Literals can be numbers, characters or string. A literal is used whenever a value of its type is allowed.

Types of java literals:
  1. Integer literal
  2. Floating point literal
  3. Boolean literal
  4. Character literal
  5. Null literal
  6. String literal

Integer Literal
An int value is represented using an integer literal. It is a 32-bit integer value in java. Integers are most commonly used type in any program. Any whole number value is an integer literal.

Integer literals can be expressed as,
  1. Decimal value expressed in base 10. Decimal numbers appear as ordinary number in a program (example: int x=173;)
  2. Octal value expressed in base 8. Octal numbers appears with a leading 0 (example: int x=0173;).
  3. Hexadecimal value expressed in base 16. Hexadecimal numbers appears with a leading 0x or 0X in a program (example: int x=0x7B; or int x=0X7B)

Floating point literal
Floating point literals represent decimal numbers with a fractional part like “234.98”.

Floating point literals can be expressed as,
  1. A number with decimal point.
  2. Exponent is indicated by an “E” or “e” followed by a decimal number. The number can be negative or positive.
  3. Numbers with suffix “D”, “d”, “F” or “f”.

A float literal is represented by “F” or “f” appended to the value and a double literal is represented by “D” or “d” appended to the value.

Boolean literal
Boolean literals are simple and have only two possible values i.e. “true” or “false”. A Boolean value does not convert into any decimal representation. A “true” Boolean literal is not equal to 1 on java and a “false” Boolean literal is not equal to 0. Only variables declared as boolean can hold boolean values.


Character literal
Character literals are enclosed in single quotes. We can enter any of the visible ASCII character directly in the single quotes. Single characters that cannot be directly entered are hyphen (-) and backslash (\).

Null literal
When we create an object, a certain amount of memory space is allocated for that object. The starting address of this memory is stored in an object, that is, a reference value. However, sometimes it is not desirable for the reference variable to refer that object. In such a case, a null value is assigned to the reference variable.
Example: obj=null;

String literal
A string literal can be defined as a sequence of characters enclosed in double quotes. The characters can be printable or non-printable. However, escape sequence is used to represent backslash, double quotes and non-printable characters.

Java keywords : List of keywords in java


Java keywords are reserved words and have special meaning for the java compiler. These java keywords cannot be used as identifiers in a program. There is a rich list of java keywords.

List of java keywords,
  1. boolean
  2. void
  3. int
  4. threadsafe
  5. super
  6. case
  7. continue
  8. throw
  9. finally
  10. private
  11. volatile
  12. native
  13. package
  14. future
  15. operation
  16. char
  17. true
  18. long
  19. null
  20. if
  21. break
  22. do
  23. synchronized
  24. static
  25. protected
  26. class
  27. extends
  28. import
  29. generic
  30. outer
  31. byte
  32. false
  33. double
  34. new
  35. else
  36. default
  37. while
  38. try
  39. abstract
  40. public
  41. instanceof
  42. interface
  43. cast
  44. goto
  45. rest
  46. float
  47. short
  48. byvalue
  49. this
  50. switch
  51. for
  52. return
  53. catch
  54. final
  55. transient
  56. throws
  57. implements
  58. const
  59. inner
  60. var

Some of the keywords in above list are reserved for future use.

Java identifiers : Using identifiers in java


Identifiers are the names that are provided by programmer. These names can be assigned to any variables, methods, classes, interfaces, etc., java identifiers helps compilers to identify them. Java identifiers can be of any length up to 255 characters. Java identifiers can start with a letter or an undersigned character “_” or a dollar sign “$”. Subsequent characters can be alphabets (both capital and small letters) and numbers from 0 to 9. Space characters or any other special character found on keyboard is not allowed. The only other limitation is that java keywords cannot be used as java identifiers.

Examples of valid identifiers,
  1. HelloWorld
  2. Hello_World
  3. $HelloWorld
  4. HelloWorld
  5. HELLOWORLD

Examples of invalid identifiers,
  1. Hello World
  2. HelloWorld #
  3. short
  4. Hello-World

In the above examples, first have space and space is not allowed in java identifiers. In second “#” and space is present which again not allowed. The third example is invalid as “short” is a java keyword. The last example has “-” symbol and it is also not supported in java identifiers.

The naming conventions above are imposed on the programmer by the compiler. In addition to the above naming conventions, there are certain types of rules that are widely accepted and followed by the programmer community.

It is widely accepted convention to start a class name with capital letter.

Using naming conventions in a java program is a good habit as it makes your program easily readable and understandable to other programmers.