Posted By:
4 Feb, 2014 11:44 am PST

Code Structure in Java

  Code Structure in Java

 1. What goes in a source file?

 A source code file (with the .java extension) holds one class definition. The class represents a piece of your program.

 Example:

 public class Dog {

}

 2. What goes in a class?

 A class has one or more methods. In the Dog class, the bark method will hold instructions for how the Dog should bark. Your methods must be declared inside a class (in other words, within the curly braces of the class)

 Example:

                  public class Dog

                  {

                  void bark()

                    {

                            }

                       } 

3. What goes in a method? 

Within the curly braces of the method, write your instructions for how that method should be performed. Method code is basically a set of statements, and it can be a function or a procedure. 

Example:

public class Dog {

void bark {

Statement1;

Statement2;

}

}

Conclusion:

·   Put a class in a source file

·  Put methods in a class

·  Put statements in a class. 

Writing a class with a main

Consider the below mentioned program:

 


The main() method is where your program starts running. Running a program means telling the JVM to “Load the class, then start executing its main(). Keep running till all the code in main is finished.”

The main() method must be specified using the following syntax:

public static void main(String[] args)

In the above declaration main is called a method. Please note that method name cannot start with a number, cannot have punctuation characters except dollar and underscore, and cannot be a reserved word of java.

No matter how big your program is(in other words, no matter how many classes your program uses), there’s got to be one main() method per application.

If we do not give main() method in our program, then we are bound to get No such method Error: main error message during compile time.

Java is a case sensitive language. This means that main and Main have different meanings. Please ensure that you type the code exactly. Otherwise unpredictable error and behaviour can result.

 Variables and Primitive Data Types

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

There are two data types available in Java:

·          Primitive Data Types

·         Reference/Object Data Types

For now, we’ll focus only on primitive data types.

Primitive data types

Java provides us with 8 primitive (basic) data types. These are:

1.      Byte (8 bits)

2.      Short (16 bits)

3.     Int(32 bits)

4.      Long (64 bits)

5.      Float (32 bits)

6.      Double (64 bits)

7.      Char (16 bits)

8.      Boolean

 The byte, short, long and int can hold only integer numbers with no fractions(decimal points)

The float and double data types can hold very large numbers, including those with decimal points.

The char data type can hold only single character at a time.

The Boolean data type can hold only true or false – nothing else.

Before we start, please note that every statement in java must end with a semi-colon (;). Also remember that you cannot use a variable before declaring it. For example, look at the following statement:

 X=555;

This is not correct, since the compiler does not know how many bits of memory are required to store the variable x. What we need to do is first declare the data type of the variable x, and then assign a value to it.

To declare a variable, we write something like this:

int x;

x=555;

The first word in the statement int x; is the data type int. Next the name of the variable is written, which is x. Finally we have a semi colon. So a variable is declared using a data type followed by the name of the variable, followed by a semi-colon.Some examples of variable declarations are shown below:

·         int x;//(Declare one variable at a time)

·        int x=5 ;//(Declare and initialize a variable with a value on the same time)

·         int x, y, z;//(Declare more than one variable of the same data type on the same time)

·         int x, y=55, z;//(Initialize some of the variables on one line)

·         int x=88, y=878, z=555;//(Initialize all the variables on the same line)

You can assign value to a variable in three ways:

·         x=12;//(Assign a literal value to the variable)

·         y=x;//(Assign another variable’s value)

·         z=x+y+6;//(Use an expression containing literals or variables or a mixture of both)

 Identifiers

The names we assign to our variables are called identifiers.

The rules for naming identifiers are:

1.     An identifier must start with either a letter, the $ sign, or the underscore (_) character.

2. An identifier cannot start with a number.

    3. The reserved keywords in java should not be used as identifier. Below mentioned keywords should not be used as identifiers as these are reserved words.

 

4.Since java is a case sensitive language, an identifier named student is different from Student.

5. The length of an identifier has no limit. We can define an identifier salary, and another one called Salary_of_the_chairman.However it would not be practical to use very long identifier names in your programs.

Literals

A literal is the value in the source code. For example:

