Java Println with Example and Programs

Println in java: Println() method places the cursor in the next line after printing the current output. So the next output will be printed in the next line. Println is a method present in PrintStream Class where PrintStream class present in Java.io.package.

There are 10 Println methods in PrintStream Class. They are:

1) void println(): Terminates the current line by writing the line separator string.
2) void println(boolean x): Prints a boolean and then terminates the line.
3) void println(char x): Prints a character and then terminate the line.
4)  void println(char[] x): Prints an array of characters and then terminate the line.
5) void println(double x): Prints a double and then terminate the line.
6) void println(float x): Prints a float and then terminate the line.
7) void println(int x): Prints an integer and then terminate the line.
8) void println(long x): Prints a long and then terminate the line.
9) void println(Object x): Prints an object and then terminate the line.
10) void println(String x): Prints a string and then terminate the line.

Example of Println Program:


class PrintlnExample
{
  public static void main(String args[])
 {
  System.out.println("Int statement.");
  System.out.println("Double statement.");
  System.out.println("String statement.");
  System.out.println("Boolean statement.");
  System.out.println("Object statement.");
  System.out.println("Float statement.");
  System.out.println("Long statement.");
  }
}

Output:

Int statement.
Double statement.
String statement.
Boolean statement.
Object statement.
Float statement.
Long statement.

What is the difference between System.out.println() and System.out.print()  in Java?

Println(): Println() method places the cursor in the next line after printing the current output. So the next output will be printed in the next line.

Print():  Print() method places the cursor in the same line after printing the current output. So the next output will also be printed in the same line.
Example using both System.out.println() and System.out.print() methods:

Pyramid Program:
import java.io.*;
import java.util.*;
class PyramidExa1
{
  public static void printPyramid(int n)
  {
  int i, j, k = 2*n-2;
  for(i=0; i<n; i++)
   {
  for(j=0; j<k; j++)
     {
      System.out.print(" ");
     }
   k = k - 2;
    for(j=0; j<=i; j++)
     {
      System.out.print("* ");
     }
      System.out.println();
   }
  }
public static void main(String args[])
{
 Scanner in = new Scanner(System.in);
  System.out.println("Enter a number");
  int n = in.nextInt();
 printPyramid(n);
}
}

Output:
Enter a number
6
          *
        * *
      * * *
    * * * *
  * * * * *
* * * * * *

Explaining in detail about the System.out.println() method :

System: System is the name of the class present in java.lang package.

Out: out is an object of the print-stream class and declared as static in System class. Present in java.lang package.
Println(): println() is a method of the PrintStream class. Present in java.io package.
Share:

Class and Object in Java with Programs and Examples

Class and objects

Why do we need a class in Java?

Java is an object-oriented programming language and represents data in the form of Objects. So in order to create an object, we required a class.

What is a class?

A class is a user-defined data type in Java & is a Structure representing data and logic.

                         (or)

A class is a specification or blueprint or template of an object. A class defines the structure, state, and behavior of mean data & code that can be shared by a set of objects.
The data defined by the class are referred to as member variables or instance variables or attributes.

Syntax to declare a class:

Class<class name>
{
Type instance variable 1;
Type instance variable 2;
…..……………………………….
 Type instance variable N;

Type  methodname1(parameter list)
{
 //body of method//
 }
Type methodname2(parameter list)
 {
    //body of method//
  }
……………………………………
Type methodnameN(parameter list)
 {
    //body of method//
  }
}

Declaring a variable: In Java, all variables must be declared before they can be used. 

Variable declaration is shown below:

Type identifier [ = value], identifier [ = value], ………;

Example:

int a, b, c;       // declares three integers a, b, c;
int i = 1, j = 2, k;   //declares three more integers & initializing i & j;

Class Example:

Class A
{
int i,j;
 Void funA()
{
System.out.println(“FunA() of class A”);
}
}


Understanding the above program:

1) Where “A” is the name of the class.
2) “i& j” are instance variables.
3) “funA()” is the name of the method (or) function.

Q) What is Next?


a) Object.

Why do we need an Object?

In order to load the members of the class(means instance variables, methods) from the byte code to the Ram in the form of executable format and make them available to the program which is under execution. Without using the concept of an object, we can’t load the members of the class from the byte code to the RAM at runtime.

What is an object?

An object is an instance of a class. The memory space which is allocated for the members of a class, dynamically at the runtime can be called an object. 

What is the Instance?

