A JAVA PROGRAM TO CHECK THE GIVEN STRING IS PALINDROME OR NOT .

Tech Jitendra provides,

We are going to discuss about –

A JAVA PROGRAM TO CHECK WHETHER A STRING IS PALINDROME OR NOT .

Java Program to Check whether a String is a Palindrome

This is a Java Program to Check whether a String is a Palindrome.

Enter any string as input. Now we use for loops and if-else conditions along with equalsIgnoreCase() method to conclude whether the entered string is palindrome or not.

Here is the source code of the Java Program to Check whether a String is a Palindrome. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.advertisement

  1. public class Palindrome
  2. {
  3. public static void main(String args[])
  4. {
  5. String a, b = “”;
  6. Scanner s = new Scanner(System.in);
  7. System.out.print(“Enter the string you want to check:”);
  8. a = s.nextLine();
  9. int n = a.length();
  10. for(int i = n – 1; i >= 0; i–)
  11. {
  12. b = b + a.charAt(i);
  13. }
  14. if(a.equalsIgnoreCase(b))
  15. {
  16. System.out.println(“The string is palindrome.”);
  17. }
  18. else
  19. {
  20. System.out.println(“The string is not palindrome.”);
  21. }
  22. }
  23. }

Output:$ javac Palindrome.java $ java Palindrome   Enter the string you want to check:NeveroddorEVen The string is palindrome.

Thinking you

Tech Jitendra

JAVA ITERATOR

Java Iterator – Iterator in Java

In this post we are going to discuss about some basics of Java Enumeration and in-depth discussion about Java Iterator. As Java Enumeration interface is deprecated, it is not recommended to use this in our applications.

Tech Jitendra Provides,

In this post we are going to this discuss the following concepts about Java’s Iterator.

Java Four Cursors

First of all, I would like to define what is a Java Cursor? A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one.

Java supports the following four different cursors.

  • Enumeration
  • Iterator
  • ListIterator
  • Spliterator

Each Java cursor have some advantages and drawbacks. We will discuss some basics about Enumeration and full details about Iterator in this posts. We will discuss about ListIterator and Spliterator in my coming posts.

Java Enumeration Limitations

Java Enumeration is available since Java 1.0 and it has many limitations and not advisable to use in new projects.

  • It is available since Java 1.0 and legacy interface.
  • It is useful only for Collection Legacy classes.
  • Compare to other Cursors, it has very lengthy method names: hasMoreElements() and nextElement().
  • In CRUD Operations, it supports only READ operation. Does not support CREATE, UPDATE and DELETE operations.
  • It supports only Forward Direction iteration. That’s why it is also know as Uni-Directional Cursor.
  • It is not recommended to use it in new code base or projects.

NOTE:- What is CRUD operations in Collection API?

  • CREATE: Adding new elements to Collection object.
  • READ: Retrieving elements from Collection object.
  • UPDATE: Updating or setting existing elements in Collection object.
  • DELETE: Removing elements from Collection object.

To overcome all these issues, Java come-up with new Cursors: Iterator and ListIterator in Java 1.2. It has introduced a new type of Cursor: Spliterator in Java 1.8.

We will discuss about Iterator with some suitable examples in this post.

Java Iterator

In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a collection of objects.

  • It is used to traverse a collection object elements one by one.
  • It is available since Java 1.2 Collection Framework.
  • It is applicable for all Collection classes. So it is also known as Universal Java Cursor.
  • It supports both READ and REMOVE Operations.
  • Compare to Enumeration interface, Iterator method names are simple and easy to use.

Java Iterator Class Diagram

As shown in the Class Diagram below, Java Iterator has four methods. We are already familiar with first four methods. Oracle Corp has added fourth method to this interface in Java SE 8 release.

Java Iterator Methods

In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples in the coming section.

  • boolean hasNext():Returns true if the iteration has more elements.
  • E next(): Returns the next element in the iteration.
  • default void remove(): Removes from the underlying collection the last element returned by this iterator.
  • default void forEachRemaining(Consumer action): Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Java Iterator Basic Example