int age=5;

The data type is int, the identifier is age and the literal value is 5.

Methods

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

Creating a Method:

In general, a method has the following syntax:

modifier returnValueType methodName(list of parameters){

// Method body;

}

A method definition consists of a method header and a method body. Here are all the parts of a method:

  • Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.
  • Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.
  • Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
  • Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method Body: The method body contains a collection of statements that define what the method does.

Note: In certain other languages, methods are referred to as procedures and functions. A method with a non-void return value type is called a function; a method with a void return value type is called a procedure.

Example: 

public class Ex0201

{

public static void main(String[] args)

{

System.out.println(“Inside main”);

m2();

m1();

m2();

}

Static void m1()

{

System.out.println(“Inside method m1”);

}

Static void m2()

{

System.out.println(“Inside method m2”);

}

}

 OUTPUT:

                 Inside main

Inside method m2

Inside method m1

Inside method m2

 What happened above? There are four sentences in the main() method. They get executed in turn.

The first sentence results in the text Inside main to be displayed on the screen. The second sentence calls the method m2(). This results in the program executing all the sentences in the m2() paragraph. There is only one sentence here – this sentence displays the text Inside method m2 on the screen.Next, the third sentence in the main() meyhod invokes m1() method which displays Inside method m1 on the screen. Lastly the fourth sentence in the main() method again calls m2() method and displays the output on the screen.

 After each sentence, the next sentence gets executed. Each sentence is a call to some method-yes, System.out.println() is a method; only it is inbuilt to java.

 All the methods are called in the main() method. The main() method is the calling method. The methods invoked are the called methods.

The distinction between calling and called methods is important. A calling method is the method from which other methods are invoked. The methods invoked from the calling methods are called ‘called methods’. Once all the statements inside a called method are executed, the program execution returns back to the next sentence of the calling method.

A method can be both a called method and a calling method.

                                   public class Ex0201

{

Public static void main(String[] args)

{

System.out.println(“Inside main”);

m2();

m1();

m2();

}

static void m1(){

System.out.println(“Inside method m1”);

}

Static void m2(){

System.out.println(“Inside method m2”);

m1();

}

}

 OUTPUT:

                                  Inside main

Inside method m2

Inside method m1

Inside method m1

Inside method m2

Inside method m1

The method m2() contains two statements. The second sentence calls method m1(). Method m2() was called from main(), so m2() is a called method. Method m2() also calls method m1(), so m2() is also a calling method.

 

Using System.out.println()

The System .out.println() method is an extremely useful method that displays content on the screen. What gets displayed depends on what we put in between the parenthesis.

Example:

                                   public class Ex0202

{

public static void main(String [] args)

{

System.out.println(“Inside main”);

}

}

 OUTPUT:

Inside main

 The sentence Inside main gets displayed on the screen. We have seen this in earlier programs. We use double quotes to display strings.

 Make changes in the program as shown below:

                                  public class Ex0202{

public static void main(String [] args)

{

int i;

i=5;

System.out.println(i”);

}

}

OUTPUT:

i

 If you thought the value of the variable i would be displayed, you are incorrect. This is because we have put i in double quotes. For java this means display the stuff in double quotes.

Now, of we remove the double quotes, the program would look like this:

                                   public class Ex0202{

public static void main(String [] args)

{

int i;

i=5;

System.out.println(i);

}

}

OUTPUT:

                      5 

As expected, the value of the variable i is now displayed.

 In order to display the value of the variable, do not include it inside double- quotes. If you include it inside double quotes, the name of the variable will be printed, not its value.

 

 Introducing the System.out.print() method

 

public class Ex0202{

public static void main(String [] args)

{

System.out.print(“Good”);

System.out.println(“Morning”);

}

}

OUTPUT:

                          GoodMorning

 The entry point main() has two sentences. The first one calls the print() method, and the second one calls the println() method.

 After the call to the print() method, the cursor does not move down to the next line.. It remains at the end of the same line.

 When the next sentence with the println() executes, the text gets added from the end of the line itself, and not from the next line. After the println() method, the cursor moves to the start of the next line.

 Another example:

 