Any dynamic memory allocation can be called an Instance. That is memory space allocated for anything during runtime can be called an Instance.

Syntax to declare Object:

<Class Name>   ClassObjectReference = new <Class Name>();

Object Example for Above program:


A a1 = new A();

Object Example in Java

Ways to create Object: There are various ways to create an Object. The most commonly used and the simple  and easiest way to create Object is using New keyword;

Example:


class Objectexample
{
 public static void main(String[] args)
 {
  Objectexample e = new Objectexample();
  System.out.println("Example of  Object using th new keyword");
  System.out.println("E="+e);
 }
}

Output:
Example of  Object using the new keyword
E = Objectexample@42e922

Types of Objects In Java:

In Java, we have two types of objects based on the referenced variables. They are:

     1)    Referenced (or) Reachable Object.
     2)    In-referenced (or) Un-reachable Object.


Referenced (or) Reachable Object: If an object is pointed by at least one referenced variable, it is called Referenced (or) Reachable object.

Example of Referenced Objetc creation :

ObjectExample e = new ObjectExample();

Program of Referenced (or) Reachable Object:

class Objectexample
{
 public static void main(String[] args)
 {
  Objectexample e = new Objectexample();
  System.out.println("Example of Referenced Object");
  System.out.println("E="+e);
 }
}

Output:

Example of Referenced Object
E = Objectexample@52e922

Un-Referenced (or) Un-Reachable Object: If an object is not pointed by at least one referenced variable, it is called Un-Referenced (or) Un-Reachable object.

Example of Un-Referenced Object creation: new Object Example();

Program of Un-Referenced (or) Un-Reachable Object:

class Objectexample1
{
 public static void main(String[] args)
 {
  new Objectexample1();
  System.out.println("Example of Un-Referenced Object");
  System.out.println("E="+ new Objectexample1());
 }
}

Output:
Example of Un-Referenced Object
E = Objectexample1@52e922

The Five different locations where we can define Objects in Java are:

1) Defining Object has local to a function.
2) Defining Object has an instance variable (or) Non-static member of a class.
3) Defining Object has the parameter of the function.
4) Defining Object has a return data type of the function.
5) Defining Object has a Static variable of the class.

Defining Object has local to a function:

class Demo1
{
int x,y;
void fun1()
{
 x = x + 1;
A a1 = new A();
a1.i = x + 1;
 }
 public static void main(String[] args)
{
A a1 = new A();
Demo1 d1 = new Demo1();
d1.x = 2;
 System.out.println("a1.i = "+ a1.i);
System.out.println("d1.x = "+ d1.x);
 }
}

Output:
a1.i = 0; 
a1.x = 2; 

Defining Object has an instance variable (or) Non-static member of a class.


class Demo2
{
 int x = 1;
A a1 = new A();
public static void main(String[] args)
{
Demo2 d1 = new Demo2();
System.out.println(d1.a1);
System.out.println(d1.a1.i);
d1.a1.funA();
}
}

Output:

A@522e34
0
funA() of A

Defining Object has a parameter of the function.

class Demo3
{
 void fun1(int x)
{
int sq = x*x;
System.out.println("sq = " +sq);
 }
public static void main(String[] args)
{
  Demo3 d1 = new Demo3();
  d1.fun1(5);
   int x = 7;
  d1.fun1(x);
 }
}

Output:

sq = 25
sq = 49

Defining Object has return data type of the function:

class Demo4
{
int getSq(int x)
{
int sq = x * x;
return(sq);
 }
 public static void main(String[] args)
{
 Demo4 d1 = new Demo4();
  int x = d1.getSq(2);
 System.out.println("X = " +x);
 System.out.println(d1.getSq(4));
 int y = d1.getSq(5) + 2;
 System.out.println("Y = " +y);
 }
 }

Output:

x = 4 
 16 
y = 27 

Defining Object has a Static variable of the class.

Program 1:

class Demo5
{
 static int x = 1;
static A a1 = new A();
}

Program 2:

class Demo6
{
public static void main(String[] args)
{
System.out.println(Demo5.x);
System.out.println(Demo5.a1);
System.out.println(Demo5.a1.i);
Demo5.a1.funA();
}
}

Output:

1
A@527e33  
0
funA() of A

Also Read: C String Program with output 
Java Constructor
Share:

Java Polymorphism and Types of Polymorphism in Java with Examples.

Polymorphism in Java

What is Polymorphism in Java?