First discuss about how to get an Iterator object from a Collection. Each and every Collection class has the following iterator() method to iterate it’s elements. Iterator<E> iterator()

It returns an iterator over the elements available in the given Collection object.

Example-1:- import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class ExternalIteratorDemo { public static void main(String[] args) { List<String> names = newLinkedList<>(); names.add("Rams"); names.add("Posa"); names.add("Chinni"); // Getting Iterator Iterator<String> namesIterator = names.iterator(); // Traversing elements while(namesIterator.hasNext()){ System.out.println(namesIterator.next()); } } }

Example-2:- import java.util.LinkedList; import java.util.List; public class InternalIteratorDemo { public static void main(String[] args) { List<String> names = newLinkedList<>(); names.add("Rams"); names.add("Posa"); names.add("Chinni"); for(String name: names){ System.out.println(name); } } }

If we observe the two above examples, both examples are doing the same thing. In Example-1, we have created Iterator object externally and retrieved List object elements one by one. In Example-2, we have Not created Iterator object externally. We are using Enhanced for loop to retrieve the List object elements one by one.

Enhanced for loop uses Iterator object internally and do the same thing like External Iterator example. So both examples gives the same output as shown below.

Output:- Rams Posa Chinni

Develop Custom Class Iterator

In previous section, we have discussed about how Collection API has implemented the iterator() method to iterate it’s elements with or without using Enhanced For Loop.

In this section, we will discuss about how to provide similar kind of functionality for a User-Defined or Custom classes. We should follow these instructions to provide this functionality:

  • Define Custom class.
  • Define Collection class to this Custom class.
  • This Collection class should implement Iterable interface with Custom class as Type parameter.
  • This Collection class should provide implementation of Iterable interface method: iterator().

If we implement these instructions to our Custom class, then it’s ready to use Enhanced For Loop or external Iterator object to iterate it’s elements.

Let us develop a simple example to understand these instructions clearly.

Example:- public class Employee { private int empid; private String ename; private String designation; private double salary; public Employee(int empid,String ename,String designation,doublesalary){ this.empid = empid; this.ename = ename; this.designation = designation; this.salary = salary; } public int getEmpid() { return empid; } public String getEname() { return ename; } public String getDesignation() { return designation; } public double getSalary() { return salary; } @Override public String toString(){ return empid + "\t" + ename + "\t"+ designation + "\t" + salary; } } import java.util.*; public class Employees implementsIterable{ private List<Employee> emps = null; public Employees(){ emps = new ArrayList<&glt;(); emps.add(newEmployee(1001,"Rams","Lead", 250000L)); emps.add(newEmployee(1002,"Posa","Dev", 150000L)); emps.add(newEmployee(1003,"Chinni","QA", 150000L)); } @Override public Iterator<Employee> iterator() { return emps.iterator(); } } public class EmployeesTester { public static void main(String[] args) { Employees emps = new Employees(); for(Employee emp : emps){ System.out.println(emp); } } }

Output:- 1001 Rams Lead 250000.0 1002 Posa Dev 150000.0 1003 Chinni QA 150000.0

Thinking you

Tech Jitendra

Java DataInputStream Class

Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.


Java DataInputStream class declaration

Let’s see the declaration for java.io.DataInputStream class:

  1. public class DataInputStream extends FilterInputStream implements DataInput  

Java DataInputStream class Methods

MethodDescriptionint read(byte[] b)It is used to read the number of bytes from the input stream.int read(byte[] b, int off, int len)It is used to read len bytes of data from the input stream.int readInt()It is used to read input bytes and return an int value.byte readByte()It is used to read and return the one input byte.char readChar()It is used to read two input bytes and returns a char value.double readDouble()It is used to read eight input bytes and returns a double value.boolean readBoolean()It is used to read one input byte and return true if byte is non zero, false if byte is zero.int skipBytes(int x)It is used to skip over x bytes of data from the input stream.String readUTF()It is used to read a string that has been encoded using the UTF-8 format.void readFully(byte[] b)It is used to read bytes from the input stream and store them into the buffer array.void readFully(byte[] b, int off, int len)It is used to read len bytes from the input stream.

Example of DataInputStream class

In this example, we are reading the data from the file testout.txt file.

  1. package com.javatpoint;  
  2. import java.io.*;    
  3. public class DataStreamExample {  
  4.   public static void main(String[] args) throws IOException {  
  5.     InputStream input = new FileInputStream(“D:\\testout.txt”);  
  6.     DataInputStream inst = new DataInputStream(input);  
  7.     int count = input.available();  
  8.     byte[] ary = new byte[count];  
  9.     inst.read(ary);  
  10.     for (byte bt : ary) {  
  11.       char k = (char) bt;  
  12.       System.out.print(k+”-“);  
  13.     }  
  14.   }  
  15. }  

Here, we are assuming that you have following data in “testout.txt” file:JAVA

Output:J-A-V-A

Thanking you

Tech Jitendra

Decision Making in Java (if, if-else, switch, break, continue, jump)

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program based on certain conditions. These  are used to cause the flow of execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:if(condition) { // Statements to execute if // condition is true } Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
    If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,if(condition) statement1; statement2; // Here if the condition is true, if block // will consider only statement1 to be inside // its block.Flow chart:

    Example:// Java program to illustrate If statement class IfDemo { public static void main(String args[]) { int i = 10;   if (i > 15) System.out.println("10 is less than 15");   // This statement will be executed // as if considers one statement by default System.out.println("I am Not in if"); } } Output:I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }
    Example:// Java program to illustrate if-else statement class IfElseDemo { public static void main(String args[]) { int i = 10;   if (i < 15) System.out.println("i is smaller than 15"); else System.out.println("i is greater than 15"); } } Output:i is smaller than 15
  • nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:if (condition1) { // Executes when condition1 is true if (condition2) { // Executes when condition2 is true } }
    Example:// Java program to illustrate nested-if statement class NestedIfDemo { public static void main(String args[]) { int i = 10;   if (i == 10) { // First if statement if (i < 15) System.out.println("i is smaller than 15");   // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) System.out.println("i is smaller than 12 too"); else System.out.println("i is greater than 15"); } } } Output:i is smaller than 15 i is smaller than 12 too
  • if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.if (condition) statement; else if (condition) statement; . . else statement;
    Example:// Java program to illustrate if-else-if ladder class ifelseifDemo { public static void main(String args[]) { int i = 20;   if (i == 10) System.out.println("i is 10"); else if (i == 15) System.out.println("i is 15"); else if (i == 20) System.out.println("i is 20"); else System.out.println("i is not present"); } } Output:i is 20
  • switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
    Syntax:switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; }
    • Expression can be of type byte, short, int char or an enumeration. Beginning with JDK7, expression can also be of type String.
    • Dulplicate case values are not allowed.
    • The default statement is optional.
    • The break statement is used inside the switch to terminate a statement sequence.
    • The break statement is optional. If omitted, execution will continue on into the next case.

    Example:// Java program to illustrate switch-case class SwitchCaseDemo { public static void main(String args[]) { int i = 9; switch (i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 2."); } } } Output:i is greater than 2.
  • jump: Java supports three jump statement: break, continue and return. These three statements transfer control to other part of the program.
    1. Break: In Java, break is majorly used for:
      • Terminate a sequence in a switch statement (discussed above).
      • To exit a loop.
      • Used as a “civilized” form of goto.
      Using break to exit a LoopUsing break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.
      Note: Break, when used inside a set of nested loops, will only break out of the innermost loop.

      Example:// Java program to illustrate using // break to exit a loop class BreakLoopDemo { public static void main(String args[]) { // Initially loop is set to run from 0-9 for (int i = 0; i < 10; i++) { // terminate loop when i is 5. if (i == 5) break;   System.out.println("i: " + i); } System.out.println("Loop complete."); } } Output:i: 0 i: 1 i: 2 i: 3 i: 4 Loop complete. Using break as a Form of GotoJava does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. Java uses label. A Label is use to identifies a block of code.
      Syntax:label: { statement1; statement2; statement3; . . }Now, break statement can be use to jump out of target block.
      Note: You cannot break to any label which is not defined for an enclosing block.
      Syntax:break label;Example:// Java program to illustrate using break with goto class BreakLabelDemo { public static void main(String args[]) { boolean t = true;   // label first first: { // Illegal statement here as label second is not // introduced yet break second; second: { third: { // Before break System.out.println("Before the break statement");   // break will take the control out of // second label if (t) break second; System.out.println("This won't execute."); } System.out.println("This won't execute."); }   // Third block System.out.println("This is after second block."); } } }

Decision Making in Java

Tech Jitendra Provides,

Discussing about Dicision making in Java .

Decision Making in Java (if, if-else, switch, break, continue, jump)

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program based on certain conditions. These  are used to cause the flow of execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:if(condition) { // Statements to execute if // condition is true } Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
    If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,if(condition) statement1; statement2; // Here if the condition is true, if block // will consider only statement1 to be inside // its block.Flow chart:

    Example:// Java program to illustrate If statement class IfDemo { public static void main(String args[]) { int i = 10;   if (i > 15) System.out.println("10 is less than 15");   // This statement will be executed // as if considers one statement by default System.out.println("I am Not in if"); } } Output:I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }
    Example:// Java program to illustrate if-else statement class IfElseDemo { public static void main(String args[]) { int i = 10;   if (i < 15) System.out.println("i is smaller than 15"); else System.out.println("i is greater than 15"); } } Output:i is smaller than 15
  • nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:if (condition1) { // Executes when condition1 is true if (condition2) { // Executes when condition2 is true } }
    Example:// Java program to illustrate nested-if statement class NestedIfDemo { public static void main(String args[]) { int i = 10;   if (i == 10) { // First if statement if (i < 15) System.out.println("i is smaller than 15");   // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) System.out.println("i is smaller than 12 too"); else System.out.println("i is greater than 15"); } } } Output:i is smaller than 15 i is smaller than 12 too
  • if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.if (condition) statement; else if (condition) statement; . . else statement;
    Example:// Java program to illustrate if-else-if ladder class ifelseifDemo { public static void main(String args[]) { int i = 20;   if (i == 10) System.out.println("i is 10"); else if (i == 15) System.out.println("i is 15"); else if (i == 20) System.out.println("i is 20"); else System.out.println("i is not present"); } } Output:i is 20
  • switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
    Syntax:switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; }
    • Expression can be of type byte, short, int char or an enumeration. Beginning with JDK7, expression can also be of type String.
    • Dulplicate case values are not allowed.
    • The default statement is optional.
    • The break statement is used inside the switch to terminate a statement sequence.
    • The break statement is optional. If omitted, execution will continue on into the next case.

    Example:// Java program to illustrate switch-case class SwitchCaseDemo { public static void main(String args[]) { int i = 9; switch (i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 2."); } } } Output:i is greater than 2.
  • jump: Java supports three jump statement: break, continue and return. These three statements transfer control to other part of the program.
    1. Break: In Java, break is majorly used for:
      • Terminate a sequence in a switch statement (discussed above).
      • To exit a loop.
      • Used as a “civilized” form of goto.
      Using break to exit a LoopUsing break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop.
      Note: Break, when used inside a set of nested loops, will only break out of the innermost loop.

      Example:// Java program to illustrate using // break to exit a loop class BreakLoopDemo { public static void main(String args[]) { // Initially loop is set to run from 0-9 for (int i = 0; i < 10; i++) { // terminate loop when i is 5. if (i == 5) break;   System.out.println("i: " + i); } System.out.println("Loop complete."); } } Output:i: 0 i: 1 i: 2 i: 3 i: 4 Loop complete. Using break as a Form of GotoJava does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. Java uses label. A Label is use to identifies a block of code.
      Syntax:label: { statement1; statement2; statement3; . . }Now, break statement can be use to jump out of target block.
      Note: You cannot break to any label which is not defined for an enclosing block.
      Syntax:break label;Example:// Java program to illustrate using break with goto class BreakLabelDemo { public static void main(String args[]) { boolean t = true;   // label first first: { // Illegal statement here as label second is not // introduced yet break second; second: { third: { // Before break System.out.println("Before the break statement");   // break will take the control out of // second label if (t) break second; System.out.println("This won't execute."); } System.out.println("This won't execute."); }   // Third block System.out.println("This is after second block."); } } }

Thnaking you

Tech Jitendra

OPERATORS IN JAVA

Tech Jitendra Provides

We are going to discussing about Operators in Java

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

  • Unary Operator,
  • Arithmetic Operator,
  • Shift Operator,
  • Relational Operator,
  • Bitwise Operator,
  • Logical Operator,
  • Ternary Operator and
  • Assignment Operator.

Java Operator Precedence

Operator TypeCategoryPrecedenceUnarypostfixexpr++ expr--prefix++expr --expr +expr -expr ~ !Arithmeticmultiplicative* / %additive+ -Shiftshift<< >> >>>Relationalcomparison< > <= >= instanceofequality== !=Bitwisebitwise AND&bitwise exclusive OR^bitwise inclusive OR|Logicallogical AND&&logical OR||Ternaryternary? :Assignmentassignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

  • incrementing/decrementing a value by one
  • negating an expression
  • inverting the value of a boolean

Java Unary Operator Example: ++ and —

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int x=10;  
  4. System.out.println(x++);//10 (11)  
  5. System.out.println(++x);//12  
  6. System.out.println(x–);//12 (11)  
  7. System.out.println(–x);//10  
  8. }}  

Output:10 12 12 10

Java Unary Operator Example 2: ++ and —

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=10;  
  5. System.out.println(a++ + ++a);//10+12=22  
  6. System.out.println(b++ + b++);//10+11=21  
  7.   
  8. }}  

Output:22 21

Java Unary Operator Example: ~ and !

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=-10;  
  5. boolean c=true;  
  6. boolean d=false;  
  7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
  8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
  9. System.out.println(!c);//false (opposite of boolean value)  
  10. System.out.println(!d);//true  
  11. }}  

Output:-11 9 false true

Java Arithmetic Operators

Java arithmatic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=5;  
  5. System.out.println(a+b);//15  
  6. System.out.println(a-b);//5  
  7. System.out.println(a*b);//50  
  8. System.out.println(a/b);//2  
  9. System.out.println(a%b);//0  
  10. }}  

Output:15 5 50 2 0

Java Arithmetic Operator Example: Expression

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. System.out.println(10*10/5+3-1*4/2);  
  4. }}  

Output:21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

Java Left Shift Operator Example

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. System.out.println(10<<2);//10*2^2=10*4=40  
  4. System.out.println(10<<3);//10*2^3=10*8=80  
  5. System.out.println(20<<2);//20*2^2=20*4=80  
  6. System.out.println(15<<4);//15*2^4=15*16=240  
  7. }}  

Output:40 80 80 240

Java Right Shift Operator

The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right operand.

Java Right Shift Operator Example

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. System.out.println(10>>2);//10/2^2=10/4=2  
  4. System.out.println(20>>2);//20/2^2=20/4=5  
  5. System.out.println(20>>3);//20/2^3=20/8=2  
  6. }}  