public class Ex0203{

public static void main(String[] args){

System.out.print(“Good”);

System.out.print(“ “);

System.out.println(“Morning”);

 

System.out.print(“How”);

System.out.print(“ “);

System.out.print(“are you”);

System.out.println(“?”);

}

}

 OUTPUT:

                  Good Morning

                  How are you?

 

 Using the plus(+) operator inside the System.out.println() method

 

class Ex0204{

public static void main(String[] args)

{

Strings1=”Good”;

String s2=” Morning”;

System.out.println(s1 + s2);

}

}

 OUTPUT:

                 Good Morning

 Let us understand what we have done here. We have defined two variables s1 and s2. These variables are of data type String.A variable of data type String can hold many characters. The String variable s1 has 4 characters Good and the String variable s2 has 7 characters Morning.

 We ask the System.out.println() method to display s1+s2. At this point, you may wonder how java can add two Strings together. Well, the answer is really simple. It does not add the Strings. It joins them. It will join them without adding any spaces in between. The joined result is displayed in the output.

 The plus operation on Strings does not add additional spaces. So, we can extend this to add a space, as shown below:

                                  public class Ex0204{

public static void main(String[] args)

{

Strings1=”Good”;

String s2=” Morning”;

System.out.println(s1 + “ “+s2);

}

}

 OUTPUT:

                     Good Morning

Observe above the space between the two words displayed. Now see how the plus operator.

Let us now see how the plus operator works on some of the primitive data types.

                                  public class Ex0205

{

public static void main(String [] args)

{

int i1;

int i2;

i1=5;

i2=10;

System.out.printlb(i1 + i2);

}

}

 OUTPUT:

                     15

When we have only primitive data types in expressions inside the println() method or the print() method, the value of expression gets evaluated and displayed.

Let us now see what happens if we mix up primitive data types with the String data type in an expression.

                                  public class Ex0206 {

public static void main(String[] args)

{

int i1;

int i2;

String s = “Hello”;

i1=15;

i2 = 10;

System.out.println( i1 + i2 + “ “ + s + “ “ + i1 + i2);

}

}

OUTPUT:

                           25 Hello 1510

 The expression to the left of the first non-primitive data type got evaluated and this result was printed as 25. This was followed by the String data types being joined together giving Hello with surrounding spaces. This stuff to the right was also considered as a String and joined together giving 1510 rather than 25.

Expressions to the left of the first non-primitive will get converted into a value. Expressions to the right of any non-primitive will not get evaluated, unless we use parenthesis (just as in BODMAS).

Another Example

                                                 public class Q0013{

public static void main(String[] args) {

int a;

int b;

int c;

a=5;

b=3;

c= a+b;

System.out.println(a + b +c);

System.out.println("a: " + a + " b: "+ b + " c:" + c);

System.out.println(c + "=" + a + " +" + b);

System.out.println(a + b +"..."+a+b);

System.out.println(a - b + "... " +(a+b) );

System.out.println(a + b - c + "..." + (a * b) );

}

}

 OUTPUT:

                                                 16

a: 5 b: 3 c: 8

8 = 5 + 3

8 ... 53

2 ... 8

0 ... 15

 You cannot use operators other than a plus to the right side of the first non-primitive data type.

 Create a file Ex0207.java as shown below:

                                           public class Ex0207

{

public static void main(String[] args)

{

String s1 = “Good Morning”);

int a;

int b;

a = 5;

b = 3;

System.out.println( a + b + s1 + a – b );

}

}

Save the file and compile it. You’ll see the following compile error

The compiler understands a + b will be added initially to give 8. It will then add s1 to the output to give 8Good Morning. Next it will join 5 to give 8Good Morning5. After that it will realize we want to use minus with a String on one side. This has no meaning, and hence the compiler will not compile this code.

 

 

 

 

 

 

 

 

 

Attachment: table.png


Video s posted for better understanding of the concept.

Was it useful?  