Defining the multiple functions (or) methods with the same name associated with the same object is called polymorphism.

Types of polymorphism: There are two types of polymorphism. They are:

1) Static polymorphism (or) Compile time polymorphism.

2) Dynamic polymorphism (or) Run-time polymorphism. 




Static polymorphism (or) Compile time polymorphism: 


Defining multiple functions (or) methods with the same name within the same class by changing the data types of the parameters is called as Static polymorphism (or) Compile time polymorphism.

Example using the program:

class StaticPoly
{
 void fun1()
{
 System.out.println("Fun1() of Static Polymorphism");
}
void fun1(int x)
{
 System.out.println("Fun1(int x) of Static Polymorphism");
}
void fun1(int x, int y)
{
 System.out.println("Fun1(int x, int y) of Static Polymorphism");
}
public static void main(String[] args)
{
 StaticPoly p1 = new StaticPoly();
 p1.fun1();
 p1.fun1(1);
 p1.fun1(1,2);
}
}

Output:

Fun1() of Static Polymorphism.
Fun1(int x) of Static Polymorphism.
Fun1(int x, int y) of Static Polymorphism.


Q) What happens in static polymorphism at the time of compilation?

A) In static polymorphism out of multiple methods with the same name the method which has to get executed would be decided at the time of compilation itself. So we call the static polymorphism as compile time polymorphism.

Rules-based on which the Polymorphism works in Java:


1) Whenever a function call is made by passing a value has an argument then JVM searches for the method defined to accept the same data type of the value that is passed.

2) There is a method defined to accept the same data type is existing JVM would not be considered any other method whose parameter value matches to the passed argument. The first priority given to the method defined to accept the same data type of the value we pass has an argument.
3) When a function call is made by passing value has an argument & if there is no method is defined to accept the data type value passed then it may reach to the alternate method.
4) The alternate method is a method where parameter value where we passed matches the argument but the data type of the parameter and the type of the value what we pass has argument would not be same.

Example:

class Poly
{
 void funA(float f)
 {
  System.out.println(" F = " +f);
 }
 void funB(boolean b)
 {
  System.out.println(" B = " +b);
 }
public static void main(String[] args)
 {
  Poly p1 = new Poly();
  p1.funA(10);
 }
}

Output: F = 10.0

Explanation: In the above program the statement “p1.funA(10)” the value “10” is passed to the funA(). At calling position first the value “10” with an integer is not declared so it passed to the void funA(float f). Where float is an alternate method is acceptable to the Integer value we passed.

Dynamic polymorphism (or) Run-time polymorphism: 

Defining functions (or) methods in the subclass with the same name and the same signature of the superclass function are called method overloading (or) Dynamic polymorphism.
Example:
Super class program:
class A
{
 int i,j;
 void funA()
 {
  System.out.println("FunA() of A");
 }
}
Sub class program:
class D extends A
{
 int i,x;
 void funA()
{
 System.out.println("FunA() of class B");
}
public static void main(String[] args)
{
 D b1 = new D();
 b1.funA();
}
}

Output: FunA() of class B.

Explanation: Whenever we are overriding a superclass method in a sub-class the signature and the prototype of the sub-class method must be the same as the super-class method without which where a compilation error would occur. Whatever the rules permitted in static polymorphism are also applicable in method overriding.

Note: In Dynamic polymorphism, multiple methods with the same name & with the same data types of the parameters have to get executed and would be decided dynamically at the runtime-based conditions.

Share:

Java if, if...else Statement (With Examples)

Java if statement: The if statement is a decision-making statement and is used to control the flow of executions of statements. It is the two-way decision statement and is used in conjunction with a Test expression.

Declaration of if statement:

if(test expression)

Explanation: In the above declaration the if statement allows the computer to evaluate the expression first and then depending on whether the value of the expression (means condition) is “True” or “False” it transfers the control to next statement. The program has to follow two paths one for the true condition another for the false condition.



SIMPLE IF STATEMENT
If (test expression)
          {
            statement-block;
           }
           statement-n;

The statement block may be a single statement or a group of statements. If the test expression is true, the statement block will be executed otherwise the statement-block will be skipped and the execution will jump to the statement-n;

Examples using Integers:
class IfExample
 {
  public static void main(String[] args)
  {
    int i = 6, j = 7;
    if(i<j)
    {
 System.out.println("J is Greater then I");
 }
}
}

Output:
J is Greater then I