Output:2 5 2

Java Shift Operator Example: >> vs >>>

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3.     //For positive number, >> and >>> works same  
  4.     System.out.println(20>>2);  
  5.     System.out.println(20>>>2);  
  6.     //For negative number, >>> changes parity bit (MSB) to 0  
  7.     System.out.println(-20>>2);  
  8.     System.out.println(-20>>>2);  
  9. }}  

Output:5 5 -5 1073741819

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn’t check second condition if first condition is false. It checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=5;  
  5. int c=20;  
  6. System.out.println(a<b&&a<c);//false && true = false  
  7. System.out.println(a<b&a<c);//false & true = false  
  8. }}  

Output:false false

Java AND Operator Example: Logical && vs Bitwise &

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=5;  
  5. int c=20;  
  6. System.out.println(a<b&&a++<c);//false && true = false  
  7. System.out.println(a);//10 because second condition is not checked  
  8. System.out.println(a<b&a++<c);//false && true = false  
  9. System.out.println(a);//11 because second condition is checked  
  10. }}  

Output:false 10 false 11

Thanking you

Tech Jitendra

DATA TYPES IN JAVA

Tech Jitendra provides ,

We are going to discuss about Data types in Java .

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

  1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
  2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to declare variable’s type and name.

There are 8 types of primitive data types:

  • boolean data type
  • byte data type
  • char data type
  • short data type
  • int data type
  • long data type
  • float data type
  • double data type