Code Structure in Java

 

 1. What goes in a source file?

 A source code file (with the .java extension) holds one class definition. The class represents a piece of your program.

 Example:

 public class Dog {

}

  1. What goes in a class?

 A class has one or more methods. In the Dog class, the bark method will hold instructions for how the Dog should bark. Your methods must be declared inside a class (in other words, within the curly braces of the class)

 Example:

                  public class Dog

                  {

                  void bark()

                    {

                            }

                       } 

  1.  What goes in a method? 

Within the curly braces of the method, write your instructions for how that method should be performed. Method code is basically a set of statements, and it can be a function or a procedure. 

Example:

public class Dog {

void bark {

Statement1;

Statement2;

}

}

Conclusion:

  • Put a class in a source file
  • Put methods in a class
  • Put statements in a class. 

 

Writing a class with a main

Consider the below mentioned program:

The main(method is where your program starts running. Running a program means telling the JVM to “Load the class, then start executing its main(). Keep running till all the code in main is finished.”

The main() method must be specified using the following syntax:

public static void main(String[] args)

In the above declaration main is called a method. Please note that method name cannot start with a number, cannot have punctuation characters except dollar and underscore, and cannot be a reserved word of java.

No matter how big your program is(in other words, no matter how many classes your program uses), there’s got to be one main() method per application.

If we do not give main() method in our program, then we are bound to get No such method Error: main error message during compile time.

Java is a case sensitive language. This means that main and Main have different meanings. Please ensure that you type the code exactly. Otherwise unpredictable error and behaviour can result.

 


Was it useful?  



Variables and Primitive Data Types

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

There are two data types available in Java:

  1. Primitive Data Types
  2. Reference/Object Data Types

For now, we’ll focus only on primitive data types.

 

Primitive data types

Java provides us with 8 primitive (basic) data types. These are:

  1. Byte (8 bits)
  2. Short (16 bits)
  3. Int(32 bits)
  4. Long (64 bits)
  5. Float (32 bits)
  6. Double (64 bits)
  7. Char (16 bits)
  8. Boolean

 The byte, short, long and int can hold only integer numbers with no fractions(decimal points)

The float and double data types can hold very large numbers, including those with decimal points.

The char data type can hold only single character at a time.

The Boolean data type can hold only true or false – nothing else.

Before we start, please note that every statement in java must end with a semi-colon (;). Also remember that you cannot use a variable before declaring it. For example, look at the following statement:

 X=555;

This is not correct, since the compiler does not know how many bits of memory are required to store the variable x. What we need to do is first declare the data type of the variable x, and then assign a value to it.

To declare a variable, we write something like this:

int x;

x=555;

The first word in the statement int x; is the data type int. Next the name of the variable is written, which is x. Finally we have a semi colon. So a variable is declared using a data type followed by the name of the variable, followed by a semi-colon.Some examples of variable declarations are shown below:

  1. int x;//(Declare one variable at a time)
  2. int x=5 ;//(Declare and initialize a variable with a value on the same time)
  3. int x, y, z;//(Declare more than one variable of the same data type on the same time)
  4. int x, y=55, z;//(Initialize some of the variables on one line)
  5. int x=88, y=878, z=555;//(Initialize all the variables on the same line)

 

You can assign value to a variable in three ways:

  1.  x=12;//(Assign a literal value to the variable)
  2. y=x;//(Assign another variable’s value)
  3. z=x+y+6;//(Use an expression containing literals or variables or a mixture of both)

 

 Identifiers

The names we assign to our variables are called identifiers.

The rules for naming identifiers are:

  1. An identifier must start with either a letter, the $ sign, or the underscore (_) character.
  2. An identifier cannot start with a number.
  3. The reserved keywords in java should not be used as identifier. Below mentioned keywords should not be used as identifiers as these are reserved words.

     

  1. Since java is a case sensitive language, an identifier named student is different from Student.
  2. The length of an identifier has no limit. We can define an identifier salary, and another one called Salary_of_the_chairman.However it would not be practical to use very long identifier names in your programs.

 

Literals

 

A literal is the value in the source code. For example:

 

int age=5;

 

The data type is intthe identifier is age and the literal value is 5.

 


Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud