Java - Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.

Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

Java - Overview

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

Java is 

Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.

Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.

Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.

Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.

Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.

High Performance − With the use of Just-In-Time compilers, Java enables high performance.

Distributed − Java is designed for the distributed environment of the internet.

Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

History of Java

James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.

Java String - Programming Examples

1. How to compare two strings in Java ?

2. How to search the last position of a substring ?

3. How to remove a particular character from a string ?

4. How to replace a substring inside a string by another one ?

5. How to reverse a String?

6. How to search a word inside a string ?

7. How to convert a string totally into upper case?

8. How to optimize string concatenation ?

How to optimize string concatenation ?

Following example shows performance of concatenation by using "+" operator and StringBuffer.append() method.

public class StringConcatenate {
   public static void main(String[] args) {
      long startTime = System.currentTimeMillis();
     
      for(int i = 0;i<5000 i="" p="">         String result = "This is"
            + "testing the"
            + "difference"+ "between"
            + "String"+ "and"+ "StringBuffer";
      }
      long endTime = System.currentTimeMillis();
      System.out.println("Time taken for string"
         + "concatenation using + operator : "
         + (endTime - startTime)+ " ms");
      long startTime1 = System.currentTimeMillis();
     
      for(int i = 0;i<5000 i="" p="">         StringBuffer result = new StringBuffer();
         result.append("This is");
         result.append("testing the");
         result.append("difference");
         result.append("between");
         result.append("String");
         result.append("and");
         result.append("StringBuffer");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Time taken for String concatenation"
         + "using StringBuffer : "
         + (endTime1 - startTime1)+ " ms");
   }
}

Result
The above code sample will produce the following result. The result may vary.

Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 22 ms

-------------------------------------------------------------------------------------------------------------

How to do string concatenation ?

Following example shows concatenation string. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

public class HelloWorld {
   public static void main(String []args) {
      String s = "Hello";
      s = s.concat("word");
      System.out.print(s);
   }
}

Result
The above code sample will produce the following result. The result may vary.

Helloword

How to convert a string totally into upper case?

Following example changes the case of a string to upper case by using String toUpperCase() method.

public class StringToUpperCaseEmp {
   public static void main(String[] args) {
      String str = "string abc touppercase ";
      String strUpper = str.toUpperCase();
      System.out.println("Original String: " + str);
      System.out.println("String changed to upper case: " + strUpper);
   }
}

Result
The above code sample will produce the following result.

Original String: string abc touppercase 
String changed to upper case: STRING ABC TOUPPERCASE 

How to search a word inside a string ?

This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1.

public class SearchStringEmp{
   public static void main(String[] args) {
      String strOrig = "Hello readers";
      int intIndex = strOrig.indexOf("Hello");
     
      if(intIndex == - 1) {
         System.out.println("Hello not found");
      } else {
         System.out.println("Found Hello at index " + intIndex);
      }
   }
}

Result
The above code sample will produce the following result.

Found Hello at index 0

This example shows how we can search a word within a String object

public class HelloWorld {
   public static void main(String[] args) {
      String text = "The cat is on the table";
      System.out.print(text.contains("the"));
   }
}

Result
The above code sample will produce the following result.

true

How to reverse a String?

Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method.

public class StringReverseExample{
   public static void main(String[] args) {
      String string = "abcdef";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("\nString before reverse: "+string);
      System.out.println("String after reverse: "+reverse);
   }
}

Result
The above code sample will produce the following result.

String before reverse:abcdef
String after reverse:fedcba

Example

Following another example shows how to reverse a String after taking it from command line argument

import java.io.*;
import java.util.*;

public class HelloWorld {
   public static void main(String[] args) {
      String input = "tutorialspoint";
      char[] try1 = input.toCharArray();
      for (int i = try1.length-1;i>=0;i--) System.out.print(try1[i]);
   }
}

The above code sample will produce the following result.

tniopslairotut 

How to replace a substring inside a string by another one ?

This example describes how replace method of java String class can be used to replace character or substring by new one.

public class StringReplaceEmp{
   public static void main(String args[]){
      String str = "Hello World";
      System.out.println( str.replace( 'H','W' ) );
      System.out.println( str.replaceFirst("He", "Wa") );
      System.out.println( str.replaceAll("He", "Ha") );
   }
}


Result
The above code sample will produce the following result.

Wello World
Wallo World
Hallo World

How to remove a particular character from a string ?

Following example shows hoe to remove a character from a particular position from a string with the help of removeCharAt(string,position) method.

public class Main {
   public static void main(String args[]) {
      String str = "this is Java";
      System.out.println(removeCharAt(str, 3));
   }
   public static String removeCharAt(String s, int pos) {
      return s.substring(0, pos) + s.substring(pos + 1);
   }
}


Result
The above code sample will produce the following result.

this is Java

How to search the last position of a substring ?

This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.

public class SearchlastString {
   public static void main(String[] args) {
      String strOrig = "Hello world ,Hello Reader";
      int lastIndex = strOrig.lastIndexOf("Hello");
     
      if(lastIndex == - 1){
         System.out.println("Hello not found");
      } else {
         System.out.println("Last occurrence of Hello is at index "+ lastIndex);
      }
   }
}

Result

The above code sample will produce the following result.

Last occurrence of Hello is at index 13

Example

This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.

public class HelloWorld{
   public static void main(String []args) {
      String t1 = "Tutorialspoint";
      int index = t1.lastIndexOf("p");
      System.out.println(index);
   }
}

The above code sample will produce the following result.

9

How to compare two strings in Java ?

Following example compares two strings by using str compareTo (string), str compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the ascii difference of first odd characters of compared strings.

public class StringCompareEmp{
   public static void main(String args[]){
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;

      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

Result
The above code sample will produce the following result.

-32
0
0

String compare by equals()

This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}

The above code sample will produce the following result.

true 

false 

String compare by == operator
public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}

The above code sample will produce the following result.

true

false 

Environment in Java programming

Commonly used examples:-

1. How to compile a java file?

2. How to run a class file?

3. How to debug a java file?

4. How to set classpath?

5. How to view current classpath?

6. How to set destination of the class file?

7. How to run a compiled class file?

8. How to check version of java running on your system?

9. How to set classpath when class files are in .jar file?

How to set classpath when class files are in .jar file?

Following example shows how to set class path when classes are stored in a .jar or .zip file.

c:> java -classpath C:\java\myclasses.jar utility.testapp.main

Result

The above code sample will produce the following result.

Class path set.

How to check version of java running on your system?

Following example shows how to check version of java installed on your system using version argument with java command.

java -version

Result

The above code sample will produce the following result.

java version "1.6.0_13"
Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing)

How to run a class file?

Following example shows how to run a class file from command prompt using java command.

c:\jdk\demoapp>java First 

Result

The above code sample will produce the following result.

Demo application executed.

How to set destination of the class file?

Following example shows how to set destination of the class file that will be created after compiling a java file using -d option with javac command.

c:> javac demo.java -d c:\myclasses 

Result

The above code sample will produce the following result.

Demo application executed.

How to view current classpath?

Following example shows how to view current classpath using echo command.

C:> echo %CLASSPATH%

Result

The above code sample will produce the following result.

.;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip

How to set classpath?

Following example shows how to set classpath.

C:> java -classpath C:\java\DemoClasses utility.demoapp.main

Result

The above code sample will produce the following result.

Class path set.

How to set destination of the class file?

Following example shows how to debug a java file using =g option with javac command.

c:> javac demo.java -g

Result

The above code sample will produce the following result.

Demo.java will debug.

How to set multiple classpath in Java?

Following example shows how to set multiple classpath. Multiple class paths are separated by a semicolon.

c:> java -classpath C:\java\MyClasse1;C:\java\MyClass2 
   utility.testapp.main

Result

The above code sample will produce the following result.

Class path set.

How to Compile a Java file

Following example shows how to compile a java file using javac command.

c:\jdk\demoapp> javac First.java 


Result

The above code sample will produce the following result.

First.java compile successfully.