Java Data Types

Data TypeDefault ValueDefault sizebooleanfalse1 bitchar’\u0000’2 bytebyte01 byteshort02 byteint04 bytelong0L8 bytefloat0.0f4 bytedouble0.0d8 byte

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its “size” can’t be defined precisely.

Example: Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two’s complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of “int” data type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two’s complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Example: int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two’s complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is – 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int.

Example: long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.

Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = ‘A’

Thanking you

Tech Jitendra

Java First Program

Beginning Java programming with Hello World Example

Tech Jitendra provides ,

In this article we are going to discuss on java first program.

The process of Java programming can be simplified in three steps:

  • Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
  • Compile it by typing “javac HelloWorld.java” in the terminal window.
  • Execute (or run) it by typing “java HelloWorld” in the terminal window.

Recommended:

Below given  program is the simplest program of Java printing “Hello World” to the screen. Let us try to understand every bit of code step by step./* This is a simple Java program. FileName : "HelloWorld.java". */classHelloWorld { // Your program begins with a call to main(). // Prints "Hello, World" to the terminal window. publicstaticvoidmain(String args[]) { System.out.println("Hello, World"); } }

Output:Hello, World

The “Hello World!” program consists of three primary components: the HelloWorld class definition, the mainmethod and source code comments. Following explanation will provide you with a basic understanding of the code:

  1. Class definition:This line uses the keyword class to declare that a new class is being defined.class HelloWorld HelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace  {  and the closing curly brace  } .
  2. main method: In Java programming language, every application must contain a main method whose signature is:public static void main(String[] args) public: So that JVM can execute the method from anywhere. static: Main method is to be called without object. The modifiers public and static can be written in either order. void: The main method doesn’t return anything. main(): Name configured in the JVM. String[]: The main method accepts a single argument: an array of elements of type String.Like in C/C++, main method is the entry point for your application and will subsequently invoke all the other methods required by your program.
  3. The next line of code is shown here. Notice that it occurs inside main( ).System.out.println(“Hello, World”); This line outputs the string “Hello, World” followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. System is a predefined class that provides access to the system, and outis the variable of type output stream that is connected to the console.
  4. Comments: They can either be multi-line or single line comments./* This is a simple Java program. Call this file “HelloWorld.java”. */ This is a multiline comment. This type of comment must begin with /* and end with */. For single line you may directly use // as in C/C++.

Important Points :

  • The name of the class defined by the program is HelloWorld, which is same as name of file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a class and there is at most one public class which contain main() method.
  • By convention, the name of the main class(class which contain main method) should match the name of the file that holds the program.

Compiling the program :

Java : hello word .

Thanking you

Tech Jitendra

JAVA ENVIRONMENT

Java Runtime Environment (JRE)

Tech Jitendra provides,

Definition – What does Java Runtime Environment (JRE) mean?

The Java Runtime Environment (JRE) is a set of software tools for development of Java applications. It combines the Java.

Java Virtual Machine (JVM), platform core classes and supporting libraries.

JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle Corporation. 

Also known as Java runtime.

Tech Jitendra explains Java Runtime Environment (JRE)

JRE consists of the following components:

  • Deployment technologies, including deployment, Java Web Start and Java Plug-in.
  • User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input methods.
  • Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.
  • Other base libraries, including international support, input/output (I/O), extension mechanism, Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization and Java for XML Processing (XML JAXP).
  • Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref Objects and Regular Expressions.
  • Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.


JRE 1.0 has evolved with a variety of class and package additions to the core libraries, and it has grown from a few hundred classes to several thousand in Java 2 Platform, Standard Edition (J2SE). Entirely new APIs have been introduced, and many of the original version 1.0 APIs have been deprecated. There has been a significant degree of criticism because of these massive additions.Share this:  

Thanks

Tech Jitendra

Design a site like this with WordPress.com
Get started