Example 2:
class IfExample1
{
public static void main(String[] args)
{
 if(8>6)
 {
 System.out.println(" Welcome to TutorialsWeb ");
 }
}
}

Output:
Welcome to TutorialsWeb

else: It is a keyword using this keyword we can create an alternate block for the “if” condition using “else” means always optional, it is recommended to use. When we have an alternate block of “if” condition. When we are working with “if” and “else” only one block will be executed and when if the condition is false then only the else part will be executed.

if …else Statement:

The if …else statement is an extension of the simple if statement. The Syntax of if …else statement is below:

if(test expression)
{
 True-block statement(s);
}
else
{
 False-block statement(s);
}
statement(x);

Explanation: If the Test expression is true, then the true-block statement(s), immediately following the if statements are executed. Or the False-block Statements are executed. In other cases, either true-block (or) False-block will be executed, not both. Then the control is transferred subsequently to the statement-x;


Program:

import java.util. *;
class IfElseExample
{
public static void main(String[] args)
{
 Scanner s1 = new Scanner(System.in);
 System.out.println("Enter I value");
 int i = s1.nextInt();
 System.out.println("Enter J value");
 int j = s1.nextInt();
 if(i > j)
 {
 System.out.println("I is Greater then J");
 }
 else
 {
 System.out.println("J is Greater then I");
 }
System.out.println("Out Of If Else Loop");
}
}

Output:

Enter I value
15
Enter J value
14
I is Greater then J
Out Of If Else Loop

Explanation:

1)    Two integers “I” and “J” are declared. Input values are received for both “I” and “J” using Scanner.
2)     In the above program if else condition statement is used to check whether “I” is greater than “J”.
3)    If “I” is greater than “J”, the Print message “I is Greater then J” is Printed.
4)    If “J” is greater than “I”, the else part will be executed. The Print message “J is Greater then I” is Printed.
5)    After completing the else part the statement-x will be executed.

Nested If…else Statements in Java: When a series of decision is involved then we have to use more than one if…else statement in the nested form shown below.


Explanation: In the above logic of execution if the Test condition-1 is True, it continues to the Test condition-2. If the Test condition-2 is True, the statement-1 will be evaluated other-wise else statement-2 evaluated. If the condition-1 is false, the statement-3 will be executed, and then the control is transferred to the statement-x;



Program:                                                         
import java.util.*;
class NestedIfelseExample
{
 public static void main(String[] args)
 {
 Scanner s1 = new Scanner(System.in);
 System.out.println("Enter the Number");
 int n = s1.nextInt();
 if(n > 0)
 {             
 if(n == 0)
 {
  System.out.println("It is Zero");
 }
 else
 {
 System.out.println("Number is greater than Zero");
 }
 }
 else
 {
 System.out.println("Number is less than Zero");
 }
 }
}

Output:
Enter the Number
12
Number is greater than Zero


The Else If Ladder: Another way of putting ifs together when multipath decisions are involved. A multipath decision of ifs in which the statement associated with each else is an if.  The syntax of Else If Ladder is shown below:


Explanation: In the above Else If Ladder the conditions are evaluated from the top of the ladder to downwards. When the condition found to be True, the statement associated with it is executed and the control is transferred to the statement-x skipping the rest of the ladder. When all the n conditions become False, then the final else with default statement will be executed.

Program:

import java.util.*;
class ElseIfLadderExample
{
 public static void main(String[] args)
 {
 Scanner s1 = new Scanner(System.in);
 System.out.println("Enter the Marks");
 int m = s1.nextInt();
 if(m<50)
    {        
     System.out.println("fail"); 
    } 
    else if(m >= 50 && m < 60)
    { 
     System.out.println("D grade"); 
    } 
    else if(m >= 60 && m < 70)
    { 
     System.out.println("C grade"); 
    } 
    else if(m >=70 && m < 80)
    { 
     System.out.println("B grade"); 
    } 
    else if(m >= 80 && m < 90)
    { 
     System.out.println("A grade"); 
    }
    else if(m >=90 && m < 100)
    { 
     System.out.println("A+ grade"); 
    }
    else
    { 
     System.out.println("Invalid!"); 
    } 
  }
}

Output:

Enter the Marks
66
C grade
Share:

Ads

Search This Blog

  • ()
Powered by Blogger.

Strings in C With Syntax, C String Program with output

Strings in C :  Strings can be defined as the one-dimensional array of characters terminated by a null ('\0'). The difference betwee...

Blog Archive